/* Funciones auxiliares para js no intrusivo */
DEGREES = {
	init : function(clase, generic_content, clase_active) {
		$(clase).each(function(e){
			$(this).click(function(){
        $(generic_content).removeClass(clase_active);
				$("#more_" + this.id).addClass(clase_active);
				return false;
			}); // click
		}); // each
	}
}
	
	function onYouTubePlayerReady(playerId) {
      ytplayer = document.getElementById("myytplayer");
      setInterval(updateytplayerInfo, 250);
      updateytplayerInfo();
      ytplayer.addEventListener("onStateChange", "onytplayerStateChange");
      ytplayer.addEventListener("onError", "onPlayerError");
    }

VIDEOLISTS = {

	init : function(clase) {
		$(clase).each(function(){
			$(this).click(function(e){
				e.preventDefault();
				ytplayer.loadVideoById(this.id,0)
				ytplayer.play();
				return false;
			}); // click
		}); // each
	}
}

function initImage() {
  imageId = 'thephoto';
  image = document.getElementById(imageId);
  setOpacity(image, 0);
  image.style.visibility = 'visible';
  fadeIn(imageId,0);
}

function fadeIn(objId,opacity) {
  if (document.getElementById) {
    obj = document.getElementById(objId);
    if (opacity <= 100) {
      setOpacity(obj, opacity);
      opacity += 10;
      window.setTimeout("fadeIn('"+objId+"',"+opacity+")", 10);
    }
  }
}

function setOpacity(obj, opacity) {
  opacity = (opacity == 100)?99.999:opacity;

  // IE/Win
  obj.style.filter = "alpha(opacity:"+opacity+")";

  // Safari<1.2, Konqueror
  obj.style.KHTMLOpacity = opacity/100;

  // Older Mozilla and Firefox
  obj.style.MozOpacity = opacity/100;

  // Safari 1.2, newer Firefox and Mozilla, CSS3
  obj.style.opacity = opacity/100;
}


FLICKR_GALLERIES = {
	
	init : function(clase) {
		$(clase).each(function(){
			$(this).click(function(e){
				$("#flickr_gallery img").attr("src",  this.href);
				initImage();
				return false;
			}); // click
		}); // each
	}
	
}



var FiltroPregrado = {
  request: function(value) {
    location.href = '/es/oferta-academica/grado-new/filter?campus='+value;
  },
	send: function() {
			$.ajax({ type: "GET", 
							 url: "/filter/grado", 
							 data: $('#form_filtro_pregrado').serialize(),
							cache: false,
							beforeSend: function() { $('#spinner').toggle()},
							complete: function(html){
							    $("#grado_filter_result").html(html.responseText);
							 },
							success: function() { $('#spinner').toggle();}
						})
},
	cambiaSelect: function(value) {
		if (value == '5')
		{
			$('#type_filter_39').attr('disabled','disabled');
			$('#type_filter_40').attr('disabled','disabled');
			$('#type_filter_54').attr('disabled','disabled');
			$('#type_filter_55').attr('disabled','disabled');
			$('#type_filter_56').attr('disabled','disabled');
			$('#type_filter_68').attr('disabled','disabled');
		}
		else
		{
			$('#type_filter_39').attr('disabled','');
			$('#type_filter_40').attr('disabled','');
			$('#type_filter_54').attr('disabled','');
			$('#type_filter_55').attr('disabled','');
			$('#type_filter_56').attr('disabled','');
			$('#type_filter_68').attr('disabled','');
		};
		this.send(value);
	}
};

var FiltroPostgrado = {
	send: function() {


		$.ajax({ type: "GET", 
						 url: "/filter/posgrado", 
						 data: $('#form_filtro_posgrado').serialize(),
						cache: false,
						beforeSend: function() { $('#spinner').toggle()},
						complete: function(html){
						    $("#posgrado_filter_result").html(html.responseText);

						 },
							success: function() { $('#spinner').toggle();}
						})
					}
};

SOCIAL = {

	init : function(clase) {
			$(clase).not($('.degree_desp a')).bind('click', function(e){
			  e.preventDefault();
			  var $item_content = $(this).parent().next();
				if($item_content.css("display") == "none") {
					SOCIAL.reset(clase, $item_content);
					$item_content.slideDown();
					$(this).parents("li:first").addClass("active_list");
				} else {
					SOCIAL.reset(clase);
				}
				return false;
			}); // click
	},
	
	reset: function(clase, $item_content){
		$(clase).each(function(){
				$(this).parent().next().slideUp();
				$(this).parents('ul:first').find('li').removeClass("active_list");
		})
	}

}

COMBO = {

  init : function() {
    var list = $(".content_select_box ul");
    var element = $("a",list)
    $(list).addClass("accesible");
    $(".content_select_box h2").click(function(e){
      e.preventDefault();
      $(list).toggleClass("accesible");
    });
    $(element).click(function(e){
      $(list).addClass("accesible");
      $(".content_select_box h2 a").html($(this).text());
    });
    $(".content_select_box").hover(function(){},function(){
      $(list).addClass("accesible");
    })
}

}

LOGINBOX = {

	init : function(clase, loginbox) {
		$(clase).each(function(e){
			$(this).click(function(){
					$(loginbox).slideToggle();
				return false;
			}); // click
		}); // each
	},
	
	cleared : function(loginbox) {
			$(loginbox).each(function(e){
				$(this).focus(function(){
					$("loginbox").attr("value", ""); 
				return false;
			}); // click
		}); // each
	}

}

HIDDEN_PANORAMIX = {
	
	init : function(clase, panoramio) {
		$(clase).each(function(e){
			$(this).click(function(){
					$(panoramio).css("display", "none");
				return false;
			}); // click
		}); // each
	}
}

// 360
PANORAMIX = {
	field: function(dest, image, pixdeg) {
		var code = "";
		code += "<applet codebase='http://www.uem.es/sites/corporativo/java/pmvr.jar' code='pmvr.class' name='pmvr' archive='http://www.uem.es/sites/corporativo/java/pmvr.jar' width=471 height=100% MAYSCRIPT>"
		code += "<param name='image' value='" + image + "'>"
		code += "<param name='view' value='360'>"
		code += "<param name='pixdeg' value='" + pixdeg + "'>"
		code += "<param name='auto' value='1'>"
		code += "<param name='zoom' value='no'>"
		code += "<param name='delay' value='3000'>"
		code += "Java support is required for panoramic images."
		code += "</applet>"
		
		$(dest).html(code)
	},
	layout: function(dest, image, coordx, coordy) {
		var code = "";
		code += " <applet codebase='http://www.uem.es/sites/corporativo/java/pmvr.jar' code='FloorPlan.class' name='pmvr' archive='http://www.uem.es/sites/corporativo/java/pmvr.jar' width=220 height=100% MAYSCRIPT>"
		code += " <param name='image' value='" + image + "'>"
		code += " <param name='x' value='" + coordx + "'>"
		code += " <param name='y' value='" + coordy + "'>"
		code += " <param name='cLine' value='993333'>"
		code += " <param name='cDot' value='93333'>"
		code += " <param name='gray' value='20'>"
		code += " </applet>"
		
		$(dest).html(code)
	}
}
CAROUSEL = {

	init : function(clase, clase_active) {
		$(clase).each(function(){
			$(this).click(function(){
				CAROUSEL.reset(clase_active);
				$("#list_text" + $(this).html()).addClass(clase_active);
				return false;
			}); // click
		}); // each
	},

		reset: function(clase_active){
			$(".view").removeClass(clase_active);
		}

	}
	
	
var slideShow = {
  wrap: '',
  nav : '',
  visor : '',
  slides : '',
  navitems : '',
  total_slides : '',
  init : function(wrap, visor, nav){
    slideShow.wrap = $(wrap);
    slideShow.nav = $(nav, slideShow.wrap);
    slideShow.visor = $(visor, slideShow.wrap); 
    slideShow.slides = $('ul li', slideShow.visor);
    
    slideShow.slides.not(':first').hide();
    
    //generate nav links
    slideShow.slides.each(function(i){
      slideShow.nav.append('<a href="#" rel="'+i+'">'+(i+1)+'</a>')
    })
    slideShow.navitems = $('a', slideShow.nav);
    
    slideShow.fire();
    slideShow.navitems.eq(0).trigger('click');
    
    slideShow.autoplay();
  },
	fire : function(){
    slideShow.navitems.bind('click', function(e){
      e.preventDefault();
      var $target = $(this)
      if (!$target.hasClass('active')) {
        slideShow.navitems.removeClass('active');
        $target.addClass('active');
        slideShow.slides.filter(':visible').fadeOut('normal', function(){
          // escondemos la info si es un panel .full
          // slideShow.slides.filter('.full').find('> div').css('right', '-420px');
          var s = $(slideShow.slides[$target.attr('rel')]);
                    s.fadeIn('normal');
          // animamos la info si es un panel .full
          // if (s.hasClass('full')) {
          //             s.fadeIn('normal', function(){
          //               setTimeout(function(){
          //                 s.find('> div').animate({'right': '0'}, 'slow', 'swing');
          //               }, 3500);
          //             })
          //           }else{
          //             s.fadeIn('normal');
          //           };

        })
      };
      
      if(e.originalEvent !== undefined) {
        clearInterval(slideShow.slide_timer);
      }
      
    })
  },
  autoplay : function(){
    slideShow.slide_timer = setInterval( function(){
      if ($('.active',slideShow.nav).next().length > 0) {
        $('.active',slideShow.nav).next().trigger('click');
      }else{
        slideShow.navitems.eq(0).trigger('click')
      }
    },9000);
  }
}



var slideShow_videos = {
  wrap2: '',
  nav2 : '',
  visor2 : '',
  slides2 : '',
  navitems2 : '',
  total_slides2 : '',
  init : function(wrap2, visor2, nav2){
    slideShow_videos.wrap2 = $(wrap2);
    slideShow_videos.nav2 = $(nav2, slideShow_videos.wrap2);
    slideShow_videos.visor2 = $(visor2, slideShow_videos.wrap2); 
    slideShow_videos.slides2 = $('ul li', slideShow_videos.visor2);
    
    slideShow_videos.slides2.not(':first').hide();
    
    //generate nav links
    slideShow_videos.slides2.each(function(i){
      slideShow_videos.nav2.append('<a href="#" rel="'+i+'">'+(i+1)+'</a>')
    })
    slideShow_videos.navitems2 = $('a', slideShow_videos.nav2);
    slideShow_videos.navitems2.eq(0).addClass('active')
    
    slideShow_videos.fire()
  },
  fire : function(){
    slideShow_videos.navitems2.bind('click', function(e){
      e.preventDefault();
      var $target2 = $(this)
      if (!$target2.hasClass('active')) {
        slideShow_videos.navitems2.removeClass('active')
        $target2.addClass('active');
        slideShow_videos.slides2.filter(':visible').fadeOut('normal', function(){
          $(slideShow_videos.slides2[$target2.attr('rel')]).fadeIn('normal')
        })
      };
    })
  }
};

function openLightbox(){
	$("#lightbox_bg, #lightbox").fadeIn(200);
	$("#lightbox_bg").css('height', $(document).height());
}

// Devuelve el parametro que se le pase como atributo
function param( name ){
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
    return "";
  else
    return results[1];
}
	
$(document).ready(function() {
  
  
  
	// Lightbox
	if ($("#lightbox").length > 0 && $.flash.available) {
		$("a#open_lightbox").click(function(e){
		  e.preventDefault();
			openLightbox();
		});
		$("#lightbox_bg, a#close_lightbox").click(function(){
			$("#lightbox_bg, #lightbox").fadeOut(200);
		});
	};
	
	
	
	/*
	//sidebar click to call
	var sidebar_clicktocall = $("#click-to-call");
	if (sidebar_clicktocall.length > 0 ){
			var elem = $(".sidebar_click-to-call");
	    var min = elem.offset().top;
	    var didScroll = false;
	    $(window).scroll(function() {
	       didScroll = true;
	    });
	    setInterval(function() {
	       if ( didScroll ) {
	           didScroll = false;
	           var divH = sidebar_clicktocall.height();
	           var scroll = $(window).scrollTop();
	           var max = $(".main_content").height();
	           var margen = scroll - (parseInt(divH)+10);
						 if(scroll>=min && scroll<=max){
	             elem[  ($.browser.msie && $.browser.version == '6.0') ? 'css' : 'animate'  ]({"marginTop":margen+"px"});
	           }else if(scroll<min){
	             elem.css({"marginTop":"0"});
	           }
	       }
	    }, 700);
	}
	*/
	
	if ($.fn.carousel !== undefined) {
	  $('.m_carousel').carousel();
	};
  
  //llamada a equaheights home
  if ($.fn.equalHeights != undefined) {
    $("ul.academic_block:not(.first_academic) > li").equalHeights();
    $("ul.first_academic > li").equalHeights();
    $(".blogs_box ul > li").equalHeights();
    $(".more_info_boxs .degree_blocks").equalHeights();
  };
  
  
  
  // mensajes random en uem-personal
  var uem_personal_random_intros = $('#uem_personal_random_intros h2')
  if (uem_personal_random_intros.length > 0) {
    uem_personal_random_intros.hide();  
    uem_personal_random_intros.eq(Math.floor(Math.random()*uem_personal_random_intros.length)).show();
  };



  slideShow.init('.carrusel_home_postgrado', '.visor', '.nav');
  slideShow_videos.init('.carrusel_videos_horario', '.visor2', '.nav2');
  
  
  
  $(".filter_button").addClass("accesible");
	jQuery.fn.reverse = [].reverse;
	
	jQuery('#carousel').jcarousel();

  if($('#s4').length>0) {
	
		$('#s4') 
		.before('<div id="nav">') 
		.cycle({ 
		    fx:     'fade', 
		    speed:   600, 
				timeout: 12000, 
				next:   '#s4', 
				pause:   1,
				before:  onBefore,
		    pager:  '#nav'
		});
	}

	
	function onBefore() { 
		  var href = this.rel; 
	    $('#home_intro').html('<h2>'+ this.title.split("|")[0] + '</h2>');
			$('#home_intro').append('<p>' + this.title.split("|")[1] + '</p>');
			$('.home_more_info a').attr("href", this.rel);
	}


	SOCIAL.init(".social_box ul li a.flickr_box");
	SOCIAL.init(".list a");
	LOGINBOX.init("#login", ".login_box");
	LOGINBOX.cleared("#username");
	VIDEOLISTS.init(".video_lists li a");
	FLICKR_GALLERIES.init(".flickr_gallery");
	HIDDEN_PANORAMIX.init("a.thickbox", ".instalations_box" );
	COMBO.init();
  $(".step_carousel").infiniteCarousel();

	
	$('.rounded_corners').reverse().each(function(){
			$(this).html($(this).html() + '<span class="rc ne"></span><span class="rc nw"></span><span class="rc se"></span><span class="rc sw"></span>');
		});
		
		$('.scroll_lists').jScrollPane({
  		showArrows: true,
  		scrollbarWidth: 25
  	});

  	$(".carousel").infiniteCarousel();
  	
  	
  	
  	
  	
  	// /**
  	//     * validar formulario 
  	//     *--------------------------------------------------------------------------*/
  	//     $("#subhome_box .register_comunity form").validate({
  	//       success: function(label) {
  	//         var message = '&nbsp;'; // set &nbsp; as text for IE
  	//         label.closest("p").removeClass("error");
  	//         $("span.error", label.closest("p")).remove();
  	//         label.html(message).addClass("valid");
  	//       },
  	//       highlight: function(element, errorClass) {
  	//         $(element).closest("p").addClass("error");
  	//         $("span.error", $('#'+element.id).closest("p")).remove();
  	//         if(element.id == 'legal'){
  	//           $(element).parent().append('<span class="error">Campo Obligatorio</span>')
  	//         }
  	//       },
  	//       rules: {
  	//         name: {
  	//           required: true
  	//         },
  	//         email: {
  	//           required: true,
  	//           email: true
  	//         },
  	//         password: {
  	//           required: true
  	//         },
  	//         password_repeat: {
  	//           required: true
  	//         },
  	//         title: {
  	//           required: true
  	//         },
  	//            address: {
  	//           required: true
  	//         },
  	//         legal: {
  	//           required: true
  	//         }
  	//       },
  	//       messages: {
  	//         name: {
  	//           required: "Campo Obligatorio"
  	//         },
  	//         
  	//         email : {
  	//           required: "Campo Obligatorio",
  	//           email:"Campo Obligatorio"
  	//         },
  	//         password : {
  	//           required: "Campo Obligatorio"
  	//         },
  	//         password_repeat : {
  	//           required: "Campo Obligatorio"
  	//         },
  	//         title : {
  	//           required: "Campo Obligatorio"
  	//         },
  	//         address : {
  	//           required: "Campo Obligatorio"
  	//         },
  	//         legal : {
  	//           required: "Campo Obligatorio"
  	//         }
  	//       }
  	//       
  	//       
  	//     });





        $("#fp_courses table.subjects_plan tbody tr:even, #content #fp_courses .aside_fp table.schedules tbody tr:even").addClass('zebra');


});


/**
* Carousel (to hack in tck library)
*--------------------------------------------------------------------------*/

$.fn.infiniteCarousel = function () {

    function repeat(str, num) {
        return new Array( num + 1 ).join( str );
    }

	var $selector = this.selector,
		$roundtrip = "";
  
    return this.each(function () {
        var $wrapper = $('> div', this).css('overflow', 'hidden'),
            $slider = $wrapper.find('> ul'),
            $items = $slider.find('> li'),
            $single = $items.filter(':first'),
            
            singleWidth = $single.outerWidth(), 
            visible = Math.ceil($wrapper.innerWidth() / singleWidth), // note: doesn't include padding or border
            currentPage = 1,
            pages = Math.ceil($items.length / visible);            


        // 1. Pad so that 'visible' number will always be seen, otherwise create empty items
        if (($items.length % visible) != 0) {
            $slider.append(repeat('<li class="empty" />', visible - ($items.length % visible)));
            $items = $slider.find('> li');
        }

        // 2. Top and tail the list with 'visible' number of items, top has the last section, and tail has the first
        $items.filter(':first').before($items.slice(- visible).clone().addClass('cloned'));
        $items.filter(':last').after($items.slice(0, visible).clone().addClass('cloned'));
        $items = $slider.find('> li'); // reselect
        
        // 3. Set the left position to the first 'real' item
        $wrapper.scrollLeft(singleWidth * visible);
        
        // 4. paging function
        function gotoPage(page) {

			var $paginator = $($selector + "-paginator a");
			if (page == 0) { page = $paginator.length};
			$paginator.removeClass("active");
			if($paginator.length <= (page-1)) {
				$($paginator[0]).addClass("active");
			} else {
				$($paginator[page-1]).addClass("active");
			};
	
            var dir = page < currentPage ? -1 : 1,
                n = Math.abs(currentPage - page),
                left = singleWidth * dir * visible * n;
            
            $wrapper.filter(':not(:animated)').animate({
                scrollLeft : '+=' + left
            }, 800, function () {
                if (page == 0) {
                    $wrapper.scrollLeft(singleWidth * visible * pages);
                    page = pages;
                } else if (page > pages) {
                    $wrapper.scrollLeft(singleWidth * visible);
                    // reset back to start position
                    page = 1;
                } 

                currentPage = page;
            });                
                        
			return false;
        }
        
        $wrapper.after('<a class="arrow back">&lt;</a><a class="arrow forward">&gt;</a>');
        
        // 5. Bind to the forward and back buttons
        $('a.back', this).click(function () {
			GoGoGo();
            return gotoPage(currentPage - 1);                
        });
        
        $('a.forward', this).click(function () {
			GoGoGo();
            return gotoPage(currentPage + 1);
        });
        
        // create a public interface to move to a specific page
        $(this).bind('goto', function (event, page) {
            gotoPage(page);
        });
		
		// has paginator?
		$($selector + "-paginator a").click(function(e){
			e.preventDefault();
			GoGoGo();
			gotoPage(parseInt($(this).html()));
		});
		$($selector + "-paginator a:first").addClass("active");
		
		
		function GoGoGo() {
		    if($($selector).attr("rel")!="static"){
    			clearInterval($roundtrip);
    			$roundtrip = setInterval("$('a.forward').trigger('click')",8000);
		    }
		};
		
		GoGoGo();
    });  
};


