/* 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).each(function(e){
			$(this).click(function(){
				if($("#social_" + this.id).css("display") == "none") {
					SOCIAL.reset(clase);
					$("#social_" + this.id).slideDown();
					$(this).parents("li:first").addClass("active_list");
				} else {
					SOCIAL.reset(clase);
				}
				return false;
			}); // click
		}); // each
	},
	
	reset: function(clase){
		$(clase).each(function(){
				$("#social_" + this.id).slideUp();
				$(".degree_lists 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);
		}

	}
	
$(document).ready(function() {
  $(".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();

});


/**
* 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();
    });  
};


