//miramos idioma
var lang = {
    en: ['[show more]','[show less]', 'Remove', 'Learn more &gt;', 'Close ', 'Edit', 'Saved!', 'Your message was sent.'],
    es: ['[mostrar]','[ocultar]', 'Quitar', 'Más información &gt;', 'Cierra', 'Editar', 'Guardado!', 'Tu mensaje se ha enviado correctamente.'],
    de: ['[zeigen]','[verbergen]', 'Entfernen', 'Mehr Information &gt;', 'Schliessen', 'Bearbeiten', 'Gespeichert!', 'Deine Nachricht wurde gesendet.']
};

var lang_join = {
    en: ['Your email address appears to be valid. Thanks!','This email is already registered.','The email provided does not appear to be valid.'],
    es: ['Tu email parece ser válido. Gracias!','Este email ya esta siendo usado.','El email no es valido.'],
    de: ['Deine E-Mail-Adresse scheint g&uuml;ltig zu sein. Danke!','Diese E-Mail-Adresse wurde schon registriert.','Diese E-Mail-Adresse scheint nicht g&uuml;ltig zu sein.']
};

var lang_upload = {
    en: ['Content uploading', 'Speed:', 'Percentage:', 'Estimated time:',' seconds remaining.', ' minute(s) remaining.',  ' hour(s) remaining.'],
    es: ['Enviando contenido', 'Velocidad', 'Porcentaje completado:', 'Tiempo estimado:', ' segundos.', ' minuto(s).',  ' hora(s).'],
    de: ['Upload l&auml;uft', 'Geschwindigkeit:', 'Prozent hochgeladen:', 'Fertig in ca.',' Sekunde(n) fertig.', ' Minute(n) fertig.',  ' Studen(s) fertig.']
};

var send_to = {
    en: ['Send to Teachers', 'Send Invitations'],
    es: ['Enviar a Profesores', 'Enviar invitaciones'],
    de: ['An Lehrer senden', 'Einladung senden']
};

var i18n = {
    '[show more]': {
        en: '[show more]',
        es: '[mostrar]',
        de: '[zeigen]'
    },
    '[show less]': {
        en: '[show less]',
        es: '[ocultar]',
        de: '[verbergen]'
    }
};

var _tmp={};

//estilos Capa Loading
var loadingLayer = function(text) {
    var textLoading = text || '';  // Default no text!
    return {
    css: {
            'border-radius': '10px',
            '-moz-border-radius': '10px',
            '-webkit-border-radius': '10px',
            opacity: '.8',
            filter: 'alpha(opacity=80)',
            border: '10px solid #555',
            color: '#333',
            padding: '15px'
        },

        overlayCSS: {
            backgroundColor: '#000',
            opacity: '0.4'
        },

        applyPlatformOpacityRules: false,
        message: '<div style="text-align: center; font-size: 20px; line-height:20px; font-weight: bold;"><img src="/scimg/loading.gif" style="vertical-align: middle" />' + textLoading + '</div>'
    };
};

var loadingLayerFind = function(text) {
    var textLoading = text || '';  // Default no text!
    return {
    css: { "border": "none"},
    overlayCSS: {backgroundColor: 'white', opacity: "0"},
    message: '<div style="text-align: center; font-size: 20px; line-height:20px; font-weight: bold;"><img src="/scimg/loading.gif" style="vertical-align: middle" />' + textLoading + '</div>'
    };
};

//On load
$(function(){
    $('#academy.webclass #timeEntry').timeEntry({show24Hours: true});

    langActive = $('html').attr('lang');

    adminInterface();   // Admin Interface for events etc.
    toogles(); //generica
    loginSlide(); //generica
    misc(); //genericas
    tooltips(); //generica
    autoAjax(); //video o doc
    videoInfo(); //video
    tabs(); //en varios sitios
    quickLogin(); //en view Doc o view Video
    rating(); //en videos y docs
    uploader(); //al subir video
    mensajes(); //en profile
    editInPlace(); //en academy
    changeImageAcademy(); //en academy
    addFavorite(); //en academy
    validateEditVideo(); //en edit video
    tabsProfile.init(); // en profile
    validate_signup(); //en signup
    tags_suggest(); //en join
    relationships(); //en profile
    sendInternalMail(); //en academy (llamo a la funcion tabsProfile.sendMessage ya que hace lo mismo)
    enrollCourse(); //en academy.courses
    toggleCourseDescr(); //en academy.courses
    courseMaterial(); //en academy.courses
    courseResources.init(); //en academy.webclass
    inviteStudents.init(); //en academy.webclass y academy.courses
    invitations.init();
    importMails(); //en academy.webclass
    createCourse.init(); //en academy.courses
    premium.init(); //en premium
    addContent.init(); // en #add-content
    inviteContactsbyEmail.init(); // en invite contacts
    browseTruncate(); //en course browse
    paypal(); //en create course o create webclass (o edit)
    webclassSecret.init(); //en live web classes
    edit.init(); //en edit content (video and documents)
    facebookInvite(); // En webclasses / courses
    open_meeting(); // En academy meeting
    open_webclass();
    credentials.init(); //en academy > credentials
    community(); //bubbles en community
    ViewMediaBubbles.init(); //en viewMedia
    languages(); // footer
    timeZone();
    contentFolders();
//    courseProgram.init();
//    courseProgramUpload();
    requestinfoUtils();
    courseUtils();
    webclassesUtils();
    wall();
    learningpath();
    discussions();
    webclasses_list();
    students_list();
//    materials_list();
//    course_program();
    alertSystem();
    admissionUtils.init();

    uploadContent(); //en add content (upload)
    login(); //en toooodos sitios
    dashboard();
    paypal_plan.init();
    onlinetest.init();
    //shareIt();
});

$.postJSON = function(url, data, callback) {
    $.post(url, data, callback, "json");
};

//para hacer un alert del objeto
$.fn.debug = function() {
  return this.each(function(){
       if(window.console) {
        console.debug(this);
      } else {
         alert(this);
      }
  });
};

// Para votar
/*
$("#cast_my_vote").sexyVote({fn: function(e, score) {
    var reference = $('#reference').val();
    var application = $('#application').val();
    $.postJSON('/rating', {application: application, reference: reference, rate: score}, function(data){
    });
}});
*/

//para debugear con mensajes
$.log = function(message) {
  if(window.console) {
     console.debug(message);
  } else {
     alert(message);
  }
};

//plugin para aplicar en textarea/inputs para que cuando tenga el foco se elimine el contenido
$.fn.autoClean = function() {
    return this.filter('input, textarea').each(function(){
        var $this = $(this);
        $this
            .attr('default',$this.val())
            .focus(function(){
                if ( $this.attr('id') == 'terms' ) {
                    if ($this.val() == $this.attr('title') ) $this.val('');
                } else {
                    if ($this.val() == $this.attr('default') ) $this.val('');
                }
            })
            .blur(function(){
                if ($this.val() == '') $this.val($this.attr('default'));
            });
  });
};

/*
Encoding / decoding UTF8 in javascript
*/
function encode_utf8( s )
{
  return unescape( encodeURIComponent( s ) );
}

function decode_utf8( s )
{
  return decodeURIComponent( escape( s ) );
}

// Borrar " y ' de un string
function delquote(str){return (str=str.replace(/["']{1}/gi,""));}


/*
Para obtener un listado de eventos asociados a un elemento concreto

uso:
    // List all onclick handlers of all anchor elements:
    $('a').listHandlers('onclick', console.info);

    // List all handlers for all events of all elements:
    $('*').listHandlers('*', console.info);

    // Write a custom output function:
    $('#whatever').listHandlers('click',function(element,data){
        $('body').prepend('<br />' + element.nodeName + ': <br /><pre>' + data + '<\/pre>');
    });
*/
$.fn.listHandlers = function(events, outputFunction) {
    return this.each(function(i){
        var elem = this,
            dEvents = $(this).data('events');
        if (!dEvents) {return;}
        $.each(dEvents, function(name, handler){
            if((new RegExp('^(' + (events === '*' ? '.+' : events.replace(',','|').replace(/^on/i,'')) + ')$' ,'i')).test(name)) {
               $.each(handler, function(i,handler){
                   outputFunction(elem, '\n' + i + ': [' + name + '] : ' + handler );
               });
           }
        });
    });
};

//validacion de mail
function validarmail(email){
    return (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(email));
}

// Admin Interface for events, etc.
function adminInterface() {
    $('.select-invitation-type').live("click", function() {
        $$ = $(this);
        if ($$.hasClass('orange-button-selected')) return false;
        $('.select-invitation-type').removeClass('orange-button-selected').addClass('orange-button');
        $$.addClass('orange-button-selected');
        if ($$.attr('rel') == 'I') {
            $('#text-invite-teachers').hide();
            $('#text-invite-students').show();
            $('div.orange-button-bigfoot').html($('#text-invite-students').html());
            $('.only_show_for_students').show();
            $('.only_show_for_teachers').hide();
            $('#invite-students > li > a').click();
        }
        if ($$.attr('rel') == 'W') {
            $('#text-invite-students').hide();
            $('#text-invite-teachers').show();
            $('div.orange-button-bigfoot').html($('#text-invite-teachers').html());
            $('.only_show_for_students').hide();
            $('.only_show_for_teachers').show();
            $('#invite-students > li > a').click();
        }
        $('#invitation-type').val($$.attr('rel'));
    });

    $(".adminaction").live("click", function() {
        //var type = $('body').attr('class');
        var type  = $("#module").val();
        var state = $(this).attr('rel').substring(0,1);
        var user  = $(this).attr('rel').substring(1);
        /* State can be:
            A   - Admit to attendance or remove admin
            M   - Make Admin
            I   - Invited
            S   - Pending Payment - Admit
            */
        var id_reference = "";
        if (type == "events") {
            id_reference = $("#event_reference").val();
        }
        else if (type == "groups") {
            id_reference = $("#group_reference").val();
        }
        else if (type == "courses") {
            id_reference = $("#course_reference").val();
        }
        else if (type == "webclasses") {
            id_reference = $("#reference").val();
        }
        $.post('/' + type + '/confirm_enrollment', { username: user, state: state, reference: id_reference }, function(data) {
            if (data == "ok") {
                // Update information immediately
                switch (state) {
                    case "O":   // Admit student and put it pending payment
                        $("#span-"+user+" span.liketoattend").css("display","none");
                        $("#spanpay-"+user+" span.paypending").css("display","inline");
                        break;
                    case "A":   // Admit student or remove admin
                        $("#span-"+user+" span").css("display","none");
                        $("#span-"+user+" span.attending").css("display","inline");
                        $("#span-deletestudent-"+user).css("display", "inline");
                        break;
                    case "M":   // Make Admin
                        $("#span-"+user+" span").css("display","none");
                        $("#span-"+user+" span.admin").css("display","inline");
                        break;
                    case "K":
                    case "D":   // Dismiss
                        $("#facebox .delete .delcontent div").css("display", "none");
                        $("#facebox .delete .delcontent #returnmessage").css("display","block");
                        $("#reloadpage").val("1");
                        setTimeout(function(){ $(document).trigger('close.facebox'); }, 2000);
                        break;
                    case "I":   // invite
                        $("#span-"+user+" span.invitationignored").css("display","none");
                        $("#span-"+user+" span.usernotresponded").css("display","inline");
                        break;
                    case "W":   // invite
                        $("#span-"+user+" span.coteachinvitationignored").css("display","none");
                        $("#span-"+user+" span.notresponded").css("display","inline");
                        break;
                }
            }
        });
        return false;
    });

    $(".adminconfirmpayaction").live("click", function() {
        var user  = $(this).attr('rel');
        $.post('/admission/payconfirmation', {username: user}, function(fb) { $.facebox(fb); });
    });

    $(".adminpayaction").live("click", function() {
        var type  = $("#module").val();
        var state = $(this).attr('rel').substring(0,1);
        var user  = $(this).attr('rel').substring(1);
        var id_reference = "";
        if (type == "events") {
            id_reference = $("#event_reference").val();
        }
        else if (type == "groups") {
            id_reference = $("#group_reference").val();
        }
        else if (type == "courses") {
            id_reference = $("#course_reference").val();
        }
        else if (type == "webclasses") {
            id_reference = $("#webclass_reference").val();
        }
        $(document).trigger('close.facebox');

        if (state == 'A') {
            $.post('/admission/confirmpayment', { username: user, application: type, reference: id_reference }, function(data) {
                if (data == "ok") {
                    $("#span-"+user+" span").css("display","none");
                    $("#span-"+user+" span.attending").css("display","inline");
                    $("#span-deletestudent-"+user).css("display", "inline");

                    $("#spanpay-"+user+" span.payconfirmation").css("display","none");
                    $("#spanpay-"+user+" span.payconfirmed").css("display","inline");
                }
            });
        }
        if (state == 'X') {
            $.post('/admission/cancelpayment', { username: user, application: type, reference: id_reference }, function(data) {
                if (data == "ok") {
                    $("#spanpay-"+user+" span.payconfirmation").css("display","none");
                    $("#spanpay-"+user+" span.paycanceled").css("display","inline");
                }
            });
        }
        return false;
    });

    $(".block-user").live("click", function() {
        var user  = $(this).attr('rel');
        $.post('/admission/blockuser', {username: user, application: $("#module").val()}, function(fb) { $.facebox(fb); });
        return false;
    });

    $("#adm-block-user").live("click", function() {
        var type  = $("#module").val();
        var user  = $(this).attr('rel');
        var id_reference = "";
        if (type == "events") {
            id_reference = $("#event_reference").val();
        }
        else if (type == "groups") {
            id_reference = $("#group_reference").val();
        }
        else if (type == "courses") {
            id_reference = $("#course_reference").val();
        }
        else if (type == "webclasses") {
            id_reference = $("#reference").val();
        }
        $(document).trigger('close.facebox');
        $.post('/admission/block', { username: user, application: type, reference: id_reference }, function(data) {
            if (data == "ok") {
                $('#maintable-'+user).fadeOut('fast');
            }
        });
        return false;
    });

}

//para mostrar y ocultar
function toogles(){
    //links sociales
    $('#share-this').hide();
    $('.share').toggle(
        function(){
            $('#share-this').show();
        },
        function(){
            $('#share-this').hide();
        }
    );

    $('a[rel*=facebox]').facebox();
}

//desplegable login
function loginSlide(){
    $("#sign").click(function(){
	    var pos = $("#sign").offset();
	    $("#signin_menu").css( "left", (pos.left - $("#signin_menu").width() + 12) + "px" );
	    $('#signin_menu').toggle();
		$('#username').focus();
	    return false;
	});
	
	$('#signin_menu').click(function(e){
	    e.stopPropagation();
	});
	$(document).click(function(){
		$('#signin_menu').hide();
	});

	$('#signin_submit').bind('click', function(){
		var button_login = $(this);
		$('.wait_overlay').css('display','block');
		button_login.css('background','url("/scimg/spinner.gif") no-repeat scroll 6px 4px #1D7EC3').css('cursor', 'wait');
		var academy = '';
		if ($('#academy_id').length) {
			academy = $('#academy_id').val();
		}
	    $.post('/join/boxlogin',{username:$('#username').val(), password:$('#password').val(), remember_me: $('#remember').attr('checked'), academy: academy},function(data){
	        if (data.action == 'reload'){
				// si es un signup normal nos vamos a la pantalla de welcome, si hemos pulsado un boton de paypal lanzamos paypal
				if ($('#after-login').length) {
					button_login.css('background','#1D7EC3').css('cursor', 'pointer');
					$('#navigation').remove();
					$('#signin_menu').hide();
					var action = $('#after-login').val();
					if (action == 'AC-BUTTON') {
				        $.facebox.settings.opacity = 0.3;
				        $.facebox.settings.modal = true;
				        $.facebox( { div: '#academy-type-a' } );					
					} else {
                if ($('#facebox #pay_month_year').length>0) {
                        $('#facebox #pay_month_year').remove();
                }
						var plan = $('#'+action).attr('rel');
		            	var prices = $('#'+action).attr('value');
		            	$('#price_per_year').html(prices.split('/')[1]);
		            	$('#price_per_month').html(prices.split('/')[0]);
		            	$('#plan_selected').val(plan);
		            	$('#payment_option').attr('checked','checked');
		            	$.facebox.settings.opacity = 0.3;
		            	$.facebox.settings.modal = true;
		            	$.facebox( { div: '#pay_month_year' } );
					}
				}
				else {
					window.location.reload(true);
				}
	        }
	        else if (data.action == 'navigate'){
				window.location = data.url;
			}
			else
	        {
				$('.wait_overlay').css('display','none');
				button_login.css('background','#1D7EC3').css('cursor', 'pointer');
	            $('#username').select().focus();
	            $('#alert').fadeIn();
	            setTimeout("$('#alert').fadeOut();",3000);
	        }
	    }, 'json');
	    return false;
	});	
	
    $('#resend_password_link').click( function(){
        $('#signin_form').hide();
        $('#lostPassword').show();
        return false;
    });

    $('#recover_cancel').click( function(){
        $('#signin_form').show();
        $('#lostPassword').hide();
		$('#username').focus();
        return false;
    });

    $("#recover").click(function () {
        $.post('/join/recover', { email: $('#emailForgot').val()} ,function(data){
            $('body').prepend('<div class="alertSystem" id="alertSystem">'+data.msg+'</div>');
            alertSystem();
            if (data.action == 'ok') {
                $('#signin_form').show();
                $('#lostPassword').hide();
				$('#username').focus();
            }
        }, "json");
        return false;
    });
	
}

//truncate en course browse / webclass browse
var browseTruncate = function(){
    langActive = $('html').attr('lang');

    $('#main-extended.browse ul.browse li .col-center > p').livequery(function(){
        $(this).not('.subtitle').jTruncate({
            length: 180,
            moreText: i18n['[show more]'][langActive],
            lessText: i18n['[show less]'][langActive]
        });
    });
    $('#background').livequery(function(){
        $(this).not('.subtitle').jTruncate({
            length: 150,
            moreText: i18n['[show more]'][langActive],
            lessText: i18n['[show less]'][langActive]
        });
    });
    $('#good').livequery(function(){
        $(this).not('.subtitle').jTruncate({
            length: 150,
            moreText: i18n['[show more]'][langActive],
            lessText: i18n['[show less]'][langActive]
        });
    });
    $('#intereses').livequery(function(){
        $(this).not('.subtitle').jTruncate({
            length: 150,
            moreText: i18n['[show more]'][langActive],
            lessText: i18n['[show less]'][langActive]
        });
    });
    $('#academy.events .event_title #description').livequery(function(){
        $(this).jTruncate({
            length: 260,
            moreText: i18n['[show more]'][langActive],
            lessText: i18n['[show less]'][langActive]
        });
    });

    $('.user-text').livequery(function(){
        $(this).jTruncate({
            length: 180,
            newline: false,
            moreText: i18n['[show more]'][langActive],
            lessText: i18n['[show less]'][langActive]
        });
    });
};

function misc(){
    //autoclean de inputs

    $('.autoclean').autoClean();

    //añade la zona horaria a un input hidden
    if (document.getElementById('timezone')){
        var $timezone=new Date().getTimezoneOffset()/(-60);
        document.getElementById('timezone').value = $timezone;
    }
    $('textarea.expanding').elastic();
}

function tooltips(){
        $('.pag-next,.pag-prev,.tooltip').tooltip({
            track: true,
            delay: 0,
            showURL: false,
            showBody: " - ",
            fade: 250
        });
        $('.moodle_private').tooltip({
            bodyHandler: function() {return "Only you and students you invite can can see this web class information.";}
        });
}

//toggle de info de videos (etiquetas, tags...)
function videoInfo(){
    if ($('#viewMedia').length == 0) return;

    $('#video_information').hide();
    var cut = $('#video_description').text().length;

        if (cut > 90){ //truncamos
            $('#video_description').jTruncate({
                length: 80,
                moreText: lang[langActive][0],
                lessText: lang[langActive][1],
                moreAni: "fast",
                lessAni: "fast"
            });

            $('a.truncate_more_link').toggle(function(){
                $('#video_information').slideDown();
            },function(){
                $('#video_information').slideUp();
            });
        }
        else{ //ocultamos solo etiquetas, fecha y duracion
            $('#video_description').append('<div class="clearboth"><a class="truncate_more_link" href="#">' + lang[langActive][0] + '</a></div>');
            $('a.truncate_more_link').live('click',function(){
                if ($('#video_information').is(':hidden')){
                    $('#video_description .truncate_more_link').text(lang[langActive][1]);
                    $('#video_information').slideDown();
                }
                else{
                    $('#video_description .truncate_more_link').text(lang[langActive][0]);
                    $('#video_information').slideUp();
                }
            });

        }

    $('.addvideotomylibrary').click(function(){
        $.facebox( { div: '#add_to_my_library' } );
        return false;
    });

    $('#facebox #add_to_my_library_button').live('click',function(){
        $.get('/content/add_mylibrary'+$(this).attr("rel"), function(data){
            $('#facebox #add_step_one').hide();
            $('#facebox #add_ok').show();
            setTimeout(function() { $(document).trigger('close.facebox'); }, 2000);
        });
    });
}

/*
    para realizar llamadas ajax mediante la clase "ajaxfied" en enlaces o formularios
    Uso: <a href="controller.php?id=2" rel="ajaxfied videoOption">enlace</a> || donde mediante ajaxfied generamos la consulta en ajax y videoOption es el
                                                                                id del div donde descargamos lo devuelo por el php
*/
function autoAjax(){
    $('a[rel^=ajaxfied]').live('click',function(){
        var $$ = $(this);
        $( "#"+$$.attr('rel').split(' ')[1] ).load( $$.attr('href'), function(data){
            location.href = '#' + $$.attr('rel').split(' ')[1]; //nos desplazamos hacia el contenido cargado
        } );
        return false;
    });

    $('form[rel^=ajaxfied]').live('submit',function(){
        var $$ = $(this);
        $( "#" + $$.attr('rel').split(' ')[1] ).load( $$.attr('action') + $$.serialize() ); //el action debe acabar en ? o + (si ya hay otro parametro en la url)
        return false;
    });

    //cancelar enviar a amigo
    $('#sendFriend-cancel,#flag-cancel').live('click',function(){
        $('#videoOption').html(''); //vaciamos
        return false;
    });
}

/* genera el comportamiento de las pestañas */
function tabs(){
    /*if ($('#viewMedia #sidebar.doc ul.tabs-nav').is('ul')){
        $('#viewMedia #sidebar.doc ul.tabs-nav').tabs();
    }*/
    //poltergeist: el caso de arriba debería funcionar, pero no es así en la pagina de video
   // $('#viewMedia ul.tabs-nav').tabs();

    //tabs (en realidad no son tabs) para videos - Taboola
    $('#viewMedia #sidebar.video .tabs-nav a').click(function(){
        $('#viewMedia #sidebar.video .tabs-nav li').removeClass('ui-tabs-selected');
        $(this).parent().addClass('ui-tabs-selected');
        trc_selectList($(this).attr('id'));
        return false;
    });
	
	// BY ALEX
	$("#sidebar").tabs();
}

//caja login
function quickLogin(){
    if ($('.login-required')){
        if ($('#viewMedia .login-required').is('a')){ //si estoy en view documents mostramos una caja de login
            $('.login-required').click(function(){
                var el = $('#player-login');
                if (el.is(':visible')) $('h3',el).effect('highlight',{},1000);
                else el.fadeIn();

                $('input#usernameLogin',el).focus();

                //boton cerrar
                $('.close',el).click(function(){
                    $(el).slideUp();
                    return false;
                });

                return false;
            });
        }
        else{ //en la mayoría de casos de rating, desplegamos la capa superior
            $('.login-required').click(function(){
                $('#login').slideDown('fast');
                $('#uLogin').focus();
                return false;
            });
        }
    }
}

//para votar videos o documentos, en el .numberRating tiene que haber un archivo rel="videos||documents"
function rating(){
    if ($('.numberRating')){
        $('.numberRating a').not('.login-required').click(function(){
            if($(this).parents('#classRating').attr('rel') == 'content'){
                $('#classRating').load('/' + $(this).parents('#classRating').attr('rel') + '/rate?id='+ $(this).parents('.numberRating').attr('rel') +'&rate='+ $(this).attr('rel') +'&type='+ $(this).parents('#classRating').attr('value') );
            }
            else{
                $('#classRating').load('/' + $(this).parents('#classRating').attr('rel') + '/rate?id='+ $(this).parents('.numberRating').attr('rel') +'&rate='+ $(this).attr('rel'));
            }
            return false;
        });
    }
}

//lo necesario para subir contenido
function uploader(){

    if ($('#progressbar').is('div')){
        var progress_key = $('#progress_key').val();

        $("input.upload-file").filestyle({
            image: "scimg/choose-file.gif",
            imageheight : 22,
            imagewidth : 82,
            width : 400
        });


        $("#progressbar").progressbar({width:400});

        if ($('#uploader-form')){
            $('#uploader-form').submit(function(){
                setTimeout('showUpload()', 1500);
            });
        }
    }
}

//muestra la barra de progreso porcentual
function showUpload() {
    var cTime = new Date();
    var rnd = cTime.getTime();

    $.get("/uploadprogress.php?id=" + $('#progress_key').val() + '&rnd=' + rnd, function(data) {
        if (!data)
            return;

        var response;
        eval ("response = " + data);

        if (!response)
            return;

        var percentage = Math.floor(100 * parseInt(response['bytes_uploaded']) / parseInt(response['bytes_total']));
        $("#progressbar").progressbar("progress",percentage);
        var speed = Math.floor(parseInt(response['speed_average'])/1024);
        $("#speed").html(speed + 'Kbps');

    });
    setTimeout("showUpload()", 750);
}

//para postar/borrar mensajes en academia
var mensajes = function(){
    //if (document.getElementById('myMessages')){

        //contador de caracteres
        $("#message").charCounter(200, {
            container: "<p></p>",
            classname: "counter",
            format: "%1/200",
            pulse: false,
            delay: 100
        });

        $('#myMessages form').livequery('submit',function(){
            //llamada AJAX
            if ($('#message').val() == '')
            {
                return false;
            }
            $.post("/academy/post_whiteboard", { message: $('#message').val(), academy: $(this).attr('rel'), type: $('#type').val() },
                function(data){
                    $('#myMessages #msgs_content').html(data).hide().slideDown();
                    $('#message').val('');
                });
            return false;
        });

        //Borrar mensajes
        $('#myMessages #msgs_content .delete-message').live('click',function(){
            var $$ = $(this).parents('li.overclearfix');
            $.post("/academy/del_whiteboard", { message: $(this).attr('rel'), type: $('#type').val() },
                function(data){
                        $$.slideUp('fast',function(){
                            $(this).remove();
                        });
                });
            return false;
        });
    //}
};

//edición inline
var editInPlace = function(){

    var nameIconEdit = ' <img id="pencil-name" src="/scimg/pencil-off.png"/>';
    var locationAcademyIconEdit = ' <img id="pencil-academy-location" src="/scimg/pencil-off.png" style="float: right;"/>';
    var locationProfileIconEdit = ' <img id="pencil-profile-location" src="/scimg/pencil-off.png"/>';
    var backgroundIconEdit = ' <img id="pencil-background" src="/scimg/pencil-off.png" style="float: right;"/>';
    var interesesIconEdit = ' <img id="pencil-intereses" src="/scimg/pencil-off.png" style="float: right;"/>';
    var goodIconEdit = ' <img id="pencil-good" src="/scimg/pencil-off.png" style="float: right;"/>';
    var emailIconEdit = ' <img id="pencil-email" src="/scimg/pencil-off.png" style="float: right;"/>';
    var webIconEdit = ' <img id="pencil-web" src="/scimg/pencil-off.png" style="float: right;"/>';

    // Load images for all inline editable fields
    //$("#academy_name").after(nameIconEdit);
    //$("#web").after(webIconEdit);
    //$("#contact_mail").after(emailIconEdit);
    //$("#good").after(goodIconEdit);
    $("#intereses").after(interesesIconEdit);
    $("#background").after(backgroundIconEdit);
    $("#academy-location #location").after(locationAcademyIconEdit);
    $("#profile-location #location").after(locationProfileIconEdit);


    // Make pencil picture clickable
    $("#pencil-name").click(function() {
        $("#academy_name").click();
    });
    $("#pencil-web").click(function() {
        $("#web").click();
    });
    $("#pencil-email").click(function() {
        $("#contact_mail").click();
    });
    $("#pencil-good").click(function() {
        $("#good").click();
    });
    $("#pencil-intereses").click(function() {
        $("#intereses").click();
    });
    $("#pencil-background").click(function() {
        $("#background").click();
    });
    $("#pencil-academy-location").click(function() {
        $("#academy-location #location").click();
    });
    $("#pencil-profile-location").click(function() {
        $("#profile-location #location").click();
    });

    // Mouse events
    $("#pencil-background").mouseover(function(){
        $("#pencil-background").attr("src", "/scimg/pencil-on.png");
    });
    $("#background").mouseover(function(){
        $("#pencil-background").attr("src", "/scimg/pencil-on.png");
    });
    $("#pencil-background").mouseout(function(){
        $("#profile-background-border").css({'border' : 'none'});
        $("#pencil-background").attr("src", "/scimg/pencil-off.png");
    });
    $("#background").mouseout(function(){
        $("#profile-background-border").css({'border' : 'none'});
        $("#pencil-background").attr("src", "/scimg/pencil-off.png");
    });

    $("#pencil-name").mouseover(function(){
        $("#pencil-name").attr("src", "/scimg/pencil-on.png");
    });
    $("#academy_name").mouseover(function(){
        $("#pencil-name").attr("src", "/scimg/pencil-on.png");
    });
    $("#pencil-name").mouseout(function(){
        $("#profile-name-border").css({'border' : 'none'});
        $("#pencil-name").attr("src", "/scimg/pencil-off.png");
    });
    $("#academy_name").mouseout(function(){
        $("#profile-name-border").css({'border' : 'none'});
        $("#pencil-name").attr("src", "/scimg/pencil-off.png");
    });

    $("#pencil-web").mouseover(function(){
        $("#pencil-web").attr("src", "/scimg/pencil-on.png");
    });
    $("#web").mouseover(function(){
        $("#pencil-web").attr("src", "/scimg/pencil-on.png");
    });
    $("#pencil-web").mouseout(function(){
        $("#profile-web-border").css({'border' : 'none'});
        $("#pencil-web").attr("src", "/scimg/pencil-off.png");
    });
    $("#web").mouseout(function(){
        $("#profile-web-border").css({'border' : 'none'});
        $("#pencil-web").attr("src", "/scimg/pencil-off.png");
    });

    $("#pencil-email").mouseover(function(){
        $("#pencil-email").attr("src", "/scimg/pencil-on.png");
    });
    $("#contact_mail").mouseover(function(){
        $("#pencil-email").attr("src", "/scimg/pencil-on.png");
    });
    $("#pencil-email").mouseout(function(){
        $("#profile-email-border").css({'border' : 'none'});
        $("#pencil-email").attr("src", "/scimg/pencil-off.png");
    });
    $("#contact_mail").mouseout(function(){
        $("#profile-email-border").css({'border' : 'none'});
        $("#pencil-email").attr("src", "/scimg/pencil-off.png");
    });

    $("#pencil-good").mouseover(function(){
        $("#pencil-good").attr("src", "/scimg/pencil-on.png");
    });
    $("#good").mouseover(function(){
        $("#pencil-good").attr("src", "/scimg/pencil-on.png");
    });
    $("#pencil-good").mouseout(function(){
        $("#profile-good-border").css({'border' : 'none'});
        $("#pencil-good").attr("src", "/scimg/pencil-off.png");
    });
    $("#good").mouseout(function(){
        $("#profile-good-border").css({'border' : 'none'});
        $("#pencil-good").attr("src", "/scimg/pencil-off.png");
    });

    $("#pencil-intereses").mouseover(function(){
        $("#pencil-intereses").attr("src", "/scimg/pencil-on.png");
        
    });
    $("#intereses").mouseover(function(){
        $("#pencil-intereses").attr("src", "/scimg/pencil-on.png");
        
    });
    $("#pencil-intereses").mouseout(function(){
        $("#profile-intereses-border").css({'border' : 'none'});
        $("#pencil-intereses").attr("src", "/scimg/pencil-off.png");
    });
    $("#intereses").mouseout(function(){
        $("#profile-intereses-border").css({'border' : 'none'});
        $("#pencil-intereses").attr("src", "/scimg/pencil-off.png");
    });

    $("#pencil-academy-location").mouseover(function(){
        $("#pencil-academy-location").attr("src", "/scimg/pencil-on.png");      
    });
    $("#academy-location").mouseover(function(){
        $("#pencil-academy-location").attr("src", "/scimg/pencil-on.png");
    });
    $("#pencil-academy-location").mouseout(function(){
        $("#profile-academy-location-border").css({'border' : 'none'});
        $("#pencil-academy-location").attr("src", "/scimg/pencil-off.png");
    });
    $("#academy-location").mouseout(function(){
        $("#profile-academy-location-border").css({'border' : 'none'});
        $("#pencil-academy-location").attr("src", "/scimg/pencil-off.png");
    });

    $("#pencil-profile-location").mouseover(function(){
        $("#pencil-profile-location").attr("src", "/scimg/pencil-on.png");
    });
    $("#profile-location").mouseover(function(){
        $("#pencil-profile-location").attr("src", "/scimg/pencil-on.png");
    });
    $("#pencil-profile-location").mouseout(function(){
        $("#profile-profile-location-border").css({'border' : 'none'});
        $("#pencil-profile-location").attr("src", "/scimg/pencil-off.png");
    });
    $("#profile-location").mouseout(function(){
        $("#profile-profile-location-border").css({'border' : 'none'});
        $("#pencil-profile-location").attr("src", "/scimg/pencil-off.png");
    });

    //escondemos el iconito mientras modificamos y ya no lo volvemos a mostrar,
    $("#academy_name").click(function(){
        $("#pencil-name").hide(); //ya que puede estar tanto antes como despuÃ©s
        $("#profile-name-border").css({'border' : 'none'});
        $("#profile-name-inedit").attr({'value' : 'yes'});
    });
    $("#web").click(function(){
        $("#pencil-web").hide(); //ya que puede estar tanto antes como despuÃ©s
        $("#profile-web-border").css({'border' : 'none'});
        $("#profile-web-inedit").attr({'value' : 'yes'});
    });
    $("#contact_mail").click(function(){
        $("#pencil-email").hide(); //ya que puede estar tanto antes como despuÃ©s
        $("#profile-email-border").css({'border' : 'none'});
        $("#profile-email-inedit").attr({'value' : 'yes'});
    });
    $("#good").click(function(){
        $("#pencil-good").hide(); //ya que puede estar tanto antes como despuÃ©s
        $("#profile-good-border").css({'border' : 'none'});
        $("#profile-good-inedit").attr({'value' : 'yes'});
    });
    $("#intereses").click(function(){
        $("#pencil-intereses").hide(); //ya que puede estar tanto antes como despuÃ©s
        $("#profile-intereses-border").css({'border' : 'none'});
        $("#profile-intereses-inedit").attr({'value' : 'yes'});
    });
    $("#background").click(function(){
        $("#pencil-background").hide(); //ya que puede estar tanto antes como despuÃ©s
        $("#profile-background-border").css({'border' : 'none'});
        $("#profile-background-inedit").attr({'value' : 'yes'});
    });
    $("#academy-location #location").click(function(){
        $("#pencil-academy-location").hide(); //ya que puede estar tanto antes como despuÃ©s
        $("#profile-academy-location-border").css({'border' : 'none'});
        $("#profile-academy-location-inedit").attr({'value' : 'yes'});
    });
    $("#profile-location").click(function(){
        $("#pencil-profile-location").hide(); //ya que puede estar tanto antes como despuÃ©s
        $("#profile-profile-location-border").css({'border' : 'none'});
        $("#profile-profile-location-inedit").attr({'value' : 'yes'});
    });

    // Academy name (in academy)
    $("#academy_name").editable("/academy/save_data", {
        type      : 'textarea',
        width: '100%',
        loadurl:    "/academy/view_data",
        wrap: 'HARD',
        indicator : "Saving...",
        tooltip   : 'Click to edit ...',
        placeholder : "",
        submit : 'OK',
        onblur: '',
        cancel : 'Cancel',
        cssclass : "editable",
        onreset: function(value, settings) {
         $("#pencil-name").attr("src", "/scimg/pencil-off.png");
         $('#pencil-name').show(); // show pencil again after submitting
         $("#profile-name-inedit").attr({'value' : 'no'});
        },
        onsubmit : function(value, settings) {
         $("#pencil-name").attr("src", "/scimg/pencil-off.png");
         $('#pencil-name').show(); // show pencil again after submitting
         $("#profile-name-inedit").attr({'value' : 'no'});
        }
     });

    // Website (in profile)
    $("#web").editable("/academy/save_data", {
        type      : 'textarea',
        width: '100%',
        loadurl:    "/academy/view_data",
        wrap: 'HARD',
        indicator : "Saving...",
        tooltip   : 'Click to edit ...',
        placeholder : "http://MyWebsite.com",
        submit : 'OK',
        onblur: '',
        cancel : 'Cancel',
        cssclass : "editable",
        onreset: function(value, settings) {
         $("#pencil-web").attr("src", "/scimg/pencil-off.png");
         $('#pencil-web').show(); // show pencil again after submitting
         $("#profile-web-inedit").attr({'value' : 'no'});
        },
        onsubmit : function(value, settings) {
         $("#pencil-web").attr("src", "/scimg/pencil-off.png");
         $('#pencil-web').show(); // show pencil again after submitting
         $("#profile-web-inedit").attr({'value' : 'no'});
        }
     });

    // Email (in profile)
    $("#contact_mail").editable("/academy/save_data", {
        type      : 'textarea',
        width: '100%',
        loadurl:    "/academy/view_data",
        wrap: 'HARD',
        indicator : "Saving...",
        tooltip   : 'Click to edit ...',
        placeholder : "My@Email.com",
        submit : 'OK',
        onblur: '',
        cancel : 'Cancel',
        cssclass : "editable",
        onreset: function(value, settings) {
         $("#pencil-email").attr("src", "/scimg/pencil-off.png");
         $('#pencil-email').show(); // show pencil again after submitting
         $("#profile-email-inedit").attr({'value' : 'no'});
        },
        onsubmit : function(value, settings) {
         $("#pencil-email").attr("src", "/scimg/pencil-off.png");
         $('#pencil-email').show(); // show pencil again after submitting
         $("#profile-email-inedit").attr({'value' : 'no'});
        }
     });

    // Good (in profile)
    $("#good").editable("/academy/save_data", {
        type      : 'textarea',
        loadurl:    "/academy/view_data",
        width: '100%',
        wrap: 'HARD',
        indicator : "Saving...",
        tooltip   : 'Click to edit ...',
        placeholder : "(describe)",
        submit : 'OK',
        onblur: '',
        cancel : 'Cancel',
        cssclass : "editable",
        onreset: function(value, settings) {
         $("#pencil-good").attr("src", "/scimg/pencil-off.png");
         $('#pencil-good').show(); // show pencil again after submitting
         $("#profile-good-inedit").attr({'value' : 'no'});
        },
        onsubmit : function(value, settings) {
         $("#pencil-good").attr("src", "/scimg/pencil-off.png");
         $('#pencil-good').show(); // show pencil again after submitting
         $("#profile-good-inedit").attr({'value' : 'no'});
        }
     });

    // Interests (in profile)
    $("#intereses").editable("/academy/save_data", {
        type      : 'textarea',
        loadurl:    "/academy/view_data",
        width: '100%',
        wrap: 'HARD',
        indicator : "Saving...",
        tooltip   : 'Click to edit ...',
        placeholder : "(empty)",
        submit : 'OK',
        onblur: '',
        cancel : 'Cancel',
        cssclass : "editable",
        onreset: function(value, settings) {
         $("#pencil-intereses").attr("src", "/scimg/pencil-off.png");
         $('#pencil-intereses').show(); // show pencil again after submitting
         $("#profile-intereses-inedit").attr({'value' : 'no'});
        },
        onsubmit : function(value, settings) {
          $("#pencil-intereses").attr("src", "/scimg/pencil-off.png");
         $('#pencil-intereses').show(); // show pencil again after submitting
         $("#profile-intereses-inedit").attr({'value' : 'no'});
        }
     });

    // Background (in profile)
    $("#background").editable("/academy/save_data", {
        type      : 'textarea',
        loadurl:    "/academy/view_data",
        width: '100%',
        wrap: 'HARD',
        indicator : "Saving...",
        tooltip   : 'Click to edit ...',
        placeholder : "(empty)",
        submit : 'OK',
        onblur: '',
        cancel : 'Cancel',
        cssclass : "editable",
        onreset: function(value, settings) {
        $("#pencil-background").attr("src", "/scimg/pencil-off.png");
         $('#pencil-background').show(); // show pencil again after submitting
         $("#profile-background-inedit").attr({'value' : 'no'});
        },
        onsubmit : function(value, settings) {
         $("#pencil-background").attr("src", "/scimg/pencil-off.png");
         $('#pencil-background').show(); // show pencil again after submitting
         $("#profile-background-inedit").attr({'value' : 'no'});
        }
     });

    // Location (in academy)
    $("#academy-location #location").editable("/academy/save_data", {
        type      : 'textarea',
        loadurl:    "/academy/view_data",
        width: '100%',
        wrap: 'HARD',
        indicator : "Saving...",
        tooltip   : 'Click to edit ...',
        placeholder : "(Click To Add Location)",
        submit : 'OK',
        onblur: '',
        cancel : 'Cancel',
        cssclass : "editable",
        onreset: function(value, settings) {
         $("#pencil-academy-location").attr("src", "/scimg/pencil-off.png");
         $('#pencil-academy-location').show(); // show pencil again after submitting
         $("#profile-academy-location-inedit").attr({'value' : 'no'});
        },
        onsubmit : function(value, settings) {
          $("#pencil-academy-location").attr("src", "/scimg/pencil-off.png");
         $('#pencil-academy-location').show(); // show pencil again after submitting
         $("#profile-academy-location-inedit").attr({'value' : 'no'});
        }
     });

     // Location (in profile)
    $("#profile-location #location").editable("/academy/save_data", {
        type      : 'textarea',
        loadurl:    "/academy/view_data",
        width: '100%',
        wrap: 'HARD',
        indicator : "Saving...",
        tooltip   : 'Click to edit ...',
        placeholder : "(Click To Add Location)",
        submit : 'OK',
        onblur: '',
        cancel : 'Cancel',
        cssclass : "editable",
        onreset: function(value, settings) {
         $("#pencil-profile-location").attr("src", "/scimg/pencil-off.png");
         $('#pencil-profile-location').show(); // show pencil again after submitting
         $("#profile-profile-location-inedit").attr({'value' : 'no'});
        },
        onsubmit : function(value, settings) {
         $("#pencil-profile-location").attr("src", "/scimg/pencil-off.png");
         $('#pencil-profile-location').show(); // show pencil again after submitting
         $("#profile-profile-location-inedit").attr({'value' : 'no'});
        }
     });


};


//cambio imagen academy
function changeImageAcademy(){

    if (document.getElementById('academy-img')){
        $('#academy-img a, #change-picture-right').click(function(){
            $.facebox.settings.opacity = 0;
            $.facebox.settings.modal = true;
            $.facebox( { ajax: '/academy/picture' } );
            return false;
        });
    }

    if (document.getElementById('profile-img')){
        $('#profile-img a').click(function(){
            $.facebox.settings.opacity = 0;
            $.facebox.settings.modal = true;
            $.facebox( { ajax: '/profile/picture' } );
            return false;
        });
    }

    if (document.getElementById('courses-img')){
        $('#courses-img a').click(function(){
            $.facebox.settings.opacity = 0;
            $.facebox.settings.modal = true;
            $.facebox( { ajax: '/courses/picture' } );
            return false;
        });
    }

    if (document.getElementById('webclasses-img')){
        $('#addpicture').click(function(){
            $.facebox.settings.opacity = 0;
            $.facebox.settings.modal = true;
            $.facebox( { ajax: '/webclasses/picture' } );
            return false;
        });
    }

    if (document.getElementById('events-img')){
        $('#addpicture').click(function(){
            $.facebox.settings.opacity = 0;
            $.facebox.settings.modal = true;
            $.facebox( { ajax: '/events/picture' } );
            return false;
        });
    }

     if (document.getElementById('groups-img')){
        $('#addpicture').click(function(){
            $.facebox.settings.opacity = 0;
            $.facebox.settings.modal = true;
            $.facebox( { ajax: '/groups/picture' } );
            return false;
        });
    }

    if (document.getElementById('courses-img')){
        $('#addpicture').click(function(){
            $.facebox.settings.opacity = 0;
            $.facebox.settings.modal = true;
            $.facebox( { ajax: '/courses/picture' } );
            return false;
        });
    }

}

//subida de la imagen
function ajaxFileUpload(){
    //starting setting some animation when the ajax starts and completes
    $("#loading")
    .ajaxStart(function(){
        $(this).show();
    })
    .ajaxComplete(function(){
        $(this).hide();
    });

    /*
        prepareing ajax file upload
        url: the url of script file handling the uploaded files
        fileElementId: the file type of input element id and it will be the index of  $_FILES Array()
        dataType: it support json, xml
        secureuri:use secure protocol
        success: call back function when the ajax complete
        error: callback function when the ajax failed

            */
    $.ajaxFileUpload
    (
        {
            url:'/academy/change_picture',
            secureuri:false,
            fileElementId:'fileToUpload',
            dataType: 'json',
            success: function (data, status)
            {
                if(typeof(data.error) != 'undefined')
                {
                    if(data.error != '')
                    {
                        alert(data.error);
                    }else
                    {
                        //alert(data.msg);
                        $('#academy-img img').attr('src',data.msg);
                        $('#academy-img form').slideUp();

                    }
                }
            },
            error: function (data, status, e)
            {
                alert(e);
            }
        }
    )

    return false;

}

//añadir academy como favorita
var addFavorite = function(){
    if (document.getElementById('topbar-favorite')){
        $('#academy #topbar-favorite a, #academy #leftbar-favorite a').click(function(){
            var academy = $(this).attr('rel');
            //añadimos favorito via ajax
            $.post("/academy/add_favorite", { academy: academy},
                function(data){
                    $('#topbar-favorite, #leftbar-favorite').html(data);
                });
            return false;
        });
    }
};


//validacion edit video
var validateEditVideo = function(){
    if ($('.halfSizeDiv').is('form')){

        $('label.invalid').removeClass('invalid');

        $('form.halfSizeDiv').validate({
            errorLabelContainer: false,
            errorClass : "invalid",
            /*errorPlacement: function(error, element) {
                $('label[for=' + element.attr('id') + ']').addClass('invalid');
            },*/
            rules: {
                videoName: "required",
                videoDescription: {
                    required: true,
                    maxlength: 1000
                }
            }
        });

        //seleccion de thumbnail
        $('#thumbnail-selection li input, #thumbnail-selection li label').hide();
        $('#thumbnail-selection li img').click(function(){
            //eliminamos seleccion actual (imagen y radio)
            $('#thumbnail-selection li img.selected').removeClass('selected');
            $('#thumbnail-selection li input:checked').removeAttr('checked');
            //seleccionamos esta (imagen y radio)
            $(this).addClass('selected').parent('li').find('input').attr('checked','checked');
        });

    }
};


//tabs de profile con AJAX
var tabsProfile = {

    tabs: function(){

        //codigo tabs
        $('#profile-tabs').tabs({
            load: function(e, ui) { //no mostramos submenu hasta que no se cargue la pestaña
                var selected = $('#profile-tabs').tabs('option', 'selected'); //para saber el indice de la pestaña seleccionada

                $(".subtab-nav").hide(); //escondemos submenus

				if ( selected == 1 ){ // 1 = learning
                    //ocultamos las categorías que no tienen items
                    $('#subtab-learning a').not('[rel=all]').parent().hide(); //ocultamos todos lo li por defecto
                    $('.tabLearning > div').each(function(){
                        $('#subtab-learning a[rel=' + $(this).attr('class') + ']').parent().show(); //mostramos los que tengan items
                    });

                    //$("#subtab-learning").show();
                    $("#subtab-learning").css('display','block');
                    tabsProfile.hideMore(); //por defecto muestro solo 2 items por categoria
                    tabsProfile.truncate();

                    if ($("#tab_additional").length > 0) {
                        if ($("#tab_additional").val() == "favourite")
                            $("#subtab-content a").click();
                        if ($("#tab_additional").val() == "courses")
                            $("#subtab-courses a").click();
                    }
                }
                else if ( selected == 2 ){ // 3 = events
                    $("#subtab-events").show();
                }
                else if ( selected == 3 ){ // 4 = contacts
                    $("#subtab-contacts").show();
                }

                $.unblockUI(); //desbloqueo interfaz
            },

        select: function(e,ui){ //solo mostramos la capa de loading cuando seleccionamos pestaña diferente
            Loading(); //iniciamos blockUI
        }
        });
    },

    categories: function(){
        //filtro segun submenu (oculto todos menos el seleccionado)
        $('#subtab-learning a').live('click',function(){
            $(this).parent().addClass('active').siblings().removeClass('active');

            if ( $(this).attr('rel') == 'all' ) {
                $('.tabLearning > div').find('> ul > li.rest').hide().end().show();
                $('.titleholder a').show(); // Show "Show all"
            }
            else {
            $('.tabLearning > div.' + $(this).attr('rel'))
                    .show()
                    .find('li.rest:hidden')
                    .slideDown()
                    .end()
                    .siblings()
                    .hide();
                    $('.titleholder a').hide(); // Hide "Show all"
            }
            return false;
        });

        //see all, comportamiento igual que cuando filtras por categorias (emulamos un click)
        $('.titleholder a').live('click',function(){
            var type = $(this).parents('div[class]:first').attr('class');
            $('#subtab-learning a[rel='+type+']').click();
        });

    },

    hideMore: function(){
        $('.tabLearning > div > ul').find('>li:gt(1)').addClass('rest').hide(); //solo dejamos visible los 2 primeros items de cada categoria

        //see all de cada categoria
        /*$('.titleholder a').live('click',function(){
            var context = $(this).parents('div[class]')[0];
            var target = $('li.rest',context);

            //muestro/oculto segun convenga
            ( target.is(':hidden') ) ? target.slideDown() : target.slideUp();

            return false;
        });*/

    },

    sendMessage: function(){ 
        if (!document.getElementById('nav_join')){ //si el usuario está logado
            //aprovechamos el mismo código para enviar mensajes en academy
            $('#send-message a, .send-message a, #academy #topbar-send a, a.syllabus-send').live('click',function(){
                $.facebox.settings.modal = false;
                var user = $(this).attr('rel');
                $.post('/mail/send', { to: user }, function(data) { if (data){ $.facebox(data); } });
                return false;
            });

            // For sending multiple messages in events
            $('.send-multiple-message').live('click', function(){
                $.facebox.settings.modal = false;
                if ($("#option-filter").length == 0)
                    var state_name = $(this).attr("name");
                else
                    var state_name = $("#option-filter").val();
                var state = $(this).attr('rel');
                if ($(this).attr('title') == 'event') {
                    $.post('/mail/send_students', { type: 'event', title: $("#title").val(), reference: $('#event_reference').val(), state: state, state_name: state_name }, function(data) {
                        if (data){ $.facebox(data); }
                    });
                }
                if ($(this).attr('title') == 'group') {
                    $.post('/mail/send_students', { type: 'group', title: $("#title").val(), reference: $('#group_reference').val(), state: state, state_name: state_name }, function(data) {
                        if (data){ $.facebox(data); }
                    });
                }
                if ($(this).attr('title') == 'course') {
                    $.post('/mail/send_students', { type: 'course', title: $("#title").val(), reference: $('#course_reference').val(), state: state, state_name: state_name }, function(data) {
                        if (data){ $.facebox(data); }
                    });
                }
                if ($(this).attr('title') == 'webclass') {
                    $.post('/mail/send_students', { type: 'webclass', title: $("#title").val(), reference: $('#webclass_reference').val(), state: state, state_name: state_name }, function(data) {
                        if (data){ $.facebox(data); }
                    });
                }
                return false;
            });

            // For sending multiple messages in events
            $('#academy.events a#send-multiple-message').live('click', function(){
                $.facebox.settings.modal = false;
                var state_name = $("#option-filter").val();
                var state = $(this).attr('rel');
                $.post('/mail/send_students', { type: 'event', title: $("#title").val(), reference: $('#event_reference').val(), state: state, state_name: state_name }, function(data) {
                    if (data){ $.facebox(data); }
                });
                return false;
            });

            // Para enviar mensaje a estudiantes de un curso
            $('#academy.courses #send-multiple-message a').live('click',function(){
                $.facebox.settings.modal = false;
                var state_name = $("#option-filter").val();
                $.post('/mail/send_students', { type:'course', title: $('#title').val() ,reference: $('#course_reference').val(), state: $('#student-filter').val(), state_name: state_name }, function(data) {
                    if (data){ $.facebox(data); }
                });
                return false;
            });

            // Para enviar mensajes a estudiantes de una webclass
            $('#academy.webclass #send-multiple-message a').live('click',function(){
                $.facebox.settings.modal = false;
                var state_name = $("#student-filter option[value='"+ $('#student-filter').val()+ "']").text();
                $.post('/mail/send_students', { type:'webclass', title: $('#title').val(), reference: $('#reference').val(), state: $('#student-filter').val(), state_name: state_name}, function(data) { if (data){ $.facebox(data); } });
                return false;
            });

            //validaciones
            $("#facebox #profile-send-message #send").live('click',function(){
                var error = false;

                $('#error_subject').hide();
                $('#error_body').hide();

                if ($('#msg_subject').val() == '') {
                    $('#error_subject').show();
                    error = true;
                }
                if ($('#msg_body').val() == '') {
                    $('#error_body').show();
                    error = true;
                }

                if (error) {
                    $('#messages').slideDown('slow', function(){
                        setTimeout(function() { $('#messages').slideUp('slow'); }, 4000);
                    });
                }
                else{
                    $.post("/mail/send", { to: $('#id_receiver').val(), subject: $('#msg_subject').val(), body: $('#msg_body').val(), type: $('#msg_type').val() },function(data){
                        type = $('#msg_type').val();
                        if (type == 'p')
                        {
                            // pageTracker._trackEvent('SOCIALIZING', 'Message sent to profile', $('#id_receiver').val());
                            //_gaq.push(['_trackEvent', 'SOCIALIZING', 'Message sent to profile']);

                        }
                        else if (type == 'a')
                        {
                            // pageTracker._trackEvent('SOCIALIZING', 'Message sent to academy', $('#id_receiver').val());
                            //_gaq.push(['_trackEvent', 'SOCIALIZING', 'Message sent to academy']);

                        }

                        $('#messages')
                            .find('ul').addClass('correct').end()
                            .find('#error_subject').hide().end()
                            .find('#error_body').html(lang[langActive][7]).css('display', 'block').end()
                            .slideDown('slow', function(){
                                   setTimeout(function() { $(this).slideUp('slow'); $(document).trigger('close.facebox'); }, 4000);
                               })
                            .siblings().hide();
                    });
                }
                return false;
            });

            // Validaciones para enviar mensajes a multiples estudiantes
            $("#facebox #students-send-message #send").live('click',function(){
                var error = false;

                $('#error_subject').hide();
                $('#error_body').hide();

                if ($('#msg_subject').val() == '') {
                    $('#error_subject').show();
                    error = true;
                }
                if ($('#msg_body').val() == '') {
                    $('#error_body').show();
                    error = true;
                }

                if (error) {
                    $('#messages').slideDown('slow', function(){
                        setTimeout(function() { $('#messages').slideUp('slow'); }, 4000);
                    });
                }
                else{
                    $(this).attr('disabled', 'disabled');
                    $.post("/mail/send_students", {subject: $('#msg_subject').val(), body: $('#msg_body').val(), type: $('#msg_type').val(), reference: $('#reference').val(), state: $('#state').val()},function(data){
                        $('#messages')
                            .find('ul').addClass('correct').end()
                            .find('#error_subject').hide().end()
                            .find('#error_body').html(lang[langActive][7]).css('display', 'block').end()
                            .slideDown('slow', function(){
                                setTimeout(function() { $(this).slideUp('slow'); $(document).trigger('close.facebox'); }, 4000);
                            })
                            .siblings().hide();
                    });
                }
                return false;
            });

            //textarea autoexpander
            //$('#facebox textarea.expanding').autogrow({minHeight: 90});
            $('#facebox textarea.expanding').elastic();
        }
    },

    shareContent: function(){
        $('.share-content a').live('click',function(){
            $.facebox.settings.modal = false;
            var content_id = $(this).attr('rel');
            $.facebox( { ajax: '/profile/show_sharecontent/'+content_id } ); //%%cambiar url (carga el template profile_learning_sharecontent.tpl)
            return false;
        });

        //autoClean de los textareas
        $('#facebox #profile-share-content textarea').livequery(function(){
            $(this).autoClean();
        })

        //boton cancel
        $('#facebox #profile-share-content #cancel').live('click', function(){ $(document).trigger('close.facebox') });

        //boton send
        $('#facebox #profile-share-content #send').live('click',function(){
            $(this).attr('disabled','disabled');
            //recogo los cursos marcados y los mails introducidos, compruebo que haya añadido algun destinatario para compartir
            if ( $('#profile-share-content #mails-friends').val()=='' && $('#profile-share-content :checkbox:checked').length == 0 ) {
                $('#messages')
                    .removeClass('correct')
                    .slideDown(function(){
                        setTimeout(function() { $('#messages').slideUp(); }, 4000);
                    });
            }
            else {
                $.ajax({
                    type: "post",
                    url: '/profile/share_content',
                    data: $('#facebox #profile-share-content form').serialize(),
                    success: function(data){
                        $('#messages')
                            .find('ul').addClass('correct').end()
                            .find('#error_subject').hide().end()
                            .find('#error_body').html('Content shared successfully!').css('display', 'block').end()
                            .slideDown('slow', function(){
                                setTimeout(function() { $(document).trigger('close.facebox'); }, 4000);
                            })
                            .siblings().hide();
                    }
                 });
            }
            return false;
        });

        //textarea autoexpander
        //$('#facebox textarea.expanding').autogrow({minHeight: 90});
        $('#facebox textarea.expanding').elastic();
    },

    del: function(){ //favorite content or favorites academies

        $('li.remove > a').live('click',function(){
            var context = ( $(this).parents('div[class=academies]').length ) ? $('#academies') : $('#content');
            var text = ( $(this).parents('div[class=academies]').length ) ? 'academy' : 'content';

            if (confirm('Are you sure you want to remove this ' + text + ' from your favorites?')) {
                //borramos
                switch (text) {
                    case 'academy':
                        Loading();
                        $.post('/academy/delete_favorite', { academy: $(this).attr('rel')} ,function(){					
                            $('#userprofile #profile-tabs').tabs('load', 1);
                        });
                        break;

                    case 'content':
                        Loading();
                        //%% cambiar url destino por la buena
                        $.post('/content/delete_favorite', { content: $(this).attr('rel')} ,function(){
                            $('#userprofile #profile-tabs').tabs('load', 1);
                        });
                        break;
                }
            }
            return false;
        })


    },

    truncate: function(){
        $('.col-center p').not($('.col-center p[class]')).jTruncate({length: 100});
    },

    init: function(){

        if ( !$('body#userprofile,body#academy,body#viewMedia').length ) return; //Limito alcance del script
		if ($("body.private").length) {
			// Profile is private
			$("#profile-tabs").tabs({ disabled: [0,1,2,3,4]});
			$("#academy-sections li a").css("cursor", "default");
			$("#academy-sections li a").css("text-decoration", "none");
			$("#academy-sections li a#teachlink").css("cursor", "pointer");
			return;
		}

        // Necesitamos el sharecontent tambien en academy->library
        if ($('body#academy,body#viewMedia').length){
            this.shareContent(); //para compartir contenido
            return;
        }

        this.tabs(); //al clickar realizo carga ajax de la pestaña, tambien muestro/oculto submenu dependiendo de la pestaña en donde estés
        this.categories(); //filtro del submenu y see all
        this.sendMessage(); //para enviar un mensaje
        this.shareContent(); //para compartir contenido
        this.del();
    }

}

function Loading(text){
    var config = loadingLayer(text);
    $.blockUI(config);
}

function LoadingFind(text){
    var config = loadingLayerFind(text);
    $.blockUI(config);
}

function validateSignUpForm(){
    $('#userEmail').css('border','');
    $('#userPass').css('border','');
    $('#userFirstName').css('border','');
    $('#userLastName').css('border', '');
    if ($.trim($('#userEmail').val()) == '')
    {
        $('#userEmail').focus();
        $('#userEmail').css('border', '1px solid #f00');
        return false;
    }
    if ($('#userPass').val() == '')
    {
        $('#userPass').css('border', '1px solid #f00');
        $('#userPass').focus();
        return false;
    }
    else if ($('#userPass').val().length < 4)
    {
        $('#userPass').css('border', '1px solid #f00');
        $('#userPass').focus();
        return false;
    }
    if ($.trim($('#userFirstName').val()) == '' || $('#userFirstName').val().toLowerCase() == $('#userFirstName').attr('rel').toLowerCase())
    {
        $('#userFirstName').css('border', '1px solid #f00');
        $('#userFirstName').focus();
        return false;
    }
    if ($.trim($('#userLastName').val()) == '' || $('#userLastName').val().toLowerCase() == $('#userLastName').attr('rel').toLowerCase())
    {
        $('#userLastName').css('border', '1px solid #f00');
        $('#userLastName').focus();
        return false;
    }
    if ($("input[name='gender']:checked").val() == null)
    {
        alert('You must select your gender.');
        return false;
    }
    if (!$('#accept_terms').is(':checked'))
    {
        alert('You must accept the Terms of Use.');
        $('#accept_terms').focus();
        return false;
    }
    return true;
}

function validate_signup(){
        $('#signup').submit(function() {
            return validateSignUpForm();
        });
}

function tags_suggest(){
        $('#join2 form').submit(function(){
            //enviamos datos via ajax
            // $("#tagSelected1").find("li").css('color','red');

            var learn_data = '';
            $("#tagSelected1 li").each(function(){
                learn_data = learn_data + $(this).attr('rel');
            });

            var teach_data = '';
            $("#tagSelected2 li").each(function(){
                teach_data = teach_data + $(this).attr('rel');
            });

            $.post("/join/add_area", { learn: learn_data, teach: teach_data},
                function(data){
                    if (teach_data != '')
                    {
                        window.location = '/academy';
                    }
                    else
                    {
                        window.location = '/profile';
                    }
                });
            return false;
        });
}


var relationships = function(){
    //cargamos el lightbox tipo facebook al encontrar #userprofile.private
    /*if ( $('#userprofile.private').is('body') ){
        // var user = $('#academy-link').attr('href').split('/')[3];
        var user = $('#username').val();
        var status = $('#rel_status').val();
        $.facebox( { ajax: '/relationships/ask/' + user + '/' + status} );
    }*/

};

//enviar mail interno en academy
var sendInternalMail = function(){

    /*$('#academy #topbar-send a, a.syllabus-send').live('click', function(){
        var user = $(this).attr('rel');
        //le quitamos el overlay y el modal, para que funcione tiene que declararse antes que la llamada a facebox
        $.facebox.settings.opacity = 0;
        $.facebox.settings.modal = true;
        $.post('/mail/send', { to: user }, function(data) { $.facebox(data) });
        return false;
    });*/

    if ( !$('body#academy')[0] ) return;
    tabsProfile.sendMessage(); //para que funcione en todos los sitios

};

function showWebclassEnroll(reference){
    $.facebox.settings.opacity = 0.5;
    $.facebox.settings.modal = false;
    $.post('/webclasses/enroll', { reference: reference }, function(data) { $.facebox(data) });
}

//botón verde para inscribirse a un curso
var enrollCourse = function(){
    $('#academy.courses #right a.course-button, a.course-link').live('click', function(event){
        if ($(this).attr('rel') != 'feedback'){
             // No es necesario mostrar #sign, ya que ahora se muestra la capa join ajax
            if ($("#sign").length > 0){
                 //$('#login').slideDown('fast'); //no está logueado

            }else{
                $.facebox.settings.opacity = 0.5;
                $.facebox.settings.modal = false;
                $.post('/courses/enroll', { reference: $('#course_reference').val() }, function(data) { $.facebox(data) });
            }
        }
        return false;
    });

    $('#webclass a.webclass-button[rel], a.course-link').live('click', function(){
        var reference = $(this).attr('rel');

        if ($("#sign").length > 0)// $('#login').slideDown('fast'); //no está logueado
        {
            $(document).bind('SHOW_ENROLL', function() {
                showWebclassEnroll(reference);
            });
        }
        else
        {
            showWebclassEnroll(reference);
            /*
            $.facebox.settings.opacity = 0.5;
            $.facebox.settings.modal = false;
            $.post('/webclasses/enroll', { reference: $(this).attr('rel') }, function(data) { $.facebox(data) });
            */
        }
        return false;
    });


    $('#academy a.browse-webclass-button[rel]').live('click', function(){
        var reference = $(this).attr('rel');

        if ($("#sign").length > 0)// $('#login').slideDown('fast'); //no está logueado
        {
            $(document).bind('SHOW_ENROLL', function() {
                showWebclassEnroll(reference);
            });
        }
        else
        {
            showWebclassEnroll(reference);
            /*
            $.facebox.settings.opacity = 0.5;
            $.facebox.settings.modal = false;
            $.post('/webclasses/enroll', { reference: $(this).attr('rel') }, function(data) { $.facebox(data) });
            */
        }
        return false;
    });

    $('#send_enroll_comments').live('click', function(){
            $.post('/courses/send_enroll', { comments: $('#comments').val(), reference: $('#course_reference').val() }, function() {
                $(document).trigger('close.facebox');
            });
        return false;
    });

    $("#enroll_course").live('click',function(){
        var rel = $(this).attr('rel');

        $.post("/courses/enrollment", { reference: $('#course_reference').val(), message: $('#comments').val()},
            function(data){
                // pageTracker._trackEvent('ASYNCTEACHING', 'Course enrollment');
                //_gaq.push(['_trackEvent', 'ASYNCTEACHING', 'Course enrollment']);
                if (rel == 'feedback')
                {
                    $('#enroll_window').fadeOut( function(){
                        $('#send_request_comments').fadeIn();
                        setTimeout("$(document).trigger('close.facebox');",1500);
                    });
                }
                else
                {
                    $(document).trigger('close.facebox');
                }
                $('#right .course-button').unbind('click').find('span').fadeOut('normal',function(){
                    if ($('#approval').val() == 'O')
                    {
                        $(this).html('Enrolled!').fadeIn();
                        window.location.reload(true);
                    }
                    else
                    {
                        $(this).html('Enrollment Pending').fadeIn();
                    }
                }).css('cursor','default');
           });
    });

    $("#enroll_webclass").live('click',function(){
        var ref = $('#wcr_reference').val();
        $.post("/webclasses/enrollment", { reference: ref },
            function(data){
                // pageTracker._trackEvent('LIVETEACHING', 'Class attendance');
                //_gaq.push(['_trackEvent', 'LIVETEACHING', 'Class attendance']);
                $(document).trigger('close.facebox');

                $('#webclass .webclass-button').unbind('click').find('span').fadeOut('normal',function(){
                    if ($('#approval').val() == 'O')
                    {
                        $(this).html('Attending').fadeIn();
                        window.location.reload(true);
                    }
                    else
                    {
                        $(this).html('Application Pending').fadeIn();
                    }

                }).css('cursor','default');

                $('#a'+ref).fadeOut('normal',function(){
                    if ($('#em'+ref).attr('rel') == 'O')
                    {
                        window.location.reload(true);
                    }
                    else
                    {
                        $('#em'+ref).html('Application Pending');
                    }

                }).css('cursor','default');

                $('#right .course-button').unbind('click').find('span').fadeOut('normal',function(){
                    $(this).html('Application Pending').fadeIn();
                }).css('cursor','default');

        });
    });

    $("#enroll_wcr_paypal").live('click',function(){
        $.post("/webclasses/enrollment", { reference: $('#wcr_reference').val() },
            function(data){
                $('#enroll_area').html(data);
        });
    });

    $("#enroll_paypal").live('click',function(){
        $.post("/courses/enrollment", { reference: $('#course_reference').val() },
            function(data){
                $('#enroll_area').html(data);
        });
    });

};

//para mostrar/ocultar info en pagina de curso
var toggleCourseDescr = function(){
    if ( $('#academy.courses').length == 0 || !document.getElementById('center')) return; //solo si estamos en cursos (solo en la pagina de curso! por eso lo del #center)

    if (document.getElementById('contents-index') && $('.summary').text().length > 100){ //aprovechamos el truncate
        $('.summary').jTruncate({length: 100});
        $('#contents-index').hide();

        $('a.truncate_more_link').live('click',function(){
            if ( $('#contents-index').is(':hidden') ) {
                $('#contents-index').slideDown();
                $('.summary').addClass('border');
            }
            else {
                $('#contents-index').slideUp();
                $('.summary').removeClass('border');
            }
        });
    }
    else{ //a manija
        $('#contents-index')
            .hide()
            .before('<a href="#" class="truncate_more_link">'+lang[langActive][0]+'</a>');

            $('a.truncate_more_link').live('click',function(){
                if ( $('#contents-index').is(':hidden') ) {
                    $('#contents-index').slideDown();
                    $('.summary').addClass('border');
                    $(this).html(lang[langActive][1]);
                }
                else {
                    $('#contents-index').slideUp();
                    $('.summary').removeClass('border');
                    $(this).html(lang[langActive][0]);
                }
            });
    }
}

//funciones relacionadas con los materiales del curso (vista profesor)
var courseMaterial = function(){

    //al hacer hover sobre cada li mostramos botones de acciones
    $("#academy.courses #content.teacher #result_list li").livequery(function(){
        $(this).hover(function(){
            $('p.actions',$(this)).show();
        },function(){
            $('p.actions',$(this)).hide();
        });
    });

    //ordenacion de los videos/docs de cursos en vista profesor
    $("#academy.courses #content.teacher #result_list").livequery(function(){
        $(this).sortable({
            placeholder: "ui-selected",
            revert: true
        });
    });

    //save order
    $("#academy.courses #content.teacher li#sendOrder a").live('click',function(){
        var order = [];
        $("#academy.courses #content.teacher #result_list li").each(function(){
            order.push($(this).attr('id'));
        });
        order = order.join(',');
        var $$ = $(this);
        $$.html('Saving order...');
        $.post('/courses/order', { course: $('#course_reference').val(), to: order }, function(data){
            //mensaje de OK
            $$.html('Order Saved!');
            setTimeout(function(){
                $$.fadeOut('normal',function(){ $$.html('Save order').fadeIn() });
            }, 2000);
        });

        return false;
    });

    //add material
    $("#academy.courses #content.teacher li#addMaterial a, .aaddMaterialQuick").live('click',function(){
        $.facebox.settings.opacity = 0;
        $.facebox.settings.modal = true;
        var reference = $('#course_reference').val();
        if (reference == null || reference == ''){
            // intentamos obtener la referencia del curso del atributo rel del elemente
            reference = $(this).attr('rel');
        }

        $.facebox( { ajax: '/courses/material/'+reference } );
        courseResources.addedVids.length = 0;
        courseResources.addedDocs.length = 0;
        return false;
    });

    //limitamos caracteres de materiales en add material
    $('#facebox ul.receiver li').livequery(function(){
        //'Remove' = 6
        if ( ($(this).text().length - 6) > 50 ) $(this).html( $(this).text().substr(0,50) + '...' +  '<a href="#">'+lang[langActive][2]+'</a>' );
    });
}

var courseResources = {
    addedVids: [],
    addedDocs: [],
    add: function(){
        var $$ = $(this);
        var vids = courseResources.addedVids;
        var docs = courseResources.addedDocs;
        if ($$.attr('id') == 'addVideo')
            var rel = 'videos';
        else if ($$.attr('id') == 'addDoc2')
            var rel = 'documents2';
        else
            var rel = 'documents';

        var id = $('select#' + rel,$(this).parents('fieldset')).val();
        var name = $('select#' + rel + ' option:selected',$(this).parents('fieldset')).text();
        var added = (rel ==  'videos') ? ($.inArray(id,vids) == -1 ? true : false) : ($.inArray(id,docs) == -1 ? true : false);

        if ( id != -1 && added ){ //si no es el texto "selecciona..." ni está ya añadido
            (rel ==  'videos') ? vids.push(id) : docs.push(id);
            if ( (name - 6) > 50 ) name.substr(0,50) + '...';
            $('.receiver',$(this).parents('fieldset')).append('<li class="' + id + '" rel="' + rel + '">' + name + '<a href="#">'+lang[langActive][2]+'</a></li>');
            $('select#' + rel + ' option:selected').remove();
            $('select#' + rel,$(this).parents('fieldset')).val(-1);// dejamos en default el valor del select
        }
    },
    addToArrays: function(){
        var vids = courseResources.addedVids;
        var docs = courseResources.addedDocs;
        //recorremos "ul.receiver li" y añadimos al array correspondiente
        $('#academy.webclass ul.receiver li').each(function(){
            if ($(this).attr('rel') == "videos") vids.push($(this).attr('class'));
            else docs.push($(this).attr('class'));
        });
        $('#academy.courses ul.receiver li').each(function(){
            if ($(this).attr('rel') == "videos") vids.push($(this).attr('class'));
            else docs.push($(this).attr('class'));
        });

    },
    del: function(){
        var $$ = $(this);
        var type = $$.parent().attr('rel');
        var text = $$.parent().text().slice(0,-6); //quitamos el texto "Remove"
        var value = $$.parent().attr('class');

        var rel = $$.attr('id') == 'addVideo' ? 'videos' : 'documents';

        $$.parent().fadeOut(function(){ $(this).remove() });

        //lo volvemos a mostrar en el select
        //$('option[value=' + $$.parent().attr('class') + ']','select#' + type).show();

        //lo volvemos a crear
        $('select#' + type,$(this).parents('fieldset')).append('<option value='+ value +'>' + text + '</option>');

        //la eliminamos del array correspondiente
        if ($(this).parent().attr('rel') == 'videos'){
            var position = $.inArray($(this).parent().attr('class'),courseResources.addedVids);
            courseResources.addedVids.splice(position,1);
        }
        else{
            var position = $.inArray($(this).parent().attr('class'),courseResources.addedDocs);
            courseResources.addedDocs.splice(position,1);
        }

        return false;
    },
    hiddens: function(){
        //location.href="#create-webclass";

        $('form#create-webclass, form#create-broadcast')
            .find('input[name=resource_videos]')
            .remove()
            .end()
            .find('input[name=resource_documents]')
            .remove()
            .end()
            .append('<input type="hidden" name="resource_videos" value="' + courseResources.addedVids.join(',') + '" />')
            .append('<input type="hidden" name="resource_documents" value="' + courseResources.addedDocs.join(',') + '" />');
        //return false;
    },
    init: function(){
        $('#academy.webclass form #addVideo, #academy.webclass form #addDoc, form.addContent #addVideo, form.addContent #addDoc, #academy.events #broadcasts-main #addDoc, #academy.events table #addDoc').live('click',this.add);
        $('#academy.webclass ul.receiver li a, form.addContent ul.receiver li a, #academy.events #broadcasts-main ul.receiver li a').live('click',this.del);
        $("#academy.events #broadcasts-main #addDoc2").live('click', this.add);

        //%% para eliminar el botón hago que directamente al cambiar el select se lance un evento click en el botón, que previamente habre ocultado
        var btAdd = $('#academy.webclass form #addVideo, #academy.webclass form #addDoc, form.addContent #addVideo, form.addContent #addDoc');
        btAdd.livequery(function(){ $(this).hide() });
        $('#academy.webclass form select#documents').live('change',function(){ $('#academy.webclass form #addDoc').click() });
        $('#academy.webclass form select#videos').live('change',function(){ $('#academy.webclass form #addVideo').click() });
        $('form.addContent select#documents').live('change',function(){ $('form.addContent #addDoc').click() });
        $('form.addContent select#videos').live('change',function(){ $('form.addContent #addVideo').click() });
        $('#academy.events form select#documents').live('change',function(){ $('#academy.events form #addDoc').click() });
        $('#academy.events form select#documents2').live('change',function(){ $('#academy.events form #addDoc2').click() });

        $('#academy.events form#create-broadcast').submit(this.hiddens);

        $('form.addContent #saveMaterial').live('click',function(){
            courseResources.addToArrays();

            $.post("/courses/save_material", { reference: $('#course_reference').val(), vids: courseResources.addedVids.join(','), docs: courseResources.addedDocs.join(',') }, function(data){
                $(document).trigger('close.facebox');
                courseResources.addedVids.length = 0;
                courseResources.addedDocs.length = 0;
                if (data == 'reload')
                {
                     window.location = '/courses/view/'+$('#course_reference').val()+'/materials';
                }
            });
            return false;
        });



        // validate webclass
        // $('#academy.webclass #timeEntry').timeEntry({show24Hours: true, spinnerImage: ''});

        $('#academy.webclass form#create-webclass')
            .submit(this.hiddens)
            .validate({
                errorContainer: $("#academy.webclass form#create-webclass div.container-error"),
                errorLabelContainer: $("ul", $("#academy.webclass form#create-webclass div.error")),
                wrapper: 'li'
            });

        //contar caracteres de description
        $("#academy.webclass #description:visible").charCounter(1000, {
            container: "<p></p>",
            classname: "note",
            format: "%1/1000",
            pulse: false,
            delay: 100
        });

        $("#academy.webclass #requirements:visible").charCounter(150, {
            container: "<p></p>",
            classname: "note",
            format: "%1/150",
            pulse: false,
            delay: 100
        });

        //limitamos caracteres de materiales en add material
        $('ul.receiver li').livequery(function(){
            //'Remove' = 6
            if ( ($(this).text().length - 6) > 50 ) $(this).html( $(this).text().substr(0,50) + '...' +  '<a href="#">'+lang[langActive][2]+'</a>' );
        });
    }
}

// import & invite contacts
var inviteContactsbyEmail = {
    addMails: function(mailsLista){
        if (typeof mailsLista == "string") {
            var mails = mailsLista.split(',');
        }
        else {
            if ($('#mails').val() == '') {
                alert('To invite students, please add at least one email address or contact.');
                return;
            }
            else{
                var mails = $('#mails').val().split(',');
                $('#mails').val('');
            }
        }

//        alert(mails);

        for (var x in mails){ //validamos el mail y miramos que no exista ya
            x = $.trim(mails[x]);

            var repetida = false;

            $('#invite-students li').not('[rel=contact]').each(function(){
                repetida = $(this).text().indexOf(x)!=-1 ? true: false;
            });

            if (!repetida) $('#invite-students').append('<li>' + x + ' <a href="#">'+lang[langActive][2]+'</a></li>');
        }

        $('#invite-form').hide();
        $('#p-invite-form').hide();
        $('#manually-invite').hide();
        $('#invitedirectemails').hide();
        $('#invited').show().removeClass('hidden');

        $('#invite-students').effect('highlight',{},1000);

        if ( $('#invite-students li').length != 0 ) $('#no-students:visible').hide(); //ocultamos texto si se ha anyadido algo
    },
    remove: function(){
        $$ = $(this).parent();

        if ($$.attr('rel')=="contact"){ //si es contacto lo devolvemos a la lista de contactos
            $('#contacts-sclipo li[id=' + $$.attr('id') + ']').removeClass('hide').effect('highlight',{},1000);
        }
        //borramos de la lista
        $$.fadeOut('normal',function(){
            $(this).remove();
            if ($('#invite-students li').length == 0)
            {
                $('#manually-invite').show();
                $('#p-invite-form').show();
                $('#invite-form').show();
                $('#no-students').show();
                $('#invitedirectemails').show();
                $('#invited').hide();
            }
        });

        return false;
    },
    hiddens: function(){
        var invitedContactsMails = [];

        //creo dos inputs hidden, uno con los ids de los contactos y otro con los correos
        $('#invite-students li').each(function(){
            invitedContactsMails.push( $(this).find('a').remove().end().text() );
        });

        $('form#invite-friends')
            .find('input[name=invited_contacts_mails]')
            .remove()
            .end()
            .append('<input type="hidden" id="invited_contacts_mails" name="invited_contacts_mails" value="' + invitedContactsMails.join(',') + '" />');
    },
    init: function(){

        if ($('form#invite-friends').length == 0) return;

        $('#contacts-sclipo li > :checkbox').click(this.addContact);
        $('#invite-mail').click(this.addMails);

        $('#invite-students li > a').live('click',this.remove);
    }
};

var invitations = {
	addInvitations: function() {
		var invitationsStudents = "";
		$("#selectedContacts li").each(function() {
			var user = $(this).attr("id");
			invitationsStudents = ""+invitationsStudents + user + ",";
		});
		$("#student_invitations").val(""+invitationsStudents);
	},
	disableTemplate: function() {
		$("#allContacts").hide();
		$("#nostudent").hide();
		$("#upgradeacademy").hide();
		$("#noteacher").hide();
		$("span.invitation-type").hide();
		$("#import-mail").unbind();
		$("#import-mail").removeClass("active").addClass("inactive");
		$("#select_contacts textarea").attr("readonly","readonly");
		// $("#cbottom .orange-btn").unbind();
	},
	enableTemplate: function() {
		$("#upgradeacademy").hide();
		$("#noteachers").hide();
		$("#nostudent").hide();
		$("#allContacts").show();
		$("span.invitation-type").show();
		$("#import-mail").unbind();
		$("#import-mail").removeClass("inactive").addClass("active");
		importMails();
		$("#select_contacts textarea").attr("readonly","");
		$("#cbottom .orange-btn").bind("click", function () {
			invitations.addInvitations(); 
			$('#create-event').submit(); 
			return false;
		});
	},
	showTeacher: function() {
		var langActive = $('html').attr('lang');
        
		$("#invitation-type").val("W");
		$("#emaildiv").hide();
		$('#cbottom .orange-btn').html(send_to[langActive][0]);
		$('#invitationheader').css('background', 'url(/scimg/loading.gif) no-repeat right bottom');
		$('#tabcontent').fadeOut(400);
		$("#selectedContacts").html("");
		$("#selectedContacts").hide();
		$("#allContacts").html("").hide();
		$("span #numSelected").text(0);
		$(".invitation-type[rel!='selected']").hide();
		$("#studenttab").removeClass("orange-button-selected");$("#teachertab").addClass("orange-button-selected");
		var user = $("input#user").attr("val");
		$.post("/relationships/filter_invitees", {user: user, type: 'teachers'}, function(data) {
				var temp = new Array();
				temp = data.split("<<>>");
				if (temp[1] == "1") { // Max teachers is 1
					invitations.disableTemplate();
					$("#upgradeacademy").show();					
				}
				else if (temp[0] == "1") { // No teachers except yourself
					invitations.disableTemplate();
					$("#noteachers").show();					
				}
				else {
					$("#allContacts").html(temp[2]);
					invitations.enableTemplate();
					// Now filter out those that are already invited or enrolled
					if ($("input#application_type").val() == "course") {
						var course = $("#course_reference").val();
						$.post("/courses/get_students_in_course", {course: course}, function(data) {
							$("#allContacts li").filter(function(index) {
							  return (data.search($(this).attr("id")) != -1);
							}).attr('makegrey','true').css('opacity','0.5').css('filter','alpha(opacity = 50, style=0)').css('zoom','1');
							$("#allContacts").show();
							invitations.enableTemplate();
							$(".invitation-type[rel!='selected']").hide();
						});
					}					
					else if ($("input#application_type").val() == "event") {
						var event = $("#events_reference").val();
						$.post("/events/get_students_in_event", {event: event}, function(data) {
							$("#allContacts li").filter(function(index) {
							  return (data.search($(this).attr("id")) != -1);
							}).attr('makegrey','true').css('opacity','0.5').css('filter','alpha(opacity = 50, style=0)').css('zoom','1');
							$("#allContacts").show();
							invitations.enableTemplate();	
							$(".invitation-type[rel!='selected']").hide();
						});
					}				
					else if ($("input#application_type").val() == "webclass") {
						var webclass = $("#reference").val();
						$.post("/webclasses/get_students_in_webclass", {webclass: webclass}, function(data) {
							$("#allContacts li").filter(function(index) {
							  return (data.search($(this).attr("id")) != -1);
							}).attr('makegrey','true').css('opacity','0.5').css('filter','alpha(opacity = 50, style=0)').css('zoom','1');
							$("#allContacts").show();
							invitations.enableTemplate();	
							$(".invitation-type[rel!='selected']").hide();
						});
					}	
					else if ($("input#application_type").val() == "group") {
						var group = $("#groups_reference").val();
						$.post("/groups/get_students_in_group", {group: group}, function(data) {
							$("#allContacts li").filter(function(index) {
							  return (data.search($(this).attr("id")) != -1);
							}).attr('makegrey','true').css('opacity','0.5').css('filter','alpha(opacity = 50, style=0)').css('zoom','1');
							$("#allContacts").show();
							invitations.enableTemplate();
							$(".invitation-type[rel!='selected']").hide();							
						});
					}	
					else {
						$("#allContacts").show();
						invitations.enableTemplate();	
						$(".invitation-type[rel!='selected']").hide();
					}
				}
				$('#invitationheader').css('background', 'none');
				$('#tabcontent').fadeIn(400);
		});
	},
	showStudent: function() {
        var langActive = $('html').attr('lang');

		$("#invitation-type").val("I");
		$("#emaildiv").show();
		$('#cbottom .orange-btn').html(send_to[langActive][1]);
		$('#invitationheader').css('background', 'url(/scimg/loading.gif) no-repeat right bottom');
		$('#tabcontent').fadeOut(400);
		$("#selectedContacts").html("");
		$("#selectedContacts").hide();
		$("#allContacts").html("").hide();
		$("span #numSelected").text(0);
		$(".invitation-type[rel!='selected']").show();
		$(".invitation-type").removeClass('orange-button-selected');
		$(".invitation-type[rel='all']").addClass('orange-button-selected');
		$("#teachertab").removeClass("orange-button-selected");$("#studenttab").addClass("orange-button-selected");
		var user = $("input#user").attr("val");
		$.post("/relationships/filter_invitees", {user: user, type: 'all'}, function(data) {
				var temp = new Array();
				invitations.enableTemplate();
				temp = data.split("<<>>");
				if (temp[0] == "0") {	// No students/contacts
					//invitations.disableTemplate();
					$("#nostudent p").hide();
					$("#nostudent #all").show();
					$("#nostudent").show();					
				}
				else {
					$("#allContacts").html(temp[1]);
						
					// Now filter out those that are already invited or enrolled
					if ($("input#application_type").val() == "course") {
						var course = $("#course_reference").val();
						$.post("/courses/get_students_in_course", {course: course}, function(data) {
							$("#allContacts li").filter(function(index) {
							  return (data.search($(this).attr("id")) != -1);
							}).attr('makegrey','true').css('opacity','0.5').css('filter','alpha(opacity = 50, style=0)').css('zoom','1');
							$("#allContacts").show();
							invitations.enableTemplate();
						});
					}					
					else if ($("input#application_type").val() == "event") {
						var event = $("#events_reference").val();
						$.post("/events/get_students_in_event", {event: event}, function(data) {
							$("#allContacts li").filter(function(index) {
							  return (data.search($(this).attr("id")) != -1);
							}).attr('makegrey','true').css('opacity','0.5').css('filter','alpha(opacity = 50, style=0)').css('zoom','1');
							$("#allContacts").show();
							invitations.enableTemplate();
						});
					}				
					else if ($("input#application_type").val() == "webclass") {
						var webclass = $("#reference").val();
						$.post("/webclasses/get_students_in_webclass", {webclass: webclass}, function(data) {
							$("#allContacts li").filter(function(index) {
							  return (data.search($(this).attr("id")) != -1);
							}).attr('makegrey','true').css('opacity','0.5').css('filter','alpha(opacity = 50, style=0)').css('zoom','1');
							$("#allContacts").show();
							invitations.enableTemplate();
						});
					}	
					else if ($("input#application_type").val() == "group") {
						var group = $("#groups_reference").val();
						$.post("/groups/get_students_in_group", {group: group}, function(data) {
							$("#allContacts li").filter(function(index) {
							  return (data.search($(this).attr("id")) != -1);
							}).attr('makegrey','true').css('opacity','0.5').css('filter','alpha(opacity = 50, style=0)').css('zoom','1');
							$("#allContacts").show();
							invitations.enableTemplate();
						});
					}	
					else {
						$("#allContacts").show();
						invitations.enableTemplate();
					}
				}
				$('#invitationheader').css('background', 'none');
				$('#tabcontent').fadeIn(400);	
		});	
	},
	init: function(){		
		$(".invitation-type").click(function() {
			$$ = $(this);						
			
			var type = $$.attr("rel");
			var user = $("input#user").attr("val");
			if (type == "selected") {
				if ($$.hasClass('orange-button-selected')) {				
					$("#selectedContacts").hide();
					$("#allContacts").show();
					$$.removeClass('orange-button-selected');
				}
				else {			
					$$.addClass('orange-button-selected');
					
					$("#allContacts").hide();
					$("#selectedContacts").show();				
				}
				return;			
			}
			else {
				$("#nostudent").hide();
				$('#allContacts').html('').hide();
				$('#contacts').css('background', 'url(/scimg/loading.gif) no-repeat center');
				if ($$.hasClass('orange-button-selected')) return false;
				$('.invitation-type').removeClass('orange-button-selected').addClass('orange-button');
				$$.addClass('orange-button-selected');
			
				$("#selectedContacts").hide();
				
				$.post("/relationships/filter_invitees", {user: user, type: type}, function(data) {					
					var temp = new Array();
					temp = data.split("<<>>");
					invitations.enableTemplate();
					if (temp[0] == "0") {	// No students/contacts
						//invitations.disableTemplate();
						$("span.invitation-type").show();
						$("#nostudent p").hide();
						$("#nostudent p."+type).show();
						$("#nostudent").show();					
					}
					else {
						$("#allContacts").html(temp[1]);						
						$("#selectedContacts li").each(function() {
							$("#allContacts li[id='"+$(this).attr("id")+"']").css('border','1px solid');
							$("#allContacts li[id='"+$(this).attr("id")+"']").css('background-color', '#F08B1D');
							$("#allContacts li[id='"+$(this).attr("id")+"']").css('color', 'white');
							$("#allContacts li[id='"+$(this).attr("id")+"']").attr("sel","1");
						});				
						
						// Now filter out those that are already invited or enrolled
						if ($("input#application_type").val() == "course") {
							var course = $("#course_reference").val();
							$.post("/courses/get_students_in_course", {course: course}, function(data) {
								$("#allContacts li").filter(function(index) {
								  return (data.search($(this).attr("id")) != -1);
								}).attr('makegrey','true').css('opacity','0.5').css('filter','alpha(opacity = 50, style=0)').css('zoom','1');
								$("#allContacts").show();
							});
						}
						else if ($("input#application_type").val() == "event") {
							var event = $("#events_reference").val();
							$.post("/events/get_students_in_event", {event: event}, function(data) {
								$("#allContacts li").filter(function(index) {
								  return (data.search($(this).attr("id")) != -1);
								}).attr('makegrey','true').css('opacity','0.5').css('filter','alpha(opacity = 50, style=0)').css('zoom','1');
								$("#allContacts").show();
							});
						}
						else if ($("input#application_type").val() == "webclass") {
							var webclass = $("#reference").val();
							$.post("/webclasses/get_students_in_webclass", {webclass: webclass}, function(data) {
								$("#allContacts li").filter(function(index) {
								  return (data.search($(this).attr("id")) != -1);
								}).attr('makegrey','true').css('opacity','0.5').css('filter','alpha(opacity = 50, style=0)').css('zoom','1');
								$("#allContacts").show();
							});
						}		
						else if ($("input#application_type").val() == "group") {
							var group = $("#groups_reference").val();
							$.post("/groups/get_students_in_group", {group: group}, function(data) {
								$("#allContacts li").filter(function(index) {
								  return (data.search($(this).attr("id")) != -1);
								}).attr('makegrey','true').css('opacity','0.5').css('filter','alpha(opacity = 50, style=0)').css('zoom','1');
								$("#allContacts").show();
							});
						}	
						else
							$("#allContacts").show();
					}			
					$('#contacts').css('background', 'none');
				});
			}
		});
		
		$("#contacts li").live('click', function() {
			if ($(this).attr("makegrey") == "true") return;
			
			if ($(this).attr("sel") == 0) {
				$(this).css('border','1px solid');
				$(this).css('background-color', '#F08B1D');
				$(this).css('color', '#FFFFFF');
				$(this).attr("sel",1);
				
				$("span #numSelected").text(parseInt($("span #numSelected").text())+1);
				$("#selectedContacts").append($(this).clone());			
			}
			else {
				$(this).css('border','none');
				$(this).css('background-color', '#FFFFFF');
				$(this).css('color', '#808080');
				$(this).attr("sel",0);
				
				$("span #numSelected").text(parseInt($("span #numSelected").text())-1);
				$("#selectedContacts li#"+$(this).attr("id")).remove();
			}
		});		
		
		$("#contacts li").live('mouseover mouseout', function(event) {
		  if ($(this).attr("sel") == 1 || $(this).attr("makegrey")=="true") return;
		  if (event.type == 'mouseover') {
			$(this).css('border','1px solid');
			$(this).css('background-color', '#F08B1D');
			$(this).css('color', '#FFFFFF');
		  } else {
			$(this).css('border','1px solid #FFFFFF');
			$(this).css('background-color', '#FFFFFF');
			$(this).css('color', '#808080');
		  }
		});			
		
		$("#typename").keypress(function(data) {
			if (data.keyCode == 13)
				return false;
		});
		
		$("#typename").keyup(function() {				
			var $$ = $(this);
			var name = $$.val();
			if (name == "") {
				$("#allContacts li").show();
				return false;
			}
			var regExp = new RegExp(name, "i");
			$("#allContacts li").hide();
			$("#allContacts li").filter(function(index) {
			  return ($(this, "h3").text().search(regExp) != -1);
			}).show();
			
			return false;
		});
	}
};

//Crear webclass!
var inviteStudents = {
    addContact: function(){
        $(this).get(0).checked = false; //desmarcamos el checkbox
        var $$ = $(this).parent();

        //Añadimos como invitado
        $('#invite-students')
            .append('<li id="' + $$.attr('id') + '" rel="contact">' + $$.text() + ' <a href="#">'+lang[langActive][2]+'</a></li>')
            .stop()
            .css('background','#fff')
            .effect('highlight',{},1000);

        $$.addClass('hide'); //Ocultamos en contactos
        $('#no-students:visible').hide(); //ocultamos texto
    },
    addMails: function(mailsLista){
        if (typeof mailsLista == "string") {
            if (mailsLista != '') var mails = mailsLista.split(',');
            else var mails = null;
        }
        else {
            if ($('#mails').val() == '') {
                alert('To invite students, please add at least one email address or contact.');
                return;
            }
            else{
                var mails = $('#mails').val().split(',');
                $('#mails').val('');
            }
        }

        if (mails != null)
        {
            for (var x in mails){ //validamos el mail y miramos que no exista ya
                x = $.trim(mails[x]);

                var repetida = false;

                $('#invite-students li').not('[rel=contact]').each(function(){
                    repetida = $(this).text().indexOf(x)!=-1 ? true: false;
                });

                if (!repetida) $('#invite-students').append('<li>' + x + ' <a href="#">'+lang[langActive][2]+'</a></li>');
            }

            $('#invite-form').hide();
            $('#p-invite-form').hide();
            $('#manually-invite').hide();
            $('#invitedirectemails').hide();

            $('#invited').show().removeClass('hidden');

            $('#invite-students').effect('highlight',{},1000);
        }

        if ( $('#invite-students li').length != 0 ) $('#no-students:visible').hide(); //ocultamos texto si se ha aÃ±adido algo
    },
    remove: function(){
        $$ = $(this).parent();

        if ($$.attr('rel')=="contact"){ //si es contacto lo devolvemos a la lista de contactos
            $('#contacts-sclipo li[id=' + $$.attr('id') + ']').removeClass('hide').effect('highlight',{},1000);
        }

        /* Nacho: 2008/03/05 Comente el if de abajo y lo sustitui por esto*/
        $$.fadeOut('normal',function(){
                $(this).remove();
                if ($('#invite-students li').length == 0) {
                    $('#no-students').show();
                    if ($('#selectnone').length != 0)
                        $('#selectnone').css('display','none');
                }
        });

        return false;
    },
    hiddens: function(){
        var invitedStudentsContacts = [];
        var invitedStudentsMails = [];

        //comprobamos que no haya mails en el textarea
        if ($('#mails').val() != undefined && $('#mails').val() != ''){

            alert('You have written some emails but you haven\'t added them to the invitation list.');
            $('#mails').focus();
            return false;

            //alert($('#mails').val());
            //this.addMails; // ($('#mails').val());
        }

        //creo dos inputs hidden, uno con los ids de los contactos y otro con los correos
        $('#invite-students li').each(function(){
            if ($(this).attr('rel')=="contact") invitedStudentsContacts.push( $(this).find('a').remove().end().attr('id') );
            else invitedStudentsMails.push( $(this).find('a').remove().end().text() );
        });

        $('form#create-webclass-2')
            .find('input[name=invited_students_contacts]')
            .remove()
            .end()
            .find('input[name=invited_students_mails]')
            .remove()
            .end()
            .append('<input type="hidden" name="invited_students_contacts" value="' + invitedStudentsContacts.join(',') + '" />')
            .append('<input type="hidden" name="invited_students_mails" value="' + invitedStudentsMails.join(',') + '" />');

        $('form#create-event')
            .find('input[name=invited_students_contacts]')
            .remove()
            .end()
            .find('input[name=invited_students_mails]')
            .remove()
            .end()
            .append('<input type="hidden" name="invited_students_contacts" value="' + invitedStudentsContacts.join(',') + '" />')
            .append('<input type="hidden" name="invited_students_mails" value="' + invitedStudentsMails.join(',') + '" />');

        $('#academy.dashboard')
            .find('input[name=invited_contacts]')
            .remove()
            .end()
            .find('input[name=invited_mails]')
            .remove()
            .end()
            .append('<input type="hidden" name="invited_contacts" id="invited_contacts" value="' + invitedStudentsContacts.join(',') + '" />')
            .append('<input type="hidden" name="invited_mails" id="invited_mails" value="' + invitedStudentsMails.join(',') + '" />');
    },
    sendMessage: function(){
        var user = $(this).attr('rel');
        //le quitamos el overlay y el modal, para que funcione tiene que declararse antes que la llamada a facebox
        $.facebox.settings.opacity = 0;
        $.facebox.settings.modal = true;
        $.post('/mail/send', { to: user }, function(data) { $.facebox(data) });
        return false;
    },
    enrollment: function(){
        var type = $('body').attr('class') == 'webclass' ? 'webclasses' : 'courses';
        var study = type == 'courses' ? 'course' : 'webclass';
        var state = $(this).attr('rel').substring(0,1);
        var user  = $(this).attr('rel').substring(1);
        //le quitamos el overlay y el modal, para que funcione tiene que declararse antes que la llamada a facebox
        $.facebox.settings.opacity = 0;
        $.facebox.settings.modal = true;

        if (type == 'webclasses')
        {
            var id_reference = $('#reference').val();
        }
        else
        {
            var id_reference = $('#course_reference').val()
        }

        switch (state){
                case 'R':
                    if (confirm('Are you sure you want to reject the application of this student?\n\nRejected students are informed of your decision via email and may contact your academy with further questions. '))
                    {
                        $('#li_'+user+' #student-status').html("Rejected");
                        $('#action_'+user+' .action-enrollment').html("");

                        /*$('#li_'+user).effect('highlight',{}).fadeOut('normal',function(){
                            $(this).remove();
                        });*/
                        $.post('/' + type + '/confirm_enrollment', { username: user, state: state, reference: id_reference, ajax: 'Y' });
                    }
                    break;
                case 'K':
                    if (confirm('Are you sure you want to dismiss this student from the ' + study + '?\n\nDismissed students are informed of your decision via email and may contact your academy with further questions.'))
                    {
                        $('#li_'+user+' #student-status').html("Dismissed");
                        $('#action_'+user+' .action-enrollment').html("");
                        /*$('#li_'+user).effect('highlight',{}).fadeOut('normal',function(){
                            $(this).remove();
                        });*/
                        $.post('/' + type + '/confirm_enrollment', { username: user, state: state, reference: id_reference, ajax: 'Y' });
                    }
                    break;
                case 'A':
                    $.post('/' + type + '/confirm_enrollment', { username: user, state: state, reference: id_reference, ajax: 'Y' });
                    if (study == 'course')
                        $('#li_'+user+' #student-status').html("Enrolled");
                    else
                        $('#li_'+user+' #student-status').html("Attending");
                    $('#action_'+user).html('<a style="float: none;" href="#" class="action-enrollment" rel="K'+user+'">Dismiss from ' + (study == 'webclass'? 'Web Class':'course') + '</a>').effect('highlight',{});
                    break;
        }
        return false;
    },
    init: function(){
        if ($('#academy.dashboard').length == 0 && $('#academy.events').length == 0 && $('form#create-event').length == 0 && $('form#create-webclass').length == 0 && $('form#create-webclass-2').length == 0) return;
        //Añadir invitados, por lista de contactos o escribiendo sus mails
        $('#contacts-sclipo li > :checkbox').click(this.addContact);
        $('#invite-mail').click(this.addMails);

        //Borrar invitados
        $('#invite-students > li > a').live('click',this.remove); //cuando solo esta en link de remove
        $('#invite-students > li ul li:nth-child(3) > a').live('click',this.remove); //cuando hay mas enlaces, debe ser el Ãºltimo (3!)

        $('form#create-event')
            .submit(this.hiddens)

        $('a.send-message, button.send-message').live('click',this.sendMessage);

        // If we are in "create events", that's it for now!
        if ($('form#create-webclass').length == 0 && $('form#create-webclass-2').length == 0) return;

        //para echar a un alumno de un curso/webclass
        $('a.action-enrollment, a.action-webclass').live('click', this.enrollment);

        //Fecha creacion webclass
        var webclass_start = new Date(2009,1,27); // new Date(year, month-1,day)
        var minDate = new Date(); // today
        var currentYear = minDate.getFullYear();
        if (webclass_start - minDate > 0) minDate = webclass_start;
        Date.format = 'dd/mm/yyyy';
        $('#start_date').datepicker({minDate:minDate, maxDate: '+1y', format: 'Y-m-d'});

        //enviar mensaje
        //$('a.send-message, button.send-message').click(this.sendMessage);


        // Inicializar fecha y hora webclass

        $('a.wc_start_later').click(function(event){
            $("#method_face_time_hour").show();
            $("#method_face_time_min").show();
            $("#method_face_time").show();
            $("#method_face_time_edit").hide();
            $('#schedule-later').hide();
            $('#schedule-now').show();
            return false;
        });

        $('a.wc_start_now').click(function(event){
            var today=new Date();
            var nextminute = today.getTime();
            today.setTime(nextminute);
            var month = today.getMonth()+1;
            if (month < 10)
            {
                month = '0'+month;
            }
            var day = today.getDate();

            var hour = today.getHours();
            if (day < 10)
            {
                day = '0'+day;
            }
            if (hour < 10)
            {
                hour = '0'+hour;
            }

            var minutes = today.getMinutes();
            if (minutes < 10)
            {
                minutes = '0'+minutes;
            }

            $('#start_date').val(month+'/'+day+'/'+today.getFullYear());
            $('#start_time').val(hour+':'+minutes);
            event.stopPropagation();
            return false;
        });

        //Esto nos sirve para las invitaciones de cursos y de webclasses
        $('form#create-webclass-2')
            .submit(this.hiddens)
            .validate({
                errorContainer: $("form#create-webclass-2 div.container-error"),
                errorLabelContainer: $("ul", $("form#create-webclass-2 div.error")),
                wrapper: 'li'
            });
    }
};

//importar mails en create webclass paso 2
var importMails = function(){
    $('#import-mail').click(function(){
        //$.facebox.settings.opacity = 0;
        $.facebox.settings.modal = false;
        $.facebox( { ajax: '/import/address' } );
        return false;
    })
};

//create course
var createCourse = {
    counters: function(){
        $("#academy.courses #description:visible").charCounter(1000, {
            container: "<p></p>",
            classname: "note",
            format: "%1/1000",
            pulse: false,
            delay: 10
        });

        $("#academy.courses #objective:visible").charCounter(1000, {
            container: "<p></p>",
            classname: "note",
            format: "%1/1000",
            pulse: false,
            delay: 10
        });

        $("#academy.courses #target:visible").charCounter(150, {
            container: "<p></p>",
            classname: "note",
            format: "%1/150",
            pulse: false,
            delay: 10
        });

        $("#academy.courses #requirements:visible").charCounter(150, {
            container: "<p></p>",
            classname: "note",
            format: "%1/150",
            pulse: false,
            delay: 10
        });
    },
    autoCheck: function(){
        //si hemos escrito algo autochequeamos
        if ($(this).val() != '' && $(this).val() != null) $(this).parent().prev().get(0).checked = true;
        else $(this).parent().prev().get(0).checked = false;
    },
    hideLocation: function(){
        if ($('#method_face').is(':checked') == false)
        {
            $('#method_face_toggle').hide();
        }
        $('#method_face').click(function(){
            if ($(this).is(':checked')) $('#method_face_toggle').slideDown();
            else $('#method_face_toggle').slideUp();
        });
    },
    startDateSelected: function(dateText){
        $('#method_face_end_date').datepicker("option",{minDate:new Date(dateText), maxDate: '+1y'});
        var currentEndDateText = $('#method_face_end_date').val();
        if (currentEndDateText != null && currentEndDateText != ''){
            var currentEndDate = new Date(currentEndDateText);
            if (currentEndDate - new Date(dateText) < 0)
            {
                $('#method_face_end_date').val(dateText);
            }
        }
        $('#application_deadline').datepicker("option",{minDate:new Date(), maxDate: new Date(dateText)});
        var currentDeadlineDateText = $('#application_deadline').val();
        if (currentDeadlineDateText != null && currentDeadlineDateText != ''){
            var currentDeadlineDate = new Date(currentDeadlineDateText);
            if (currentDeadlineDate - new Date(dateText) < 0)
            {
                $('#application_deadline').val(dateText);
            }
        }
    },
    init: function(){
        this.counters();
        this.hideLocation();
        $('#method_face_date').datepicker({minDate:new Date(), maxDate: '+1y',onSelect:this.startDateSelected});
        $('#method_face_end_date').datepicker({minDate:new Date(), maxDate: '+1y'});

        $('#application_deadline').datepicker({minDate:new Date(), maxDate: '+1y'});

        jQuery.validator.addMethod("online_url", function(value, element) {
            var x = jQuery.validator.methods.url.call(this, value, element);
            return !($('#method_online').is(':checked') && (($('#method_online_web').val() == '') || ($('#method_online_web').val() == 'http://' || !x)) );
            }, "");

        //validaciones
/*
        $('#academy.courses form#create-course').validate({
            focusInvalid: false,
            onfocusout: false,
            onkeyup: false,
            invalidHandler: function(form, validator) {
                              var errors = validator.numberOfInvalids();
                              if (errors) {
                                location.href="#course-preview";
                              } else {
                                $("div.error").hide();
                              }
            },
            showErrors: function(errorMap, errorList) {
                            this.defaultShowErrors();
                            if (errorList.length > 0){
                                var jj = errorMap["method_online_web"] !== null;
                                if (errorMap["method_online_web"] !== null){
                                    location.href="#course-preview";
                                }
                            }
            },
            rules: {
                method_face_date: {
                  required: function () {
                    return ($('input[name=times]:checked').val() == 'D' && $('#method_face_date').val() == '');
                  }
                },
                method_face_end_date: {
                  required: function () {
                    return ($('input[name=times]:checked').val() == 'D' && $('#method_face_end_date').val() == '' && !$('#ongoing_end').is(':checked'));
                  }
                },
                other: {
                  required: function () {
                    return $('#category').val() == 12 && $('#other').val() == '';
                  }
                },
                method_online_web: {
                    online_url: true
                }
            },
            errorContainer: $("#academy.courses form#create-course div.container-error"),
            errorLabelContainer: $("ul", $("#academy.courses form#create-course div.error")),
            wrapper: 'li'
        });
*/
        //ongoing check
        $('#ongoing_end').click(function(){
            if ($(this).is(':checked')) $(':input', $(this).parent()).not($(this)).attr('disabled','disabled');
            else $(':input[disabled]', $(this).parent()).not($(this)).removeAttr('disabled');
        })

		$('#createcourse_1').live('click', function(e){
		    var isOk = true;

		    $(".container-error").hide();
		    $(".container-error li").hide();
		    if ($("#title").val() == "") {
		        $("#errtitle").show();
		        isOk = false;
		    }
		    if ($("#description").val() == "") {
		        $("#errdescription").show();
		        isOk = false;
		    }
		    if ($("#tags").val() == "") {
		        $("#errtags").show();
		        isOk = false;
		    }
		    if ($('#category').attr('selectedIndex') == 0) {
		        $("#erreduarea").show();
		        isOk = false;
		    }
		    if ($('#country').attr('selectedIndex') == 0) {
		        $("#erreducountry").show();
		        isOk = false;
		    }
		    var start = new Date ($("#start_date").val()+" "+$("#start_time").val());
		    var end = new Date ($("#end_date").val()+" "+$("#end_time").val());

		    if (start > end || end.getTime()-start.getTime() < 15*60*1000) {
		        $("#errwrongdate").show();
		        isOk = false;
		    }

		    if (!isOk){
		        $(".container-error").show();
				return false;
			}else{
				$('#create-course').submit();
			}
		});
    }
};

//premium
var premium = {
    toggle: function(){
        //hay que cambiar esto (antes era td[colspan], ahora td[colspan] table para distinguirla de los títulos)
        $(this)
            .parent()
            .prev('.toggle')
            .find('td:first')
            .css('padding-left', '14px')
            .find('.wrapper-bubble')
            .prepend('<a href="#" class="toggle"><img src="/scimg/premium-closed.png" /></a> ');
    },
    bubble: function(){
        var $$ = $(this);
        var layout = '<div class="bubble">' + $(this).attr('alt') + '</div>';
        $$.parent().append(layout);
    },
    toggleLink:function(){
        var td = $(this).parents('tr.toggle').next().find('td[colspan]');

        if (td.is(':hidden')) {
            td.show();
            $('img',$(this)).attr('src','/scimg/premium-opened.png');
        }
        else {
            td.hide();
            $('img',$(this)).attr('src','/scimg/premium-closed.png')
        }

        return false;
    },
    init: function(){
        if ($('body#premium').length == 0) return;

        $('#premium-button').live('click', function(){
            if ($("#sign").length > 0)
            {
                $('form').append('<input type="hidden" name="premium" value="1">');
                $('#login').slideDown('fast'); //no esta logueado
            }
            else{
                $.facebox.settings.opacity = 0.5;
                $.facebox.settings.modal = true;
                $.facebox( { ajax: '/paypal/pay/PROFESSIONAL' } );
            }
            return false;
        });

        $('#premium-live-button').live('click', function(){
            if ($("#sign").length > 0)
            {
                $('form').append('<input type="hidden" name="premiumlive" value="1">');
                $('#login').slideDown('fast'); //no esta logueado
            }
            else{
                $.facebox.settings.opacity = 0.5;
                $.facebox.settings.modal = true;
                $.facebox( { ajax: '/paypal/pay/LIVE' } );
            }
            return false;
        });

        /*if (navigator.userAgent.indexOf('MSIE 6.0')+1) {
            $('td[colspan]').addClass('noborder'); //fucking IE
        }*/

        $('td.subtable').each(this.toggle); //añadir enlace para mostrar parte escondida
        $('td a.toggle').live('click',this.toggleLink); //añadir/esconder subbloques
        $('img.more-info').each(this.bubble);

        //mostrar/ocultar bubbles
        $('img.more-info').live('mouseover',function(){
            $('.bubble',$(this).parent()).show();
        })
        .live('mouseout',function(){
            $('.bubble',$(this).parent()).hide();
        });

        /*$('th.standard,td.standard').hover(function(){
            $('th.standard,td.standard').addClass('hover');
        },function(){
            $('th.standard,td.standard').removeClass('hover');
        }); //hover column

        $('th.premium,td.premium').hover(function(){
            $('th.premium,td.premium').addClass('hover');
        },function(){
            $('th.premium,td.premium').removeClass('hover');
        }); //hover column
        */
    }
}

function isValidEmailAddress(emailAddress) {
    var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
    return pattern.test(emailAddress);
}
function validateAjaxLogin(){
    $('#ucLogin').css('border','1px solid #ccc');
    $('#pcLogin').css('border','1px solid #ccc');

    if ($('#ucLogin').val() == '' || !isValidEmailAddress($('#ucLogin').val()))
    {
        $('#ucLogin').focus();
        $('#ucLogin').css('border', '1px solid #f00');
        return false;
    }
    if ($('#pcLogin').val() == '')
    {
        $('#pcLogin').css('border', '1px solid #f00');
        $('#pcLogin').focus();
        return false;
    }
    return true;
}

var login = function(){
    if (document.getElementById('nav_join')){

        //desactivamos form de busqueda
        // $('#finder :input').attr('disabled','disabled');
        $('a')
            .not('.normal-link')
            .not($('#join-new a'))
            .not($('#fb-connect a'))
            .not('#sign')
            .not($('#facebox a'))//.not($('#premium table#pricing a'))
            .not($('#footer a')) //con livequery click no funciona, todavia no se porque
            .not('.truncate_more_link')
            .not('.login-required')
            .not('.close')
            .not('.toggle')
            .not('.ignore')
            .click(function(){
                if (!document.getElementById('nav_join')) return false;
                var link = $(this);
                // location.href= "#main_nav";
                $.facebox.settings.opacity = 0.5;
                $.facebox.settings.modal = false;
                $.facebox( { ajax: '/join/show' } );

                $(document).bind('ACTION_BEFORE_LOGIN', function() {
                    var href = link.attr('href'); var rel = link.attr('rel'); //var id   = link.attr('id'); var class = link.attr('class');
                    // Si hay una URL en el href, dirigirse alli
                    if (href != '' &&  href != '#'){    //href.charAt(0) != '#'){
                        if (rel == 'facebox') {
                            data = $(href).html();
                            $.facebox( data );
                        }
                        else {
                            $(document).trigger('close.facebox');
                            location.href = href;
                        }
                    }else{
                        // Si no, lanzar el evento click del elemento pulsado inicialmente
                        $(document).trigger('close.facebox');
                        link.trigger('click');
                    }
                });

                //al cargar el facebox
                $(document).bind('reveal.facebox', function() {

                    // FB.XFBML.Host.parseDomTree();

                    $('.signin,#signin').click(function(){
                        $(document).trigger('close.facebox');
                        $('#login').slideDown('fast');
                        return false;
                    });

                    //validacion de email y pass del login!
                    $('#fLogin').submit(function() {
                        return validateAjaxLogin();
                    });

                    //validacion join
                    validate_signup();
                    $('#userEmail').blur(checkmail);
                    $('#userPass').keyup(function(){$('#chkpass').html('' + passwordStrength($('#userPass').val(),$('#userEmail').val()))});
                    $('#userFirstName, #userLastName').autoClean();

                }); //
            return false;
        });
    }

    $('#partner_view_page').click(function(){
        if ( $('#signup').length != 0) {
            $('#userEmail').focus();
            return false;
        }
        var link = $(this);
        $.facebox.settings.opacity = 0.5;
        $.facebox.settings.modal = false;
        $.facebox( { ajax: '/join/show' } );

        $(document).bind('ACTION_BEFORE_LOGIN', function() {
            var href = link.attr('href'); //var rel  = link.attr('rel'); var id   = link.attr('id'); var class = link.attr('class');
            // Si hay una URL en el href, dirigirse alli
            if (href != '' && href[0] != '#'){
                location.href = href;
            }else{
                // Si no, lanzar el evento click del elemento pulsado inicialmente
                link.trigger('click');
            }
        });


        //al cargar el facebox
        $(document).bind('reveal.facebox', function() {

            // FB.XFBML.Host.parseDomTree();

            $('.signin,#signin').click(function(){
                $(document).trigger('close.facebox');
                $('#login').slideDown('fast');
                return false;
            });

            //validacion de email y pass del login!
            $('#fLogin').submit(function() {
                return validateAjaxLogin();
            });

            //validacion join
            validate_signup();
            $('#userEmail').blur(checkmail);
            $('#userPass').keyup(function(){$('#chkpass').html('' + passwordStrength($('#userPass').val(),$('#userEmail').val()))});
            $('#userFirstName, #userLastName').autoClean();

        });

        return false;
    });

}

function join_click() {
    if (!document.getElementById('nav_join')) return false;
    var link = $(this);
    location.href= "#main_nav";
    $.facebox.settings.opacity = 0.5;
    $.facebox.settings.modal = false;
    $.facebox( { ajax: '/join/show' } );
    $(document).bind('ACTION_BEFORE_LOGIN', function() {
        var href = link.attr('href'); //var id   = link.attr('id'); var class = link.attr('class');
        var rel = link.attr('rel');
        // Si hay una URL en el href, dirigirse alli
        if (href.length && href != '' && href.charAt(0) != '#'){
            location.href = href;
        }else{
            // Si no, lanzar el evento click del elemento pulsado inicialmente
            if (href == '#' && rel != 'facebox') {
                $(document).trigger('close.facebox');
            }
            link.trigger('click');
        }
    });

    //al cargar el facebox
    $(document).bind('reveal.facebox', function() {

        // FB.XFBML.Host.parseDomTree();

        $('.signin,#signin').click(function(){
            $(document).trigger('close.facebox');
            $('#login').slideDown('fast');
            return false;
        });

        //validacion de email y pass del login!
        $('#fLogin').submit(function() {
            return validateAjaxLogin();
        });

        //validacion join
        validate_signup();
        $('#userEmail').blur(checkmail);
        $('#userPass').keyup(function(){$('#chkpass').html('' + passwordStrength($('#userPass').val(),$('#userEmail').val()))});
        $('#userFirstName, #userLastName').autoClean();

    }); //
}

function checkmail(){
    if ($.trim($('#userEmail').val()) != '')
    {
        $.post('/join/email_check', {email: $('#userEmail').val()}, function(data){
            if (data == 'ok')
            {
                $('#chkmail').html('<span style="color:#8BB13F;">'+lang_join[langActive][0]+'</span>');
                return true;
            }
            if (data == 'used')
            {
                $('#chkmail').html('<span style="color:#B70202;">'+lang_join[langActive][1]+'</span>');
                $('#userEmail').focus();
                return false;
            }
            if (data == 'invalid')
            {
                $('#chkmail').html('<span style="color:#B70202;">'+lang_join[langActive][2]+'</span>');
                $('#userEmail').focus();
                return false;
            }
        });
    }
}

function lostPassword(){
    $('#lostPassword').slideDown();
}

var addContent = {
    bubble: function(){
        var $$ = $(this);
        var layout = '<div class="bubble">' + $(this).attr('alt') + '</div>';
        $$.parent().append(layout);
    },
    toggle: function(){
        $(this).hide().prev().append(' <a class="toggle-link" href="#">'+lang[langActive][0]+'</a>');
    },
    toggleLink: function(){
        var target = $(this).parent().next();
        if (target.is(':hidden')) target.slideDown();
        else target.slideUp();
    },
    assignToCourse: function(){
        $(this).get(0).checked = false; //desmarcamos el checkbox
        var $$ = $(this).parent();

        //AÃ±adimos como invitado
        $('#courses-added').append('<li id="' + $$.attr('id') + '"><strong>' + $$.text() + '</strong><br />('+ $(this).attr('rel') +' course) <a href="#">'+lang[langActive][2]+'</a></li>').effect('highlight',{},1000);
        $$.addClass('hide');
    },
    remove: function(){
        $$ = $(this).parent();

        //lo devolvemos a la lista de cursos
        $('#assign-course li[id=' + $$.attr('id') + ']').removeClass('hide').effect('highlight',{},1000);

        //borramos de la lista
        $$.fadeOut('normal',function(){
            $(this).remove();
        });

        return false;
    },
    hiddens: function(){
        var coursesAssigned = [];

        //creo un input hidden con los cursos asignados
        $('#courses-added li').each(function(){
            coursesAssigned.push( $(this).attr('id') );
        });

        $('form#map-form')
            .find('input[name=courses_assigned]')
            .remove()
            .end()
            .append('<input type="hidden" name="courses_assigned" value="' + coursesAssigned.join(',') + '" />');

    return false;
    },
    init: function(){
        if ($('body#add-content').length == 0) return;

        //añadimos bubbles al vuelo
        $('img.more-info').each(this.bubble);

        //mostrar/ocultar bubbles
        $('img.more-info').live('mouseover',function(){
            $('.bubble',$(this).parent()).show();
        })
        .live('mouseout',function(){
            $('.bubble',$(this).parent()).hide();
        });

        //toggle de contenido protegido
        $('#privacy div.toggle').each(this.toggle);
        $('#privacy a.toggle-link').live('click',this.toggleLink);

        //añadir y borrar cursos para asignar contenido
        $('#assign-course li > :checkbox').click(this.assignToCourse);
        $('#courses-added li > a').live('click',this.remove);


        //%% hay que preparar el tpl para las validaciones, con los mensajes de error en un ul y con los elementos requeridos.
        $('form#map-form')
            .submit(this.hiddens);
        /*    esto hay que descomentarlo cuando esten listas las validaciones en el tpl
            .validate({
                errorContainer: $("#add-content form#map-form div.container-error"),
                errorLabelContainer: $("ul", $("#add-content form#map-form div.error")),
                wrapper: 'li'
            });*/
    }
}

var paypal = function(){
    if ($('#academy #create-webclass-3').length == 0) return;

    langActive = $('html').attr('lang');

    var myLang = {
        en: ['Please enter an email address to be able to receive payments through PayPal.'],
        es: ['Por favor, indica un email para poder recibir pagos a través de PayPal.'],
        de: ['Bitte eine Email-Adresse angeben, um Bezahlungen über PayPal erhalten zu können.']
    };

    $('#academy #create-webclass-3').submit(function(){
        if (parseInt($('#price').val()) > 0 && $('#paypal_account').val() == '') {
            alert(myLang[langActive][0]);
            return false;
        }
    })

    $('#price').change(function(){ //si pongo precio, marco el check de paypal y compruebo direccion
        if (parseInt($(this).val()) > 0) $('#paypal').get(0).checked = true;
        else $('#paypal').get(0).checked = false;
    })
};


var webclassSecret = {
    bubble: function() {
        var $$ = $(this);
        var layout = '<div class="bubble">' + $(this).attr('alt') + '</div>';
        $$.parent().append(layout);
    },
    init: function(){
        if ($('#academy.courses ul.browse p.secret').length == 0) return;

        $('p.secret img').each(this.bubble);

        //mostrar/ocultar bubbles
        $('p.secret img').live('mouseover',function(){
            $('.bubble',$(this).parent()).show();
        })
        .live('mouseout',function(){
            $('.bubble',$(this).parent()).hide();
        });
    }
};


//Upload de Add Content
function cancelUpload()
{
    $('#iframe'+$('#progress_key').val()).remove();
    //$('#progressbarinfo').toggle(); //html('Speed: Finished.  Percentage: 100%');
    //$("#uploadbar").toggle(); // progressbar({value: 100});

	var el = $('.upload_bar');
    if (el.is(':visible')) el.hide();

    langActive = $('html').attr('lang');

    var myLang = {
        en: ['Upload cancelled by user.'],
        es: ['Envio cancelado por el usuario.'],
        de: ['Upload vom Nutzer abgebrochen.']
    };

    $('#file-uploading')
        .find('img').attr('src','/scimg/uploading-failed.png').end()
        .find('strong:first').html(myLang[langActive][0]).end()
        .find('p:first').html(uploadConstants.uploadCancel).end()
        .find('span').hide().end()
        .after(uploadConstants.buttonsActions);

    $('#details-message, #file-uploading p, #upload_detail, #sidebar-narrow div.box-grey:visible').hide();

    return false;
}

var uploadContent = function(){
    if ( !$('body#upload').length && !$('body#academy.courses #file-uploading').length && !$('body#academy.courses .new-program-button').length ) return; //Limito alcance del script
    //if ( !$('body#academy.courses #file-uploading').length && !$('body#academy.courses .new-program-button').length ) return; //Limito alcance del script

    langActive = $('html').attr('lang');

    var myLang = {
        en: ['The file format you are trying to upload is not accepted. Please try a different format.'],
        es: ['El formato del archivo que estas intentando enviar no es correcto. Por favor intentalo con otro formato.'],
        de: ['Die Datei, die du hochladen willst, hat ein unbekanntes Format. Bitte versuche es mit einer anderen Datei.']
    };

    //Constantes de texto para el upload
    uploadConstants = {
        uploadSuccess: $('#uploadSuccess').text(),
        uploadCancel: $('#uploadCancel').html(),
        uploadFail: $('#uploadFail').text(),
        formSuccess: $('#formSuccess').text(),
        formSaved: $('#formSaved').text(),
        buttonsActions: $('#buttonsActions').html()
    }

    //toggles de sidebar
    $('#sidebar-narrow p.toggle > a')
        .click(function() {
            var $$ = $(this).parent().next();
            if ( $$.is(':hidden') ) {
                $$.slideDown();
                $(this).html(lang[langActive][4]+' <img src="/scimg/upload-close.png" />');
            }
            else {
                $$.slideUp();
                $(this).html(lang[langActive][3]);
            }
            return false;
        })
        .parent().next().hide();

    //$("#uploadbar").progressbar({value: 0});

    var button = $('#button1'); //, interval;

    var syllabus = 'N';

    if (button){
        new AjaxUpload(button,{
            action: '/content/doupload',
            name: 'mycontent',
            cancel: 'cancel' + $('#progress_key').val(),
            onSubmit : function(file, ext){
                //ocultamos cositas
                $('#info_text').hide();
                if ($('#upload-syllabus-ok').length) $('#upload-syllabus-ok').hide();

                //modificamos sidebar
                $('#sidebar-narrow .hide').show().siblings().hide();

                //mostramos datos de la subida, asignamos el evento de cancelar
                $('#file-uploading')
                    .find('strong:first').html(file).end()
                    .find('a.cancel').click(cancelUpload).end()
                    .show();

                var type_content = '';
                var arr_docs = ['pdf' , 'ps', 'doc', 'docx', 'ppt', 'pps', 'pptx', 'xls', 'xlsx', 'odt', 'sxw', 'odp', 'sxi', 'ods', 'sxc', 'odg', 'odf', 'txt', 'rtf'];

                // Si estamos subiendo un Syllabus, solo permitimos documentos.
                if ($('#upload_syllabus').length != 0)
                {
                    if ( $.inArray(ext[0],arr_docs) >= 0 ) type_content = 'S';
                    if ( type_content != '' ) {
                        $('#type option[rel!='+type_content+']').hide();
                    }
                    else {
                        alert(myLang[langActive][0]);
                        $('#file-uploading').hide();
                        return false;
                    }
                    syllabus = 'Y';
                }
                else
                {
                    var arr_videos = ["avi", "mjpg", "mp4", "mpeg", "mov", "mp4", "3gp", "wmv", "flv"];
                    var arr_audio = ['mp3', 'wav'];
                    var arr_image = ['jpg', 'jpeg', 'png', 'gif', 'tif', 'tiff', 'bmp'];
                    if ( $.inArray(ext[0],arr_docs) >= 0 ) type_content = 'D';
                    else if ( $.inArray(ext[0],arr_videos) >= 0 ) type_content = 'V';
                    else if ( $.inArray(ext[0],arr_audio) >= 0 ) type_content = 'A';
                    else if ( $.inArray(ext[0],arr_image) >= 0 ) type_content = 'I';

                    if ( type_content != '' ) {
                        $('#type option[rel!='+type_content+']').hide();
                    }
                    else {
                        alert(myLang[langActive][0]);
                        window.location.href = '/content/upload';
                        return false;
                    }
                }

                /* Setting data */
                this.setData({
                    'UPLOAD_IDENTIFIER': $('#progress_key').val(),
                    'ID': $('#ID').val(),
                    'content_id': $('#content_id').val(),
                    'syllabus': syllabus
                });

                //modificamos contenido principal
                $('#title').val(file.substring(0, file.indexOf('.')).replace(/_/g,' '));

                //mostramos formulario de info sobre la subida
                $('#upload_detail').slideDown('fast');

                // change button text, when user selects file
                //button.hide(); // text('Cancel');

                //las interacciones relacionadas con el form de describir contenido, le paso el id para poder relacionarlo
                uploadDetails($('#ID').val());

                // If you want to allow uploading only 1 file at time disable upload button
                //this.disable();
                // Llamamos a uploadprogress para mostrar la barra actualizada cada segundo
                window.setTimeout("$.uploadProgressUpdate('"+$('#progress_key').val()+"')", 1000);
            },
            onComplete: function(file, response){
                var error = response.split(':')[0];
                if (error == '')
                {
                    $('#mime_type').val(response.split(':')[1]);
                    if (syllabus == 'N') $('#content_type').val(response.split(':')[2]);
                    $('#file_name').val(file);
					$('.upload_progress_bar').css('width', '100%');
					var el = $('.upload_bar');
	                if (el.is(':visible')) el.hide();					

                    //modificamos mensaje de exito al guardar los datos relacionados al contenido subido
                    $('#file-uploading')
                        .addClass('uploaded')
                        .find('img').attr('src','/scimg/uploading-success.png').end()
                        .find('p:first').html(uploadConstants.uploadSuccess).end()
                        .find('span').hide().end()
                        .find('#details-message:visible strong').html('Success!').end()
                        .find('#details-message:visible p').html(uploadConstants.formSaved);

                    if (syllabus == 'Y') {
                        saveUploadDetails($('#ID').val(), 'Y');
                    }
                    else {
                        //guardo el formulario si el usuario ha hecho submit
                        if ($('#upload_detail').is(':hidden')) saveUploadDetails($('#ID').val(), 'N');
                    }
                }
                else
                {
                    alert('Error: ' + error);
                }
            }
        });
    }
};

$.extend({
    uploadProgressUpdate: function(id) {
        var stamp = new Date().getTime();   // for IE request cache distinction
        var fail;

        $.ajax({url: '/content/progress', data:{'upload_id':id, 'rnd':stamp}, success:
            function(data) {
/*
                var el = $('#tmp_upload_bar');
                if (el.is(':visible')) $('#tmp_upload_bar').hide();
*/
/*
				var el = $('.upload_bar');
                if (el.is(':visible')) $('.upload_bar').hide();
*/
                if (data['error']) {
                    return false;
                }

                var percentage = Math.floor(100 * parseInt(data['bytes_uploaded']) / parseInt(data['bytes_total']));
                sec = parseInt( data['est_sec'] );
                hours=Math.floor(sec/3600);
                minutes=(Math.floor((sec%3600)/60) < 10)?'0'+Math.floor((sec%3600)/60):Math.floor((sec%3600)/60);
                seconds=(((sec%3600)%60) < 10)?'0'+(sec%3600)%60:(sec%3600)%60;
                if (hours > 0) {
                    var time_rem = hours + ":" + minutes + ":" +seconds;
                } else {
                    var time_rem = minutes + ":" +seconds;
                }
/*
                var uploadBar = '<div class="progress_bar"><div class="progress" style="width: '+ percentage +'%;"><div style="width: '+ percentage +'%;"></div><span>';
                uploadBar += lang_upload[langActive][0] + ' | ' + lang_upload[langActive][1] +' '+Math.floor(parseInt(data['speed_average'])/1024) + 'Kbps.  ' + lang_upload[langActive][2] + ' ' + percentage + '%.  ' + lang_upload[langActive][3] + ' ' + time_rem+'.';
                uploadBar += '</span></div></div>';

                $('#upload_progress_bar').html( uploadBar );
*/
				var uploadBar = lang_upload[langActive][0] + ' | ' + lang_upload[langActive][1] +' '+Math.floor(parseInt(data['speed_average'])/1024) + 'Kbps.  ' + lang_upload[langActive][2] + ' ' + percentage + '%.  ' + lang_upload[langActive][3] + ' ' + time_rem+'.';
				$('.upload_text_bar').html(uploadBar);
				$('.upload_progress_bar').css('width', percentage+'%');

                window.setTimeout("$.uploadProgressUpdate('"+id+"')", 1000);
            }, dataType:'json', error:function(xhr, err, et) {
                return false;
            }
        });
    }
});

//interacciones del formulario para describir contenido (le paso como parametro el ID)
var uploadDetails = function(id){

    //añadir cursos
    $('div.col-left > div.box li > :checkbox').live('click',function(){
        $(this).get(0).checked = false; //desmarcamos el checkbox
        var $$ = $(this).parent();
        //Añadimos curso y truncamos a 40 caracteres
        if ($$.text().length > 40) var text = $$.text().substring(0,40)+'...';
        else var text = $$.text();
        $('div.col-right > div.box > ul').append('<li id="' + $$.attr('id') + '">' + text  + ' <a href="#">'+lang[langActive][2]+'</a></li>').effect('highlight',{},1000);
        $$.addClass('hide'); //Ocultamos el original
    });

    //borrar cursos añadidos
    $('div.col-right > div.box li > a').live('click',function(){
        $$ = $(this).parent();
        $('div.col-left > div.box li[id=' + $$.attr('id') + ']').removeClass('hide').effect('highlight',{},1000);
        $$.fadeOut('normal',function(){ $(this).remove() });
        return false;
    });

    //si clickan a editar simplemente vuelvo a desplegar el formulario (y oculto los botones ya que puede haber finalizado el upload) y el privacy
    $('#details-message a').live('click',function(){
        $('#file-uploading')
            .find('#details-message').hide().end()
            .next().hide(); //ocultamos botones (estan dentro de <p>)
        $('#sidebar-narrow div.box-grey:last-child').show(); //mostramos privacy
        $('#upload_detail').slideDown();
    });

    //submit del formulario
    $('#details').live('submit',function(){
        //genero array de cursos añadidos
        var addedCourses=[];
        //recorro cursos añadidos y así voy llenando un array
        $('div.col-right > div.box li').each(function(){ addedCourses.push( $(this).attr('id')) });

        //agrego un input hidden con los valores
        $(this)
            .find('input[name=added_courses]')
            .remove()
            .end()
            .append('<input type="hidden" name="added_courses" value="' + addedCourses.join(',') + '" />');

        //ocultamos el formulario y el sidebar de privacidad
        $('#upload_detail').hide();
        $('#sidebar-narrow div.box-grey:visible').hide();

        //si el upload ya ha terminado puedo enviar la peticion ajax directamente
        if ( $('#file-uploading').hasClass('uploaded') ) saveUploadDetails(id);
        else{
            $('#details-message')
                .find('strong').html('Success!').end()
                .find('p').html(uploadConstants.formSuccess).end()
                .show();
        }

        return false;
    });
}

var saveUploadDetails = function(id, syllabus){
    uploadConstants = {
        uploadSuccess: $('#uploadSuccess').text(),
        uploadCancel: $('#uploadCancel').html(),
        uploadFail: $('#uploadFail').text(),
        formSuccess: $('#formSuccess').text(),
        formSaved: $('#formSaved').text(),
        buttonsActions: $('#buttonsActions').html()
    }

    $.ajax({
        type : 'post',
        url: '/content/save/',
        data : $('#details').serialize()+'&id='+id,
        success : function(data){
            $('#file-uploading')
                .find('p:first').html(uploadConstants.uploadSuccess).end()
                    .find('#details-message')
                        .find('strong').html(lang[langActive][6]).end()
                        .find('p').html(uploadConstants.formSaved).end()
                        .show().end()
                        .after(uploadConstants.buttonsActions);

            var content_type = $('#content_type').val();
            var username = $('#username').val();

            if (content_type == 'V') content = 'video';
            else if (content_type == 'D') content = 'document';
            else if (content_type == 'A') content = 'audio';
            else if (content_type == 'I') content = 'image';
            else content = 'none';

            if (syllabus == 'Y') {
                $('.course_program_box').hide();
                $('#file-uploading').hide();
                content = 'syllabus';
            }
			var el = $('.upload_bar');
            if (el.is(':visible')) el.hide();
/*
            if (content != 'none') pageTracker._trackEvent('CONTENT', 'New ' +  content + ' added', username);
            if (content != 'none') _gaq.push(['_trackEvent', 'CONTENT', 'New ' +  content + ' added']);
            */
        }
    });
}


function deleteCourse(reference, academy, webclasses) {
    var message = '';
    if (webclasses > 0){
        if (webclasses > 1){
            message = 'Are you sure you want to remove this course? If you delete this course, all ' + webclasses + ' web classes associated with this course will be deleted too.';
        }else{
            message = 'Are you sure you want to remove this course? If you delete this course, the web class associated with this course will be deleted too.';
        }
    }else{
        message = 'Are you sure you want to remove this Course?';
    }
    if (confirm(message))
    {
        $.post('/courses/delete', {reference: reference},
        function(data){
            window.location = '/academy/courses/' + academy;
        });
    }
}

//interacciones al editar video o documento
var edit = {
    assignToCourse: function(){
        //añadir cursos
        $('div.col-left > div.box li > :checkbox').live('click',function(){
            $(this).get(0).checked = false; //desmarcamos el checkbox
            var $$ = $(this).parent();
            //Añadimos curso y truncamos a 40 caracteres
            if ($$.text().length > 40) var text = $$.text().substring(0,40)+'...';
            else var text = $$.text();
            $('div.col-right > div.box > ul').append('<li id="' + $$.attr('id') + '">' + text  + ' <a href="#">'+lang[langActive][2]+'</a></li>').effect('highlight',{},1000);
            $$.addClass('hide'); //Ocultamos el original
        });

        //borrar cursos añadidos
        $('div.col-right > div.box li > a').live('click',function(){
            $$ = $(this).parent();
            $('div.col-left > div.box li[id=' + $$.attr('id') + ']').removeClass('hide').effect('highlight',{},1000);
            $$.fadeOut('normal',function(){ $(this).remove() });
            return false;
        });
    },

    selectThumb: function(){
        //seleccion de thumbnail
        $('#thumbnail-selection li input, #thumbnail-selection li label').hide();
        $('#thumbnail-selection li img').click(function(){
            //eliminamos seleccion actual (imagen y radio)
            $('#thumbnail-selection li img.selected').removeClass('selected');
            $('#thumbnail-selection li input:checked').removeAttr('checked');
            //seleccionamos esta (imagen y radio)
            $(this).addClass('selected').parent('li').find('input').attr('checked','checked');
            // Actualizamos el thumbnail superior
            $('#upper-thumb').attr('src',$(this).attr('src'));
        });
    },

    beforeSubmit: function(){
        //genero array de cursos añadidos
        var addedCourses=[];
        //recorro cursos añadidos y así voy llenando un array
        $('div.col-right > div.box li').each(function(){ addedCourses.push( $(this).attr('id')) });

        // Genero otro array con los cursos no seleccionados
        var notAddedCourses = [];
        $('div.col-left > div.box li[class!=hide]').each(function(){ notAddedCourses.push( $(this).attr('id')) });

        //agrego un input hidden con los valores
		$('input[name=added_courses]').val( addedCourses.join(',') );
		$('input[name=not_added_courses]').val( notAddedCourses.join(',') );
/*
         $('form.edit-content')
            .find('input[name=added_courses]')
            .remove()
            .end()
            .append('<input type="hidden" name="added_courses" id="added_courses" value="' + addedCourses.join(',') + '" />');

         $('form.edit-content')
            .find('input[name=not_added_courses]')
            .remove()
            .end()
            .append('<input type="hidden" id="not_added_courses" name="not_added_courses" value="' + notAddedCourses.join(',') + '" />');
*/
        return true;
    },

    toggle: function(){
        var target = $(this).next();

        if ( target.is(':visible')) {
            $(this).find('span').addClass('closed');
            target.slideUp();
        }
        else {
            $(this).find('span').removeClass('closed');
            target.slideDown()
        }
    },

    init: function(){
        if ( !$('body#video')[0] && !$('body#documents')[0] ) return;

        $('h2').click(this.toggle); //toggle de cada modulo
        this.assignToCourse(); //interacciones para asignar el contenido a cursos
        this.selectThumb(); //selección de imagen para el contenido
        $('form.edit-content').submit(this.beforeSubmit) ; //antes de hacer el submit genero los inputs para los cursos asociados al contenido
    }
}

function facebookInvite(){
    $("#fb-invite").live("click", function() {
        var title = null;
        if ( $('#academy.webclass').is('body') && $(this).attr('rel').length != 0)
        {
            var title = 'Promote this Web Class to your Facebook Friends';
            var actionpost = 'webclasses/view/'+$(this).attr('rel');
            var type = 'Web Class';
            var content = 'I\'m teaching this live web class and I\'d like you to attend: <a href="http://sclipo.com/webclasses/view/'+$(this).attr('rel')+'">'+$('#title').val()+'</a>.';
            var actiontext = 'Friends that apply to attend will appear in your student list.';
            var invitation = 'false';
        }
        // En Academy/Webclasses, el body tambien tiene class=courses (en lugar de webclass),
        // por tanto hay que distinguir donde estamos de otra manera
        if ($('#academy.courses').is('body') && $(this).attr('rel').length != 0){
            if ($('#current_class_date').is('input'))
            {
                // El campo current_class_date solo existe en Academy/Webclasses List
                var title = 'Promote Web Classes to Your Facebook Friends';
                var actionpost = '/academy/webclasses/'+$(this).attr('rel');
                var type = 'Web Classes';
                var content = '<a href="http://sclipo.com/academy/webclasses/'+$(this).attr('rel')+'">Check out the web classes I\'m teaching on Sclipo</a>, a social learning network where people teach, learn and meet others with common educational interests.';
                var actiontext = 'Tell Your Friends About the Web Classes You Teach on Sclipo.';
                var invitation = 'false';
            }else if($('#courses_browse').is('input')){
                // El campo con id=courses_browse solo existe en Academy/Courses List
                var title = 'Promote Courses to Your Facebook Friends';
                var actionpost = '/academy/courses/'+$(this).attr('rel');
                var type = 'Courses';
                var content = '<a href="http://sclipo.com/academy/courses/'+$(this).attr('rel')+'">Check out the courses I\'m teaching on Sclipo</a>, a social learning network where people teach, learn and meet others with common educational interests.';
                var actiontext = 'Tell Your Friends About the Courses You Teach on Sclipo.';
                var invitation = 'false';

            }else{
                // Ninguna de las anteriores: estamos en la pantalla de invitar estudiantes de un curso, o en la ficha de un curso (course/view)
                var title = 'Promote this Course to your Facebook Friends';
                var actionpost = '/courses/view/'+$(this).attr('rel');
                var type = 'Course';
                var content = 'I\'m teaching this course and I\'d like you to enroll: <a href="http://sclipo.com/courses/view/'+$(this).attr('rel')+'">'+$('#title').val()+'</a>.';
                var actiontext = 'Friends that enroll will appear in your student list.';
                var invitation = 'false';
            }
        }

        if ( $('#import.invite').is('body') )
        {
            var title = 'Invite Students to Your Academy';
            var actionpost = 'import/invite';
            var type = 'Academy';
            var content = '<a href="http://sclipo.com/academy/view/'+$(this).attr('rel')+'">Visit my teaching academy on Sclipo</a>, a social learning network where people teach, learn and meet others with common interests.';
            var actiontext = 'Invite Facebook friends to learn in your academy.';
            var invitation = 'true';
        }

        if ( $('#partner').is('body'))
        {
            var title = 'Invite Students to Your Academy';
            var actionpost = 'import/invite';
            var type = 'Academy';
            var content = '<a href="http://sclipo.com/welcome/partner/'+$(this).attr('rel')+'">Visit my teaching academy on Sclipo</a>, a social learning network where people teach, learn and meet others with common interests.';
            var actiontext = 'Invite Facebook friends to learn in your academy.';
            var invitation = 'true';
        }


        content = content.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;');

        if ( title != null)
        {
            var reference = $(this).attr('rel');
            popupFbInvite(title, actionpost, type, content, actiontext, reference, invitation);
        }
        return false;
    });
}

function open_meeting(){
    if ( !document.getElementById('nav_join') ){ //si el usuario está logado

        $("#academy.meeting #invite-meeting[rel]").click(function(){
            $.facebox( { ajax: '/meeting/show_share/'+$(this).attr('rel') } );
            return false;
        });
        $("#academy.meeting #open-meeting[rel]").click(function(){
            var username = $('#username').val();
            // pageTracker._trackEvent('LIVETEACHING', 'Meeting attendance', username);
            //_gaq.push(['_trackEvent', 'LIVETEACHING', 'Meeting attendance']);
            // pageTracker._trackEvent('LIVETEACHING', 'Meeting started', username);
            //_gaq.push(['_trackEvent', 'LIVETEACHING', 'Meeting started']);
            window.open('http://sclipo.com/meeting/enter/'+$(this).attr('rel'),'meeting','width='+screen.width+',height='+screen.height+',toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,copyhistory=no,resizable=yes');
            return false;
        });

        if ( $('#academy.meeting').is('body'))
        {
            //boton cancel
            $('#facebox #meeting-share-content #cancel').live('click', function(){ $(document).trigger('close.facebox') });

            //boton send
            $('#facebox #meeting-share-content #send').live('click',function(){

                //recojo los alumnos marcados y los mails introducidos, compruebo que haya añadido algun destinatario para compartir
                if ( $('#meeting-share-content #mails-friends').val()=='' && $('#meeting-share-content :checkbox:checked').length == 0 ) {
                    $('#messages')
                        .removeClass('correct')
                        .slideDown(function(){
                            setTimeout(function() { $('#messages').slideUp(); }, 4000);
                        });
                }
                else {
                    $.ajax({
                        type: "post",
                        url: '/meeting/share_content',
                        data: $('#facebox #meeting-share-content form').serialize(),
                        success: function(data){
                            username = $('#username').val();
                            // pageTracker._trackEvent('ASYNCHTEACHING', 'Students invited to meeting via email', username);
                            //_gaq.push(['_trackEvent', 'ASYNCHTEACHING', 'Students invited to meeting via email']);
                            $('#messages')
                                .find('ul').addClass('correct').end()
                                .find('#error_subject').hide().end()
                                .find('#error_body').html('Live meeting invitations sent successfully!').css('display', 'block').end()
                                .slideDown('slow', function(){
                                    setTimeout(function() { $(document).trigger('close.facebox'); }, 4000);
                                })
                                .siblings().hide();
                        }
                     });
                }


                return false;
            });

            //autoClean de los textareas
            $('#facebox #meeting-share-content #mails-friends').livequery(function(){
                $(this).autoClean();
            })

        }
    }
}

var community = function(){
    if (  document.getElementById('academy') ){
        $('img.more-info').each(premium.bubble);
        //mostrar/ocultar bubbles
        $('img.more-info').hover(function(){
            $('.bubble',$(this).parent()).show();
        },function(){
            $('.bubble',$(this).parent()).hide();
        });
    }
}

function open_webclass(){
    $(".open-webclass[href]").live('click',function(){
        var href = $(this).attr('href');
        if (href.substring(0,4) != 'http') href = 'http://sclipo.com'+href;
        window.open(href,'wcr','width='+screen.width+',height='+screen.height+',toolbar=no,location=no, directories=no, status=no, menubar=no, scrollbars=yes, copyhistory=no, resizable=yes');
        return false;
    });
}


var credentials = {
    add: function(){
        $('.add-credential').click(function(){
            var type = '#add-'+$(this).attr('rel');
            $('#edu_id').val('');
            $('#cer_id').val('');
            $('#exp_id').val('');

            $('#edu_degree').val('');
            $('#edu_area').val('');
            $('#cer_title').val('');
            $('#cer_awarded').val('');
            $('#exp_area').val('');
            $('#exp_degree').val('');

            $('#edu_school_other').val('');
            $('#exp_school_other').val('');

            $('#edu_other_country').val('');
            $('#exp_other_country').val('');

            $.facebox.settings.opacity = 0;
            $.facebox.settings.modal = true;

            $.facebox( { div: type } ); //%% cambiar por ajax
            //credentials.newUpload(); //genero el upload
            credentials.ajaxForm(); //envio el formulario via ajax
            credentials.location('0');

            //oculto enlace para borrar
            $('#facebox li.del').hide();
        });
    },

    edit: function(){
        //abro facebox y dependiendo del tipo de credential relleno el contenido para que el usuario edite (añado enlace para borrar)
        $('.edit-credential').live('click',function(){
            var context = $('#facebox');
                type = $(this).parents('table').attr('rel'),
                id = $(this).parents('tr').attr('rel'), //cada fila tiene un rel con un identificador
                options = '';

            //escondemos contenido del facebox hasta que cargue los datos
            var div_edit = '#add-'+type;

            $.facebox.settings.opacity = 0;
            $.facebox.settings.modal = true;
            $.facebox( { div: div_edit } );
            $('#facebox '+div_edit+' .facebox-container').before('<p class="center" style="padding:10px"><img src="/scimg/loading_alternative.gif" /></p>').hide();

            $.postJSON('/academy/viewcredentials', {id: id, type: type}, function(data){

                if (data.length != 0){
                    var info = data[0];

                    if ( type == 'certificate' ) {
                        $('#facebox '+div_edit+' p.center').remove();
                        $('#facebox '+div_edit+' .facebox-container').fadeIn();

                        selectOtherCountry = $( $('#cer_other_country', context)[0] );

                        if ( info.country == -1) {
                            selectOtherCountry.val(info.other_country).parent().show();
                        }
                        else {
                            selectOtherCountry.parent().hide();
                        }

                    }
                    else {
                        var selectCountry = $( $('#edu_country', context)[0] || $('#exp_country', context)[0] ),
                            selectState = $( $('#edu_state', context)[0] || $('#exp_state', context)[0] ),
                            selectSchool = $( $('#edu_school', context)[0] || $('#exp_school', context)[0] ),
                            selectSchoolOther = $( $('#edu_school_other', context)[0] || $('#exp_school_other', context)[0] ),
                            selectOtherCountry = $( $('#edu_other_country', context)[0] || $('#exp_other_country', context)[0] ); // || $('#cer_other_country', context)[0] );

                        options = '';
                        // Si han escogido otro pais, mostramos el edit de other_country y escondemos other school

                        if ( info.country == -1) {
                            selectOtherCountry.val(info.other_country).parent().show();
                            selectSchool.parent().hide();
                        }
                        else {
                            selectOtherCountry.parent().hide();
                            selectSchool.parent().show();
                        }

                        //1. Cargo estados (si toca) y marco el que toca en el callback
                        //2. Cargo schools y marco la que toca en el callback (si tienes other school entonces no marco y muestro ese campo)
                        if ( info.country == 'us' ||  info.country == 'ca' ) {
                            $.postJSON('/academy/get_states', {country: info.country}, function(data){
                                //muestro el select de estados
                                selectState.parent().show();

                                $.each( data, function(i, item){
                                    options += "<option value='"+ item.state +"'";
                                    if ( info.state == item.state ) options += " selected='selected'";
                                    options += ">"+ item.name +"</option>";
                                 });

                                //rellenamos select de states
                                selectState
                                    .find('option:not([value=-1]):not([value=0])')
                                        .remove()
                                        .end()
                                    .find('option:first')
                                    .after(options);

                                //cargo schools
                                $.postJSON('/academy/get_schools', {country: info.country, state: info.state}, function(json){
                                    options = '';
                                    //muestro select de escuelas si el country no es other
                                    if (info.country != -1) selectSchool.parent().show();

                                    $.each( json, function(i, item){
                                        options += "<option value='"+ item.code +"'";
                                        if (item.code == info.college) options += " selected='selected'";
                                        options += ">"+ item.name +"</option>";
                                     });

                                    //rellenamos select de escuelas
                                    selectSchool
                                        .find('option:not([value=-1]):not([value=0])')
                                            .remove()
                                            .end()
                                        .find('option:first')
                                        .after(options);

                                    //si tiene other school lo muestro
                                    if ( typeof info.other == 'string'  &&  info.other != '' ){
                                        selectSchoolOther.val(info.other).parent().show();
                                        selectSchool.find('option[value="-1"]').attr('selected', 'selected');
                                    }
                                    else selectSchoolOther.parent().hide();

                                    $('#facebox '+div_edit+' p.center').remove();
                                    $('#facebox '+div_edit+' .facebox-container').fadeIn();
                                });
                            });

                        }
                        else { //cargo escuelas si se ha escogido un pais diferente a usa o ca o si se ha escogido un estado (tambien escondo estados ya que puede ser una edición)
                            selectState.parent().hide();

                            $.postJSON('/academy/get_schools', {country: info.country, state: ''}, function(data){
                                options = '';
                                //muestro select de escuelas
                                if (info.country != -1) selectSchool.parent().show();

                                $.each( data, function(i, item){
                                    options += "<option value='"+ item.code +"'";
                                    if (item.code == info.college) options += " selected='selected'";
                                    options += ">"+ item.name +"</option>";
                                 });

                                //rellenamos select de escuelas
                                selectSchool
                                    .find('option:not([value=-1]):not([value=0])')
                                        .remove()
                                        .end()
                                    .find('option:first')
                                    .after(options);

                                //si tiene other school lo muestro
                                if ( typeof info.other == 'string'  &&  info.other != '' ){
                                    selectSchoolOther.val(info.other).parent().show();
                                    selectSchool.find('option[value="-1"]').attr('selected', 'selected');
                                }
                                else selectSchoolOther.val('').parent().hide();

                                $('#facebox '+div_edit+' p.center').remove();
                                $('#facebox '+div_edit+' .facebox-container').fadeIn();
                            });
                        }
                    }

                    switch (type) {
                        case 'education':
                            $('#edu_degree',context).val(info.degree);
                            $('#edu_area',context).val(info.major);
                            $('#edu_id',context).val(info.id);
                            $('#edu_school_other',context).val(info.other);
                            $('#edu_country',context).val(info.country);
                            $('#edu_dates-i',context).val(info.start_date.substr(0,4));
                            $('#edu_dates-f',context).val(info.end_date.substr(0,4));
                            // $('#edu_school',context).parent().show();

                            break;

                        case 'certificate':
                            $('#cer_country',context).val(info.country);
                            $('#cer_title',context).val(info.accreditation);
                            $('#cer_awarded',context).val(info.awarded);
                            $('#cer_year',context).val(info.awarded_date);
                            $('#cer_id',context).val(info.id);
                            $('#cer_other_country',context).val(info.other_country);

                            break;

                        case 'experience':
                            $('#exp_area',context).val(info.title);
                            //$('#exp_degree',context).val(info.degree);
                            $('#exp_id',context).val(info.id);
                            $('#exp_school_other',context).val(info.other);
                            $('#exp_country',context).val(info.country);
                            $('#exp_dates-i',context).val(info.start_date.substr(0,4));
                            $('#exp_dates-f',context).val(info.end_date.substr(0,4));

                            break;
                    }

                    credentials.ajaxForm();
                    credentials.location();
                    $('#facebox li.del:hidden').show();
                    credentials.del();
                }
            });

            return false;
        });
    },

    del: function(){
        context = $('#facebox');
        id = $( $('#exp_id',context)[0] || $('#edu_id',context)[0] || $('#cer_id',context)[0] );

        $('a.delete-credential',context).click(function(){
            //si se quiere se puede ofrecer confirmacion, aunque por el tema idioma no interesa
            //if ( confirm("Are you sure") )

            var type = $(this).attr('rel');
            $.post("/academy/del_credentials", {id: id.val(), type: type}, function(data){
                //if (data == 'ok')
                $('table[rel='+type+'] tr[rel='+id.val()+']').remove();
                $(document).trigger('close.facebox');
            });
            return false;
        });
    },

    newUpload: function(){
        var context = $('#facebox');
        $('#button-upload',context).click(function(){
            $('#paso-1',context).fadeOut().before('<div style="padding:10px; text-align:center"><img src="/scimg/loading_alternative.gif" /></div>');
            /*setTimeout(function(){
                $('#paso-1',contexto).prev().remove();
                $('#paso-2',contexto).html($('#add-education .facebox-container').html()).fadeIn();
            }, 1000);*/

            //cargo via ajax el contenido del crop, no se si necesitas pasarle algun parámetro
            $.post('/url/quetoque', function(data){
                $('#paso-1',context).prev().remove();
                $('#paso-2',context).html(data).fadeIn();
            });
            return false;
        });
    },

    ajaxForm: function(){
        $('#facebox form').submit(function(){
            var type = $(this).attr('rel');

            switch (type) {
                case 'education':
                    var id = $('#facebox #edu_id').val(),
                        country = $('#facebox #edu_country').val(),
                        countryName = $('#facebox #edu_country option:selected').text(),
                        otherCountry = $('#facebox #edu_other_country').val(),
                        state = $('#facebox #edu_state').val(),
                        school = $('#facebox #edu_school').val(),
                        schoolName = $('#facebox #edu_school option:selected').text(),
                        degree = $('#facebox #edu_degree').val(),
                        area = $('#facebox #edu_area').val(),
                        date_i = $('#facebox #edu_dates-i').val(),
                        date_f = $('#facebox #edu_dates-f').val(),
                        other = $('#facebox #edu_school_other').val();
                    // Tratar errores
                    // Falta country
                    if ( country == 0){
                        $('#facebox #edu_missing_country').fadeIn('slow');
                        setTimeout(function() { $('#facebox #edu_missing_country').fadeOut('slow') }, 4000);
                        return false;
                    }
                    if ( country == -1 && otherCountry == ''){
                        $('#facebox #edu_missing_other_country').fadeIn('slow');
                        setTimeout(function() { $('#facebox #edu_other_missing_country').fadeOut('slow') }, 4000);
                        return false;
                    }

                    // Falta State
                    if ( (country == 'us' || country == 'ca') && state == 0) {
                        $('#facebox #edu_missing_state').fadeIn('slow');
                        setTimeout(function() { $('#facebox #edu_missing_state').fadeOut('slow') }, 4000);
                        return false;
                    }
                    // Falta school
                    if ( school == 0) {
                        $('#facebox #edu_missing_school').fadeIn('slow');
                        setTimeout(function() { $('#facebox #edu_missing_school').fadeOut('slow') }, 4000);
                        return false;
                    }

                    if ( school == -1 && other == '') {
                        $('#facebox #edu_missing_other_school').fadeIn('slow');
                        setTimeout(function() { $('#facebox #edu_missing_other_school').fadeOut('slow') }, 4000);
                        return false;
                    }

/*
                    if ( degree == '') {
                        $('#facebox #edu_missing_degree').fadeIn('slow');
                        setTimeout(function() { $('#facebox #edu_missing_degree').fadeOut('slow') }, 4000);
                        return false;
                    }
*/

                    if ( area == '') {
                        $('#facebox #edu_missing_area').fadeIn('slow');
                        setTimeout(function() { $('#facebox #edu_missing_area').fadeOut('slow') }, 4000);
                        return false;
                    }

                    if ( date_i > date_f) {
                        $('#facebox #edu_missing_dates').fadeIn('slow');
                        setTimeout(function() { $('#facebox #edu_missing_dates').fadeOut('slow') }, 4000);
                        return false;
                    }


                    //si se escoge escuela elimino other
                    if ( school != -1 ) $('#facebox #edu_school_other').val('');

                    $.post("/academy/savecredentials", {type: type, id: id, country: country, state: state, school: school, degree: degree, area: area, date_i: date_i, date_f: date_f, other: other, other_country: otherCountry }, function(data){
                        //cerramos capa y algo haremos con el resultado... recargamos pagina?
                        $(document).trigger('close.facebox');

                        school = ( school == -1 ) ? other : schoolName;
                        countryName = ( country == -1 ) ? otherCountry : countryName;

                        //añadimos/editamos contenido dinámicamente
                        if ( $('#facebox li.del').is(':visible') ) { //estamos editado
                            $('table[rel='+type+'] tbody tr[rel='+id+']')
                                .find('>td:nth-child(1)').html('<strong>'+degree+'</strong>').end()
                                .find('>td:nth-child(2)').html(area).end()
                                .find('>td:nth-child(3)').html(school).end()
                                .find('>td:nth-child(4)').html(countryName).end()
                                .find('>td:nth-child(5)').html(date_i + ' - ' + date_f).end()
                                .effect('highlight',{},1000);

                        }
                        else { //estamos añadiendo
                            //el id del tr nos lo tiene que devolver la llamada ajax
                            $('table[rel='+type+'] tbody')
                                .append('<tr rel='+data+'>\
                                            <td><strong>'+degree+'</strong></td>\
                                            <td>'+area+'</td>\
                                            <td>'+school+'</td>\
                                            <td>'+countryName+'</td>\
                                            <td>'+date_i+' - '+date_f+'</td>\
                                            <td><a class="edit-credential" href="#">'+lang[langActive][5]+'</a></td>\
                                        </tr>');

                            $('table[rel='+type+'] tbody tr:last-child').effect('highlight',{},1000);
                        }
                       });
                    break;

                case 'certificate':
                    var id = $('#facebox #cer_id').val(),
                        country = $('#facebox #cer_country').val(),
                        countryName = $('#facebox #cer_country option:selected').text(),
                        otherCountry = $('#facebox #cer_other_country').val(),
                        state = $('#facebox #cer_state').val(),
                        accreditation = $('#facebox #cer_title').val(),
                        awarded = $('#facebox #cer_awarded').val(),
                        year = $('#facebox #cer_year').val();

                    // Tratar errores
                    // Falta country
                    if ( country == 0){
                        $('#facebox #cer_missing_country').fadeIn('slow');
                        setTimeout(function() { $('#facebox #cer_missing_country').fadeOut('slow') }, 4000);
                        return false;
                    }
                    if ( country == -1 && otherCountry == ''){
                        $('#facebox #cer_missing_other_country').fadeIn('slow');
                        setTimeout(function() { $('#facebox #cer_other_missing_country').fadeOut('slow') }, 4000);
                        return false;
                    }

                    // Falta accreditation
                    if ( accreditation == '' ) {
                        $('#facebox #cer_missing_title').fadeIn('slow');
                        setTimeout(function() { $('#facebox #cer_missing_title').fadeOut('slow') }, 4000);
                        return false;
                    }

                    // Falta awarded
                    if ( awarded == '' ) {
                        $('#facebox #cer_missing_awarded').fadeIn('slow');
                        setTimeout(function() { $('#facebox #cer_missing_awarded').fadeOut('slow') }, 4000);
                        return false;
                    }


                    $.post("/academy/savecredentials", {type: type, id: id, country: country, state: state, accreditation: accreditation, awarded: awarded, year: year, other_country: otherCountry }, function(data){
                        countryName = ( country == -1 ) ? otherCountry : countryName;
                        $(document).trigger('close.facebox');

                        //añadimos/editamos contenido dinámicamente
                        if ( $('#facebox li.del').is(':visible') ) { //estamos editado
                            $('table[rel='+type+'] tbody tr[rel='+id+']')
                                .find('>td:nth-child(1)').html('<strong>'+accreditation+'</strong>').end()
                                .find('>td:nth-child(2)').html(awarded).end()
                                .find('>td:nth-child(3)').html(countryName).end()
                                .find('>td:nth-child(4)').html(year).end()
                                .effect('highlight',{},1000);

                        }
                        else { //estamos añadiendo
                            //el id del tr nos lo tiene que devolver la llamada ajax
                            $('table[rel='+type+'] tbody')
                                .append('<tr rel='+data+'>\
                                            <td><strong>'+accreditation+'</strong></td>\
                                            <td>'+awarded+'</td>\
                                            <td>'+countryName+'</td>\
                                            <td>'+year+'</td>\
                                            <td><a class="edit-credential" href="#">'+lang[langActive][5]+'</a></td>\
                                        </tr>');

                            $('table[rel='+type+'] tbody tr:last-child').effect('highlight',{},1000);
                        }
                    });
                    break;

                case 'experience':
                    var id = $('#facebox #exp_id').val(),
                        country = $('#facebox #exp_country').val(),
                        otherCountry = $('#facebox #exp_other_country').val(),
                        countryName = $('#facebox #exp_country option:selected').text(),
                        state = $('#facebox #exp_state').val(),
                        school = $('#facebox #exp_school').val(),
                        schoolName = $('#facebox #exp_school option:selected').text(),
                        //degree = $('#facebox #exp_degree').val(),
                        area = $('#facebox #exp_area').val(),
                        date_i = $('#facebox #exp_dates-i').val(),
                        date_f = $('#facebox #exp_dates-f').val(),
                        other = $('#facebox #exp_school_other').val();

                    // Tratar errores
                    // Falta country
                    if ( country == 0){
                        $('#facebox #exp_missing_country').fadeIn('slow');
                        setTimeout(function() { $('#facebox #exp_missing_country').fadeOut('slow') }, 4000);
                        return false;
                    }
                    if ( country == -1 && otherCountry == ''){
                        $('#facebox #exp_missing_other_country').fadeIn('slow');
                        setTimeout(function() { $('#facebox #exp_other_missing_country').fadeOut('slow') }, 4000);
                        return false;
                    }

                    // Falta State
                    if ( (country == 'us' || country == 'ca') && state == 0) {
                        $('#facebox #exp_missing_state').fadeIn('slow');
                        setTimeout(function() { $('#facebox #exp_missing_state').fadeOut('slow') }, 4000);
                        return false;
                    }
                    // Falta school
                    if ( school == 0) {
                        $('#facebox #exp_missing_school').fadeIn('slow');
                        setTimeout(function() { $('#facebox #exp_missing_school').fadeOut('slow') }, 4000);
                        return false;
                    }

                    if ( school == -1 && other == '') {
                        $('#facebox #exp_missing_other_school').fadeIn('slow');
                        setTimeout(function() { $('#facebox #exp_missing_other_school').fadeOut('slow') }, 4000);
                        return false;
                    }

                    if ( area == '') {
                        $('#facebox #exp_missing_area').fadeIn('slow');
                        setTimeout(function() { $('#facebox #exp_missing_area').fadeOut('slow') }, 4000);
                        return false;
                    }
                    if ( date_i > date_f) {
                        $('#facebox #exp_missing_dates').fadeIn('slow');
                        setTimeout(function() { $('#facebox #exp_missing_dates').fadeOut('slow') }, 4000);
                        return false;
                    }


                    //si se escoge escuela elimino other
                    if ( school != -1 ) $('#facebox #exp_school_other').val('');
                    if ( country != -1 ) $('#facebox #exp_other_country').val('');


                    $.post("/academy/savecredentials", {type: type, id: id, country: country, state: state, school: school, area: area, date_i: date_i, date_f: date_f, other: other, other_country: otherCountry }, function(data){
                        $(document).trigger('close.facebox');

                        school = ( school == -1 ) ? other : schoolName;
                        countryName = ( country == -1 ) ? otherCountry : countryName;


                        //añadimos/editamos contenido dinámicamente
                        if ( $('#facebox li.del').is(':visible') ) { //estamos editado
                            $('table[rel='+type+'] tbody tr[rel='+id+']')
                                .find('>td:nth-child(1)').html('<strong>'+area+'</strong>').end()
                                .find('>td:nth-child(2)').html(school).end()
                                .find('>td:nth-child(3)').html(countryName).end()
                                .find('>td:nth-child(4)').html(date_i + ' - ' + date_f).end()
                                .effect('highlight',{},1000);

                        }
                        else { //estamos añadiendo
                            //el id del tr nos lo tiene que devolver la llamada ajax
                            $('table[rel='+type+'] tbody')
                                .append('<tr rel='+data+'>\
                                            <td><strong>'+area+'</strong></td>\
                                            <td>'+school+'</td>\
                                            <td>'+countryName+'</td>\
                                            <td>'+date_i+' - '+date_f+'</td>\
                                            <td><a class="edit-credential" href="#">'+lang[langActive][5]+'</a></td>\
                                        </tr>');

                                $('table[rel='+type+'] tbody tr:last-child').effect('highlight',{},1000);
                        }
                    });
                break;
            }

            return false;
        });
    },

    viewCertificate: function(){
        $('a[rel=certificate]').next().find('td:first a').click(function(){
            $('#view-certificate img').attr('src', $(this).attr('href'));
            $.facebox( { div: '#view-certificate' } );
            return false;
        })
    },

    location: function(){
        // hay que saber de que combo me cambian el pais, si es usa o canada mostrar combo de estados
        // en caso contrario cargar schools via ajax
        // cuando hayan seleccionado estado mostrar schools via ajax

        $('#facebox #cer_country').change(function(){
            if ( $(this).val() == -1 ) {
                $(this).parent().next().slideDown(); // Mostrar edit other country
            }
            else {
                if ($(this).parent().next().is(':visible')) $(this).parent().next().slideUp();
            }
        });


        //esto no lo hago para añadir certificado
        if ( !$('#facebox #add-certificate')[0] ) {

            var context = $('#facebox'),
                selectCountry = $( $('#edu_country', context)[0] || $('#exp_country', context)[0] ),
                selectState = $( $('#edu_state', context)[0] || $('#exp_state', context)[0] );

            selectCountry.change(function(){
                var options = '', $$ = $(this);

                //si es US o CA aparece select para seleccionar estado
                if ( $$.val() == 'us' ||  $$.val() == 'ca' ) {
                    $.postJSON('/academy/get_states', {country: $$.val()}, function(data){
                        //muestro el select de estados
                        selectState.parent().slideDown();

                        $.each( data, function(i, item){
                            options += "<option value='"+ item.state +"'>"+ item.name +"</option>";
                         });

                        //rellenamos select de states
                        selectState
                            .find('option:not([value=-1]):not([value=0])')
                                .remove()
                                .end()
                            .find('option:first')
                            .after(options);
                    });
                }
                else { //cargo escuelas si se ha escogido un pais diferente a usa o ca o si se ha escogido un estado (tambien escondo estados ya que puede ser una edición)
                    credentials.loadSchools( selectCountry.val(), '', '0' );
                    selectState.parent().slideUp();
                }
            });

            selectState.change(function(){
                credentials.loadSchools( selectCountry.val(), selectState.val(), '0' )
            });

            //si selecciona "otra escuela" mostramos input de texto
            $('#edu_school, #exp_school', context).change(function(){
                if ( $(this).val() == -1 ) $(this).parent().next().slideDown();
                else if ($(this).parent().next().is(':visible')) $(this).parent().next().slideUp()
            });

            //si selecciona "otro country" mostramos input de texto
            $('#edu_country, #exp_country', context).change(function(){
                if ( $(this).val() == -1 ) {
                    $(this).parent().next().slideDown(); // Mostrar edit other country
                    var context = $('#facebox');

                    $('#edu_school_other', context).parent().slideDown();
                    $('#exp_school_other', context).parent().slideDown();

                    $('#edu_school', context).find('option[value="-1"]').attr('selected', 'selected');
                    $('#exp_school', context).find('option[value="-1"]').attr('selected', 'selected');
                    // Ocultamos combos de universidades
                    $('#edu_school', context).parent().slideUp();
                    $('#exp_school', context).parent().slideUp();
                }
                else {
                    if ($(this).parent().next().is(':visible')) $(this).parent().next().slideUp();
                    var context = $('#facebox');
//                    $(this).parent().next().next().next().slideDown();

                    $('#edu_school', context).parent().slideDown();
                    $('#exp_school', context).parent().slideDown();
                }
             });

        }

    },

    loadSchools: function( country, state, selected ){
        var context = $('#facebox'),
            selectSchool = $( $('#edu_school', context)[0] || $('#exp_school', context)[0] ),
            options = '';

        //si al escoger escuela no es "otra", oculto el campo de "otro" por si lo habia desplegado antes
        selectSchool.change(function(){
            if ( $(this).val() != -1 ) {
                $('li[rel=school-other]',context).slideUp();
                $('#edu_school_other').val('');
                $('#exp_school_other').val('');
            }
        });

        //espero json así: [ { value: 112, name: school1 }, { value: 334, name: school2 }, { value: 555, name: school3 } ]
        $.postJSON('/academy/get_schools', {country: country, state: state}, function(data){
            //muestro select de escuelas

            //selectSchool.parent().slideDown(); no las mostramos aqui de momento.....
            $.each( data, function(i, item){
                options += "<option value='"+ item.code +"' ";
                if (item.code == selected) options += "SELECTED='SELECTED' ";
                options += ">"+ item.name +"</option>";
             });

            //rellenamos select de escuelas
            selectSchool
                .find('option:not([value=-1]):not([value=0])')
                    .remove()
                    .end()
                .find('option:first')
                .after(options);
        });
    },

    loadStates: function( country, selected ){
        var context = $('#facebox'),
            selectState = $( $('#edu_state', context)[0] || $('#exp_state', context)[0] ),
            selectCountry = $( $('#edu_country', context)[0] || $('#exp_country', context)[0] ),
            options = '';

        $.postJSON('/academy/get_states', {country: country}, function(data){
            //muestro select de escuelas
            selectSchool.parent().slideDown();
            $.each( data, function(i, item){
                options += "<option value='"+ item.state +"' ";
                if (item.state == selected) options += "SELECTED='SELECTED' ";
                options += ">"+ item.name +"</option>";
             });

             //rellenamos select de estados (solo si no esta lleno ya)
             if ( selectState.find('option').length == 1 ) { //solo existe el option de select state
                  selectState.find('option:first').after(options);
             }

        });

        selectState.change(function(){
            credentials.loadSchools( selectCountry.val(), selectState.val(), '0' )
        });

    },

    init: function(){
        if ( !$('body#academy')[0] &&  !$('table.credentials')[0]) return;

        //$.getScript('/js/jquery.tablesorter.js',function(){
            //ordenación de columnas
            $('table[rel=education]').tablesorter( {headers: { 5:{sorter: false}}} );
            $('table[rel=experience]').tablesorter( {headers: { 4:{sorter: false}}} );
            $('table[rel=certificate]').tablesorter( {headers: { 4:{sorter: false}}} );
        //});


        //ver certificados
        this.viewCertificate();

        //vista profesor
        if ( $('.add-credential')[0] ) this.add();

        //edicion
        if ( $('.edit-credential')[0] ) this.edit();
    }
};

//bubbles en viewMedia
var ViewMediaBubbles = {
    bubble: function() {
        var $$ = $(this);
        var layout = '<div class="bubble">' + $(this).attr('alt') + '</div>';
        $$.parent().append(layout);
    },
    init: function(){
        if ( !document.getElementById('viewMedia') ) return;

        $('#videoInfo li big img').each(this.bubble);

        //mostrar/ocultar bubbles
        $('#videoInfo li big img').live('mouseover',function(){
            $('.bubble',$(this).parent()).show();
        })
        .live('mouseout',function(){
            $('.bubble',$(this).parent()).hide();
        });
    }
};

// Change language links at footer
function languages(){
    $('.select-language').click(function(){
        $.get('/frontpage/language/'+$(this).attr('rel'), function(){
            window.location.reload(true);
        });
        return false;
    });
}

// New notification system
function notificationSystem(){
    var capa = $('#notificationlayer');
    capa.animate({
        marginTop: (78)
    },{
        duration: 350
    });
    setTimeout( function(){
        capa.animate({
            marginTop: (-78)
        },{
            duration: 350
        });
    }, 3500);
}

function timeZone(){
    $('#profile-confirm-tz').click(function(){
        $.post('/profile/confirm_tz', function(){
            $.post('/profile/update_tz', {tz: $('#timezones').val()}, function(data){
                $('#span-confirm-tz').fadeOut('slow', function(){ $('#current_datetime').html(data) });
                $('#confirm_your_tz').val("1");
                $('#infoTZ').html('');
            });
        });
        return false;
    });

    $('#confirmmy-tz').click(function(){
        $.post('/profile/confirm_tz', function(){
            $.facebox( { div: '#change_my_time_zone' } );

    //        var context = $('#facebox');
    //        $('#span-confirm-tz').fadeOut('slow',function(){ $('#span-update-tz').fadeIn('slow'); });
        });
        return false;
    });

    $('#updatemy-tz').click(function(){
        $.post('/profile/confirm_tz', function(){
            $.facebox( { div: '#change_my_time_zone' } );
            var context = $('#facebox');
            $('#tzones', context).removeAttr('disabled');
        });
        return false;
    });

    $('#facebox #updateyour_tz').live('click',function(){
        var context = $('#facebox');
        $('#confirm_your_tz').val("1");

        $.post('/profile/update_tz', {tz: $('#tzones', context).val()}, function(data){
            $('#current_datetime').html(data);
            $('#select_tz', context).hide();
            $('#saved_ok', context).show();
            $('#span-confirm-tz').fadeOut('slow',function(){ $('#span-update-tz').fadeIn('slow'); });
            $('#facebox #change_my_time_zone #tzones option:selected, #change_my_time_zone #tzones option:selected').removeAttr('selected');
            $('#facebox #tzones option[value='+ $('#tzones',context).val() +'], #tzones option[value='+ $('#tzones',context).val() +']').attr('selected', 'selected');
            //$('#change_my_time_zone #tzones option:selected').removeAttr('selected');
            //$('#facebox #tzones option[value='+ $('#tzones',context).val() +']').attr('selected', 'selected');
            //$('#tzones').find('option[value="'+selected+'"]').attr('selected', 'selected');
            setTimeout(function() { $(document).trigger('close.facebox'); }, 2000);
        });
        return false;
    });
}


function contentFolders(){
    $('.fb_createfolder').live('click',function(){
        $.facebox( { ajax: '/folder/create' } );
        return false;
    });

    $('#fb_editfolder').live('click',function(){
        $.facebox( { ajax: '/folder/edit/' + $(this).attr('rel') } );
        return false;
    });

    $('.fb_assignfolder').live('click',function(){
        $.facebox( { ajax: '/folder/assign/' + $(this).attr('rel') } );
        return false;
    });

    $('#fb_deletefolder').live('click',function(){
        $(this).attr('disabled', 'disabled');
        var folder = $('#idfolder').val();
        $.post('/folder/delete', {folder: folder }, function(){
            $('ul li[id=folder'+folder+']', 'body#academy').effect('highlight',{},500).fadeOut('normal');
            changeFolder('all');
            $(document).trigger('close.facebox');
        });
        return false;
    });

    $('#fb_removefolder').live('click',function(){
        $('#folders').slideUp( function(){
            $('#confirmfolderdelete').slideDown();
        });
        return false;
    });

    $('#fb_checkallfolder').live('click',function(){
        $('ul.form :checkbox').each(function(i){
            $(this).attr('checked','checked');
        });
        // $('.fb_checkthisfolder').html($('#fb_folderremove').val());
        return false;
    });

    $('#fb_checknonefolder').live('click',function(){
        $('ul.form :checkbox').each(function(i){
            $(this).removeAttr('checked');
        });
        // $('.fb_checkthisfolder').html($('#fb_folderadd').val());
        return false;
    });
/*
    $('.fb_checkthisfolder').live('click',function(){
        if ($(this).prev().attr('checked')) {
            $(this).html($('#fb_folderadd').val()).prev().removeAttr('checked');
        } else {
            $(this).html($('#fb_folderremove').val()).prev().attr('checked','checked');
        }
        return false;
    });
*/
    $('ul.form :checkbox').live('change', function(){
        if ($(this).attr('checked')) {
            $(this).next().html($('#fb_folderremove').val());
        } else {
            $(this).next().html($('#fb_folderadd').val());
        }
        return false;
    });


    $('#foldersassign').live('submit',function(event){
        event.preventDefault();
        var form_obj = $(this);

        $("#" + form_obj.attr('id') + " input[type='submit']").attr('disabled', 'disabled');
        $.ajax({
            type: "POST",
            url: form_obj.attr('action'),
            data: form_obj.serialize(),
            cache: false,
            dataType: 'json',
            success: function(data){
                if (data == 'ko') {
                    $('#messages #ko').fadeIn();
                    setTimeout(function() { $('#messages #ko').fadeOut(); }, 3000);
                }
                else
                {
                    var ul_li = $('ul.criteriaList li.selected');
                    var ul_li_id = ul_li.attr('id').slice(6);

                    $('ul.criteriaList').find('>li:gt(0)').remove();
                    for (var i in data){
                        var f_name = data[i].folder;
                        if (f_name.length > 22) f_name = f_name.substr(0,22)+'...';

                        jQuery('<li id="folder'+data[i].id+'" rel="'+data[i].folder+'"><a class="ignore" href="#" onclick="changeFolder(\''+data[i].id+'\'); return false;">'+f_name+' ('+data[i].total+')</a></li>').appendTo($('ul.criteriaList'));
                    }
                }
                setTimeout(function() { $(document).trigger('close.facebox'); changeFolder(ul_li_id);}, 1000);

            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                $('#messages #ko').fadeIn();
                setTimeout(function() { $('#messages #ko').fadeOut(); }, 3000);
            }
        });

    });

    $('#folders').live('submit',function(event){
        event.preventDefault();
        var form_obj = $(this);
        var first = null;
        var digit = /(^-*\d+$)|(^-*\d+\.\d+$)/;
        var letters = /[A-Za-z]/;
        var alpha = /^[ a-zA-Z0-9_-]{1,50}$/;

        $("#" + form_obj.attr('id') + " input[type='submit']").attr('disabled', 'disabled');

        $('.reqfield').hide().prev().css('border','');
        $('#' + form_obj.attr('id') + ' :input').each(function(i){
            if ($(this).attr('class').indexOf('req') > -1 ) {
                if ($(this).val().length == 0) {
                    if (first == null) first = $(this);
                    $(this).css('border','solid 2px #f00').next().slideDown();
                } else {
                    if ($(this).attr('class').indexOf('digit') > -1 && $(this).val().search(digit) == -1) {
                        if (first == null) first = $(this);
                        $(this).css('border','solid 2px #f00').next().slideDown();;
                    }
                    if ($(this).attr('class').indexOf('letter') > -1 && $(this).val().search(letters) == -1) {
                        if (first == null) first = $(this);
                        $(this).css('border','solid 2px #f00').next().slideDown();;
                    }
                    if ($(this).attr('class').indexOf('alpha') > -1 && $(this).val().search(alpha) == -1) {
                        if (first == null) first = $(this);
                        $(this).css('border','solid 2px #f00').next().slideDown();;
                    }
                    if ($(this).val().length > $(this).attr('maxlength')) {
                        if (first == null) first = $(this);
                        $(this).css('border','solid 2px #f00');
                    }

                }
            }
        });
        if (first != null) {
            first.focus();
            $("#" + form_obj.attr('id') + " input[type='submit']").removeAttr('disabled', 'disabled');
            return false;
        }

        $('#foldername').val($('#foldername').val().charAt(0).toUpperCase() + $('#foldername').val().slice(1));
        $.ajax({
            type: "POST",
            url: form_obj.attr('action'),
            data: form_obj.serialize(),
            cache: false,
            dataType: 'json',
            success: function(data){
                if (data.length == 0) data = 'ko';
                if (data.msg == 'ko') {
                    $('#messages #ko').slideDown();
                    setTimeout(function() { $('#messages #' + data).fadeOut(); }, 3000);
                    $("#" + form_obj.attr('id') + " input[type='submit']").removeAttr('disabled', 'disabled');
                    return false;
                }
                else {
                    form_obj.slideUp( function(){
                        $('#messages #ok').slideDown();
                    });
                    setTimeout(function() { $(document).trigger('close.facebox'); }, 2000);
                    if (form_obj.attr('action').indexOf('create') > -1)
                    {
                        $('ul.criteriaList').find('>li:gt(0)').remove();
                        for (var i in data){
                            var f_name = data[i].folder;
                            if (f_name.length > 22) f_name = f_name.substr(0,22)+'...';

                            jQuery('<li id="folder'+data[i].id+'" rel="'+data[i].folder+'"><a class="ignore" href="#" onclick="changeFolder(\''+data[i].id+'\'); return false;">'+f_name+' ('+data[i].total+')</a></li>').appendTo($('ul.criteriaList'));
                        }

                        $('.fb_assignfolder').show();

                    }
                    if (form_obj.attr('action').indexOf('edit') > -1)
                    {
                        var ul_li = $('ul.criteriaList li.selected');
                        var ul_li_id = ul_li.attr('id').slice(6);
                        var items = ul_li.text();
                        var items = items.slice(items.indexOf(' ('));
                        var f_name = $('#foldername').val();
                        $('#work_area h3 strong').html(f_name);
                        if (f_name.length > 22) f_name = f_name.substr(0,22)+'...';
                        ul_li.attr('rel', $('#foldername').val()).html('<a class="ignore" href="#" onclick="changeFolder(\''+ul_li_id+'\'); return false;">'+f_name+items+'</a>');
                    }
                    setTimeout(function() { $(document).trigger('close.facebox'); }, 2000);
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                $('#messages #ko').fadeIn();
                setTimeout(function() { $('#messages #ko').fadeOut(); }, 3000);
            }
        });
        return false;
    });

}

function alertSystem() {
    var capa = $('#alertSystem');
	if (capa.text() == "") return;
    if ($('#capa').length == 0) {
        capa.animate({
            marginTop: (68)
        },{
            duration: 350
        });
        setTimeout( function(){
            capa.animate({
                marginTop: (-68)
            }, 1000, function() { capa.remove() });
        }, 6500);
    }
}

function wall() {
//$('#wall').livequery(function(){
//    if ( !$('#wall').length) return; //Limito alcance del script

    $('.autoclean').autoClean();
    $('.growfield').elastic();

    $('.remove-topic').live('click',function(){
        var id = $(this).attr('rel');
        var topic = $('#topic_'+id).parent();
        topic.effect('highlight',{}).fadeOut('normal',function(){
            topic.remove();
            $('.user-topic-response[rel='+id+']').fadeOut('fast').remove();
            $('#new-comment-'+id).remove();
            $.post('/wall/delete', { reference: $('#reference').val(), application: $('#application').val(), topic: id });
        });
        return false;
    });

    $('.remove-comment').live('click',function(){
        var id = $(this).attr('rel');
        var comment = $('#comment_'+id);
        comment.effect('highlight',{}).fadeOut('normal',function(){
            $.post('/wall/delete', { reference: $('#reference').val(), application: $('#application').val(), comment: id }, function(data){
                comment.remove();
            });
        });
        return false;
    });

    $('#post-new-topic').live('click',function(){
        if (($('#new-topic').val() == $('#new-topic').attr('default')) || $.trim($('#new-topic').val() == '')) return false;
        if ($('#wall_student').length) {
            var type = $('#wall_student').val();
        } else {
            var type = 'T';
        }
        $.post('/wall/create_comment', { type: type, reference: $('#reference').val(), application: $('#application').val(), text: $('#new-topic').val() }, function(data){
            if (data.length != 0) {
                $('#first-item').parent().after("<li>"+data+"</li>").fadeIn('fast');
                $('#new-topic').val($('#new-topic').attr('default'));
                // $('.growfield').growfield({animate: false, max: 100, min: 18 });
                $('.growfield').elastic();
                $('.autoclean').autoClean();
            }
        });
        return false;
    });

    $('.post-new-comment').live('click',function(){
        var parent = $(this).attr('rel');
        if (($('#message-'+parent).val() == $('#message-'+parent).attr('default')) || $.trim($('#message-'+parent).val()) == '') return false;
        $.post('/wall/create_comment', { reference: $('#reference').val(), application: $('#application').val(), text: $('#message-'+parent).val(), parent: parent }, function(data){
            if (data.length != 0) {
                $('#new-comment-'+parent).parent().before(data).fadeIn('fast');
                $('#message-'+parent).val($('#message-'+parent).attr('default'));
                $('#new-comment-'+parent).fadeOut('fast');
            }
        });
        return false;
    });

    $('#wall .new-comment').live('click',function(){
        var id = $(this).attr('rel');
		$("#comment-tab-"+id).show();
		$('#new-comment-'+id).parent().show();
        $('#new-comment-'+id).fadeIn('fast');
        $('#message-'+id).focus().live('blur', function(){
            // $(this).parent().hide();
            return true;
        });
        return false;
    });

    $('.show-all-comments').live('click',function(){
        var id = $(this).attr('rel');
        $('.user-topic-response[rel='+id+']').slideDown();
        $(this).hide();
        return false;
    });

    // Used to comment on materials, courses, etc. (in events)
    $('.post-new-topic').live('click',function(){
        var value = $('#new-topic-'+$(this).attr("rel")).val();
        var def = $('#new-topic-'+$(this).attr("rel")).attr('default');
        var ref = $(this).attr("rel");
        if (value == def || $.trim(value == '')) return false;
        $.post('/wall/create_comment', { reference: $(this).attr("rel"), application: $('#application').val(), text: value, comment: 'N', topapp: $('#event').val() }, function(data){
            if (data.length != 0) {
                $('#first-item-'+ref).after(data).fadeIn('fast');
                $('#new-topic').val($('#new-topic').attr('default'));
                // $('.growfield').growfield({animate: false, max: 100, min: 36 });
                $('.growfield').elastic();
                $('.autoclean').autoClean();
            }
        });
        return false;
    });

    $('a.view-more-wall').live('click',function(){
        var page = $(this).attr('rel');
        var filter = 'all';
        $('.wall-navigation li').each(function(){
            if ($(this).hasClass('current')) filter = $(this).attr('rel');
        });
        $(this).attr('rel', parseInt(page) + 1);

        if (parseInt(page) <= parseInt($('#total_pages').val()))
        {
            $.postJSON('/wall/load_more', { reference: $('#reference').val(), application: $('#application').val(), page: page, type: filter }, function(data){
                $('#last-item').before(data.html).fadeIn('fast');
                // $('.growfield').growfield({animate: false, max: 100, min: 36 });
                $('.growfield').elastic();
                $('.autoclean').autoClean();
                if (data.showMore == 'Y')
                {
                    $('.view-more-wall a').parent().show();
                }
                else
                {
                    $('.view-more-wall a').parent().hide();
                }
            });
        }
        return false;
    });

    $('.filter-wall').live('click',function(){
        // Si han pulsado en el boton seleccionador no hacemos nada
        if ($(this).hasClass('current')) return false;
        $('.current').removeClass('current');
        $(this).addClass('current');
        var filter = $(this).attr('rel');
        var order = $('#sort').val();
        $('#bottom').css('opacity', '.2');
        $.postJSON('/wall/load_more', { application: $('#application').val(), reference: $('#reference').val(), page: 1, type: filter }, function(data){
            if (data.showMore == 'Y')
            {
                $('.view-more-wall a').parent().show();
            }
            else
            {
                $('.view-more-wall a').parent().hide();
            }
			$('#first-item').siblings().remove();
			$('#first-item').parent().css('border-bottom','none');
			
            $('#wall-work-area').html(data.html);
            $('#bottom').css('opacity', '1');
            // $('.growfield').growfield({animate: false, max: 100, min: 36 });
            $('.growfield').elastic();
            $('.autoclean').autoClean();
        });
        return false;
    });
}

function discussions() {
    var init_discussions;
    if ( !$('#discussions').length && init_discussions == 1) return; //Limito alcance del script
    init_discussions = 1;
    $('.autoclean').autoClean();

    $('.growfield').elastic();

    $('#discussions .user-title-topic a, #discussions .new-comment').live('click',function(){
        var id = $(this).attr('rel');
        if ($(this).parent().hasClass('selected')) return false;
        $.post('/discussions/topic_view', { id: id, reference: $('#reference').val(), application: $('#application').val() }, function(data){
            if (data) {
				$('#bottom').html(data);
				if ($('#discussion_message').length) $('#discussion_message').focus();
			}
        });
        return false;
    });

    $('.remove-discussion').live('click',function(){
        var id = $(this).attr('rel');
        var topic = $('#topic_'+id);
        topic.effect('highlight',{}).fadeOut('normal',function(){
            topic.remove();
            $('#new-comment-'+id).remove();
            $.post('/discussions/delete', { reference: $('#reference').val(), application: $('#application').val(), discussion: id });
        });
        return false;
    });

    $('.remove-comment').live('click',function(){
        var id = $(this).attr('rel');
        var topic = $('#topic_'+id);
        topic.effect('highlight',{}).fadeOut('normal',function(){
            topic.remove();
            $('#new-comment-'+id).remove();
            $.post('/discussions/delete_comment', { reference: $('#reference').val(), application: $('#application').val(), comment: id });
        });
        return false;
    });

    $('.new-discussion').live('click',function(){
        if (($('#discussion_message').val() == $('#discussion_message').attr('default')) || $.trim($('#discussion_message').val() == '' || $.trim($('#discussion_title').val() == ''))) return false;
        $.post('/discussions/create', { type: $('#discussion_type').val(), application: $('#application').val(), reference: $('#reference').val(), text: $('#discussion_message').val(), title: $('#discussion_title').val() }, function(data){
            $('#bottom').css('opacity', '.2');
            $.post('/courses/enter/discussions/'+$('#reference').val(), function(data){
                $('#bottom').html(data).css('opacity', '1');
            });
        });
        return false;
    });

	$('.new-discussion-start').live('click', function(){
        $.post('/courses/enter/new_discussion/'+$('#reference').val(), function(data){
            $('#bottom').html(data);
        });
        return false;
    });

    $('#discussions .new-reply').live('click',function(){
        if (($('#discussion_message').val() == $('#discussion_message').attr('default')) || $.trim($('#discussion_message').val() == '' )) return false;
        var parent = $(this).attr('rel');
        $.post('/discussions/comment', { parent: parent, application: $('#application').val(), reference: $('#reference').val(), comment: $('#discussion_message').val()}, function(data){
            if (data.length != 0) {
                $('#discussion_message').val($('#discussion_message').attr('default'));
                if ($('#no-comments').length) $('#no-comments').fadeOut('fast');
                $('#last-item').before(data).fadeIn('fast');
            }
        });
        return false;
    });

    $('.loadpage').live('click',function(){
        var new_page = $(this).attr('rel');
        var filter = 'all';
        var order = $('#sort').val();
        $('.filter').each(function(){
            if ($(this).hasClass('orange-button-selected')) filter = $(this).attr('rel');
        });
        $('#bottom').css('opacity', '.2');
        $.post('/discussions/topics', { application: $('#application').val(), reference: $('#reference').val(), page: new_page, type: filter, order: order }, function(data){
            $('#bottom').html(data).css('opacity', '1');
        });
        return false;
    });

    $('.filter').live('click',function(){
        // Si han pulsado en el boton seleccionador no hacemos nada
        if ($(this).hasClass('orange-button-selected')) return false;
        var filter = $(this).attr('rel');
        var order = $('#sort').val();
        $('#bottom').css('opacity', '.2');
        $.post('/discussions/topics', { application: $('#application').val(), reference: $('#reference').val(), page: 1, type: filter, order: order }, function(data){
            $('#bottom').html(data).css('opacity', '1');
        });
        return false;
    });

    $('.loadcommentpage').live('click',function(){
        var new_page = $(this).attr('rel');
		if (new_page > 0){
	        $('#bottom').css('opacity', '.2');
	        $.post('/discussions/topic_view', { application: $('#application').val(), reference: $('#reference').val(), id: $('#discussion').val(), page: new_page }, function(data){
	            $('#bottom').html(data).css('opacity', '1');
	        });
		}
		if ($('#discussion_message').length) $('#discussion_message').focus();
        return false;
    });

    
    $('.back-discussion').live('click', function(){
        $('#bottom').css('opacity', '.2');
        $.post('/courses/enter/discussions/'+$('#reference').val(), function(data){
            $('#bottom').html(data).css('opacity', '1');
        });
        return false;
    });
}

function webclasses_list(){

    $('#webclasses-list .webclass-title a').live('click',function(){
        var id = $(this).attr('rel');
        $.post('/webclasses/ficha', { id: id, reference: $('#reference').val() }, function(data){
            if (data) $('#bottom').html(data);
        });
        return false;
    });


    $('#webclasses-list .loadpage-webclasses').live('click',function(){
        var new_page = $(this).attr('rel');
        var filter = 'all';
        var order = $('#sort').val();
        $('.filter').each(function(){
            if ($(this).hasClass('orange-button-selected')) filter = $(this).attr('rel');
        });
        $('#bottom').css('opacity', '.2');
        $.post('/webclasses/list_webclasses', { reference: $('#reference').val(), page: new_page, type: filter, order: order }, function(data){
            $('#bottom').html(data).css('opacity', '1');
        });
        return false;
    });

    $('#webclasses-list .filter-webclasses').live('click',function(){
        // Si han pulsado en el boton seleccionador no hacemos nada
        if ($(this).hasClass('orange-button-selected')) return false;
        var filter = $(this).attr('rel');
        var order = $('#sort').val();
        $('#bottom').css('opacity', '.2');
        $.post('/webclasses/list_webclasses', { reference: $('#reference').val(), page: 1, type: filter, order: order }, function(data){
            $('#bottom').html(data).css('opacity', '1');
        });
        return false;
    });

    $('#webclasses-list .new-webclass').live('click', function(){
        $.post('/courses/enter/new_discussion/'+$('#reference').val(), function(data){
            $('#bottom').html(data);
        });
        return false;
    });

    $('.remove-webclass').live('click',function(){
        var id = $(this).attr('rel');
        var webclass = $('#webclass_'+id);
        webclass.effect('highlight',{}).fadeOut('normal',function(){
            webclass.remove();
            $.post('/courses/removeWebclass', { reference: $('#reference').val(), webclass: id });
        });
        return false;
    });

}


function students_list() {
    $('#course-students .message').live('click', function(){
        $.facebox.settings.modal = false;
        var user = $(this).attr('rel');
        $.post('/mail/send', { to: user }, function(data) { if (data){ $.facebox(data); } });
        return false;
    });

    $('#course-students .filter-students').live('click',function(){
        // Si han pulsado en el boton seleccionador no hacemos nada
        if ($(this).hasClass('orange-button-selected')) return false;
        var filter = $(this).attr('rel');
        var order = $('#sort').val();
        $('#bottom').css('opacity', '.2');
        $.post('/courses/list_students', { reference: $('#reference').val(), page: 1, type: filter, order: order }, function(data){
            $('#bottom').html(data).css('opacity', '1');
        });
        return false;
    });

    $('#course-students #sort').live('change',function(){
        var order = $(this).val();
        $('.filter-students').each(function(){
            if ($(this).hasClass('orange-button-selected')) filter = $(this).attr('rel');
        });
        $('#bottom').css('opacity', '.2');
        $.post('/courses/list_students', { reference: $('#reference').val(), page: 1, type: filter, order: order }, function(data){
            $('#bottom').html(data).css('opacity', '1');
        });
        return false;
    });

    // Paginar
    $('.loadpage-students').live('click',function(){
        var new_page = $(this).attr('rel');
        var filter = 'all';
        var order = $('#sort').val();
        $('.filter-students').each(function(){
            if ($(this).hasClass('orange-button-selected')) filter = $(this).attr('rel');
        });
        $('#bottom').css('opacity', '.2');
        $.post('/courses/list_students', { reference: $('#reference').val(), page: new_page, type: filter, order: order }, function(data){
            $('#bottom').html(data).css('opacity', '1');
        });
        return false;
    });

}

//New material button
var assignMaterials = function(){
    $('.remove-material').live('click',function(){
        var id = $(this).attr('rel');
        var material = $('#material_'+id);
        material.effect('highlight',{}).fadeOut('normal',function(){
            $.post('/courses/deleteMaterial', { reference: $('#reference').val(), id: id }, function(data){
                material.remove();
                // Deseleccionar elemento borrado del facebox
                $('li.assign-materials-item[rel='+id+']').removeClass('selected').find('p.assign-materials-item-selected').remove();
            });
        });
        return false;
    });

    // Paginar
    $('.loadpage-materials').live('click',function(){
        var new_page = $(this).attr('rel');
        var filter = 'all';
        var order = $('#sort').val();
        $('.filter-materials').each(function(){
            if ($(this).hasClass('orange-button-selected')) filter = $(this).attr('rel');
        });
        $('#bottom').css('opacity', '.2');
        $.post('/courses/list_materials', { reference: $('#reference').val(), page: new_page, type: filter, order: order }, function(data){
            $('#bottom').html(data).css('opacity', '1');
        });
        return false;
    });

    // Filtros
    $('#materials-list .filter-materials').live('click',function(){
        // Si han pulsado en el boton seleccionador no hacemos nada
        if ($(this).hasClass('orange-button-selected')) return false;
        var filter = $(this).attr('rel');
        var order = $('#sort').val();
        $('#bottom').css('opacity', '.2');
        $.post('/courses/list_materials', { reference: $('#reference').val(), page: 1, type: filter, order: order }, function(data){
            $('#bottom').html(data).css('opacity', '1');
        });
        return false;
    });

    // Ordenar
    $('#materials-list #sort').live('change',function(){
        var order = $(this).val();
        $('.filter-materials').each(function(){
            if ($(this).hasClass('orange-button-selected')) filter = $(this).attr('rel');
        });
        $('#bottom').css('opacity', '.2');
        $.post('/courses/list_materials', { reference: $('#reference').val(), page: 1, type: filter, order: order }, function(data){
            $('#bottom').html(data).css('opacity', '1');
        });
        return false;
    });

    //abrir capa
    $('span.new-material-button, .assign-new-material, .addMaterialQuick').live('click', assignMaterialsFacebox);
}();


function requestinfoUtils(){
    $('#app_request_info').live('click',function(){
        $.facebox.settings.opacity = 0;
        $.facebox.settings.modal = true;
        $.post("/admission/requestinfo", { application: $('#application').val(), reference: $('#reference').val() }, function(data){
            $.facebox( data );
        });
        return false;
    });
    $('#app_send_info').live('click',function(){
        var $$ = $(this);
        $$.attr('disabled','disabled');
        $.post("/admission/sendrequestinfo", { comments: $('#comments').val(), application: $('#application').val(), reference: $('#reference').val() }, function(data){
            if (data == 'ok') {
                $('#request_info').hide();
                $('#messages #ko').hide();
                $('#messages #send').slideDown('fast');
                setTimeout(function() { $(document).trigger('close.facebox'); }, 4000);
            } else {
                $('#messages #ko').slideDown('fast');
                $$.removeAttr('disabled', 'disabled');
            }
        });
        return false;
    });
}

function webclassesUtils(){
    // if ( !$('body#academy.events').length ) return; //Limito alcance del script
    $('.publish_webclass').live('click',function(){
        $.facebox.settings.opacity = 0;
        $.facebox.settings.modal = true;
        $.post('/webclasses/publishshow', { reference: $(this).attr('rel') }, function(data) { if (data){ $.facebox(data); } });
        return false;
    });
	
	$('#createwebclass-1').live('click', function(e){
		    var isOk = true;
			$('.wait_overlay').css('display','block');
			$('html, body').animate({scrollTop:0}, 'slow');
			$(".container-error").hide();
			$(".container-error li").hide();
			if ($("#title").val() == "") {
				$("#errtitle").show();
				isOk = false;
			}
			if ($("#description").val() == "") {
				$("#errdescription").show();
				isOk = false;
			}
			if ($("#tags").val() == "") {
				$("#errtags").show();
				isOk = false;
			}
			if ($('#category').attr('selectedIndex') == 0) {
				$("#erreduarea").show();
				isOk = false;
			}

			if ($('#category_other').is(':visible') && $('#category_other').val() == '')
			{
				$("#erreduarea").show();
				isOk = false;
			}

			if ($("#start_date").val() == "" || $('#start_time').val() == '') {
				$("#errwrongdate").show();
				isOk = false;
			}

			if ($("#duration").val() == "" || $("#duration").val() == "0") {
				$("#errduration").show();
				isOk = false;
			}

			if (!isNumeric($("#duration").val()) || $("#duration").val() > 180) {
				$("#errmaxduration").show();
				isOk = false;
			}

			if ($("#confirm_your_tz").val() != "1") {
				$("#errtimezone").show();
				isOk = false;
			}

			if ($("input[name='admission']:checked").val() == 'D') {
				if ($('#admission_date').val() == '' || $('#admission_time').val() == '') {
					$("#erradmission").show();
					isOk = false;
				}
			}

			if ($("input[name='admission']:checked").val() == 'D') {
				var start = new Date ($("#start_date").val()+" "+$("#start_time").val());
				var max_date = new Date ($("#admission_date").val()+" "+$("#admission_time").val());
				if (start < max_date) {
					$("#errdeadline").show();
					isOk = false;
				}
			}

			if (!isOk) {
				$('.wait_overlay').css('display','none');
				$(".container-error").show();
				$('html, body').animate({scrollTop:0}, 'slow');
			}

		    if (!isOk){
		        $(".container-error").show();
				return false;
			}else{
				$('#create-webclass').submit();
			}
		});
}

function courseUtils(){
    if ( !$('body#academy.courses').length && !$('body#academy.events').length ) return; //Limito alcance del script
    $('.publish_course').live('click',function(){
        $.facebox.settings.opacity = 0;
        $.facebox.settings.modal = true;
        $.post('/courses/publishshow', { reference: $(this).attr('rel') }, function(data) { if (data){ $.facebox(data); } });
        return false;
    });
/*
    $('#course-info a').live('click',function(){
        $.facebox.settings.opacity = 0;
        $.facebox.settings.modal = true;
        $.facebox( { ajax: '/admisssion/requestinfo/' + $('#reference').val() } );
        return false;
    });


    $('#request_course_info').live('click',function(){
        var $$ = $(this);
        $$.attr('disabled','disabled');
        $.post("/admission/sendrequestinfo", { message: $('#comments').val(), course: $('#course_reference').val() }, function(data){
            if (data == 'ok') {
                $('#request_info').hide();
                $('#messages #ko').hide();
                $('#messages #send').slideDown('fast');
                setTimeout(function() { $(document).trigger('close.facebox'); }, 4000);
            } else {
                $('#messages #ko').slideDown('fast');
                $$.removeAttr('disabled', 'disabled');
            }
        });

        return false;
    });

*/
    $('#tab-new-course-material').live('click', function(){
        var tab = $(this).attr('rel');

        if ($('#course-preview .courses-main-menu[rel='+tab+']').hasClass('selected')) {
            $('.new-material-button').click();
            return false;
        }
        $('#course-preview .courses-main-menu').removeClass('selected');
        $('#course-preview .courses-main-menu[rel='+tab+']').addClass('selected');
        $('#course-preview .courses-main-menu[rel='+tab+']').addClass('loading');
        $('#bottom').css('opacity', '.2');

        $.post('/courses/enter/'+tab+'/'+$('#reference').val(), function(data){
            $('#bottom').html(data).css('opacity', '1');
            $('#course-preview .courses-main-menu[rel='+tab+']').removeClass('loading');
            assignMaterialsFacebox();
        });
        return false;
    });

/*
    $('#assignevent').live('click',function(){
    });
*/
    $('#facebox #save_assignevents').live('click',function(){
        var num = 0;
        $("#facebox .assignevent input[type='checkbox']").each(function() {
            if (!$(this).attr("disabled")) {
                var ref = $(this).attr("rel");
                if ($(this).attr("checked")) {
                    $.post("/events/assign_course", {reference: ref, course: $('#course_reference').val() });
                    num++;
                } else {
                    $.post("/events/remove_course", {reference: ref, course: $('#course_reference').val() });
                }
                $(".assignevent input[type='checkbox'][rel='"+ref+"']").attr("checked", $(this).attr("checked"));
            }
        });
        if (num == 0) num = "0";
        $("#facebox .assignevent div").hide();
        $("#facebox .assignevent .success span").html(num);
        $("#facebox .assignevent .success").show();
        setTimeout(function(){ $(document).trigger('close.facebox'); }, 3000);
        return false;
    });

    $('#facebox #save_assigngroups').live('click',function(){
        var num = 0;
        $("#facebox .assigngroup input[type='checkbox']").each(function() {
            if (!$(this).attr("disabled")) {
                var ref = $(this).attr("rel");
                if ($(this).attr("checked")) {
                    $.post("/groups/assign_course", {reference: ref, course: $('#course_reference').val() });
                    num++;
                } else {
                    $.post("/groups/remove_course", {reference: ref, course: $('#course_reference').val() });
                }
                $(".assigngroup input[type='checkbox'][rel='"+ref+"']").attr("checked", $(this).attr("checked"));
            }
        });
        if (num == 0) num = "0";
        $("#facebox .assigngroup div").hide();
        $("#facebox .assigngroup .success span").html(num);
        $("#facebox .assigngroup .success").show();
        setTimeout(function(){ $(document).trigger('close.facebox'); }, 3000);
        return false;
    });


    $('.courses-main-menu a').live('click', function(){
        if ($(this).parent().hasClass('selected')) return false;
        var tab = $(this).parent().attr('rel');
        $('#course-preview .courses-main-menu').removeClass('selected');
        $('#course-preview .courses-main-menu[rel='+tab+']').addClass('selected');
        $('#course-preview .courses-main-menu[rel='+tab+']').addClass('loading');
        $('#bottom').css('opacity', '.2');
        $.post('/courses/enter/'+$(this).parent().attr('rel')+'/'+$('#reference').val(), function(data){
            $('#bottom').html(data).css('opacity', '1');
            $('#course-preview .courses-main-menu[rel='+tab+']').removeClass('loading');
            if ($(this).parent().attr('rel') == 'wall') wall();
        });
        return false;
    });

    $('#tab-new-discussion').live('click', function(){
        var tab = $(this).attr('rel');
        $('#course-preview .courses-main-menu').removeClass('selected');
        $('#course-preview .courses-main-menu[rel='+tab+']').addClass('selected');
        $('#course-preview .courses-main-menu[rel='+tab+']').addClass('loading');
        $('#bottom').css('opacity', '.2');
        $.post('/courses/enter/new_discussion/'+$('#reference').val(), function(data){
            $('#bottom').html(data).css('opacity', '1');
            $('#bottom').html(data);
            $('#course-preview .courses-main-menu[rel='+tab+']').removeClass('loading');
        });
        return false;
    });


    $("#enroll_course_webclass").live('click',function(){
        var lang_wcr = {
            en: ['Application Pending','Attending', 'Enter now!'],
            es: ['Solicitud pendiente','Participando', 'Entrar!'],
            de: ['Antrag in Bearbeitung','Teilnehmer', 'Eintreten!']
        };
        var langActive = $('html').attr('lang');
        var ref = $(this).attr('rel');


        $.post("/webclasses/enrollment", { reference: ref }, function(data){
            $(document).trigger('close.facebox');

            $('#webclass .webclass-button').unbind('click').find('span').fadeOut('normal',function(){
                if (data == 'S')
                {
                    $(this).html(lang_wcr[langActive][2]).fadeIn();
                }
                else if (data == 'A')
                {
                    $(this).html(lang_wcr[langActive][1]).fadeIn();
                }
                else
                {
                    $(this).html(lang_wcr[langActive][0]).fadeIn();
                }

//                if ($('#approval').val() == 'O')
//                {
//                    if (data == 'S')

//                      $(this).html(lang_wcr[langActive][1]).fadeIn();
                    // window.location.reload(true);
//                }
//                else
//                {
//                    $(this).html(lang_wcr[langActive][0]).fadeIn();
//                }

            }).css('cursor','default');

            $('#a'+ref).fadeOut('normal',function(){
                if ($('#em'+ref).attr('rel') == 'O')
                {
                    window.location.reload(true);
                }
                else
                {
                    $('#em'+ref).html(lang_wcr[langActive][0]);
                }

            }).css('cursor','default');

            $('#right .course-button').unbind('click').find('span').fadeOut('normal',function(){
                $(this).html(lang_wcr[langActive][0]).fadeIn();
            }).css('cursor','default');

        });
    });
}

//todo lo necesario para cargar el facebox para asignar materiales, desde cualquier sitio (necesita el codigo del facebox, ahora incrustado en el codigo, en el futuro se cargara via ajax)
function assignMaterialsFacebox(){
    $.facebox( { div: '#assign-materials' } );
    $('#facebox').bgIframe(); //fucking IE

    //actualizo contador de boton de seleccionados
    $('#facebox .assign-materials-item.selected').length == 0 ? $('#facebox .assign-materials-sorts > span > span').html('') : $('#facebox .assign-materials-sorts > span > span').html( '('+$('#facebox .assign-materials-item.selected').length+')' );

    //boton seleccionados
    $('#facebox .assign-materials-sorts > span').click(function(){
        //pongo el filtro de folder en estado inicial
        $('#facebox .assign-materials-folders a[rel=all]').parent().addClass('selected').siblings().removeClass('selected');
        //pongo el filtro de tipos en estado inicial
        $('#facebox .assign-materials-filters span[rel=all]').removeClass('orange-button').addClass('orange-button-selected').siblings().removeClass('orange-button-selected').addClass('orange-button');

        //si la abro con boton modifico estado
        if ( $(this).hasClass('orange-button') ) { //estado normal
            if ( $('#facebox li.assign-materials-item.selected').length > 0 ) {
                $('#facebox li[class=assign-materials-item][class!=selected]').hide();
                $('#facebox li.assign-materials-item.selected').show();
                $(this).removeClass('orange-button').addClass('orange-button-selected');
            }
        }
        else { //estado activado (mostrando solo los elementos seleccionados)
            $('#facebox li.assign-materials-item').show();
            $(this).removeClass('orange-button-selected').addClass('orange-button');
        }

        //actualizo contador
        $('#facebox .assign-materials-right > h3 > span').html( $('#facebox li.assign-materials-item:visible').length || '0' );
    });

    //tipo de material
    $('#facebox .assign-materials-item > div').each(function(){
        $(this).append('<img class="assign-materials-item-type" src="/scimg/material-'+ $(this).attr('class') +'.png" />');
    });

    //autocomplete (genero arrays de títulos)
    var titles = [];
    $('#facebox li.assign-materials-item > h3').each(function(){
        titles.push( $(this).text() );
    });

    //autocomplete
    $("#facebox #assign-materials-search")
    .attr('default',$("#facebox #assign-materials-search").val())
    .focus(function(){
        $(this).val('')
    })
    .blur(function(){
        if ($(this).val()=='') $(this).val($(this).attr('default'));
    })
    .autocomplete(titles, {
        matchContains: true,
        minChars: 0
    })
    .result(function(event, data, formatted) {
        if (data) {
            $('#facebox .assign-materials-item > h3:contains('+data+')').parent().addClass('selected').append('<p class="assign-materials-item-selected">Seleccionado</p>');
            $(this).val('');
        }
    });


    //item seleccionado
    $('#facebox .assign-materials-item').click(function(){
        var $$ = $(this);
        if ($$.hasClass('selected')) {
            $$.removeClass('selected').find('p.assign-materials-item-selected').remove();
        }
        else $$.addClass('selected').append('<p class="assign-materials-item-selected">Seleccionado</p>');

        //actualizo contador de boton de seleccionados
        $('#facebox .assign-materials-item.selected').length == 0 ? $('#facebox .assign-materials-sorts > span > span').html('') : $('#facebox .assign-materials-sorts > span > span').html( '('+$('#facebox .assign-materials-item.selected').length+')' );
        //actualizo contador
        $('#facebox .assign-materials-right > h3 > span').html( $('#facebox li.assign-materials-item:visible').length || '0' );
        //pongo el filtro de folder en estado inicial
        //$('#facebox .assign-materials-folders a[rel=all]').parent().addClass('selected').siblings().removeClass('selected');
        //pongo el filtro de tipos en estado inicial
        //$('#facebox .assign-materials-filters span[rel=all]').removeClass('orange-button').addClass('orange-button-selected').siblings().removeClass('orange-button-selected').addClass('orange-button');

        return false;
    });

    //filtros tipo
    $('#facebox .assign-materials-filters span').click(function(){
        var $$ = $(this);
        var type = $$.attr('rel');

        //cambio estado de botones
        $$.addClass('orange-button-selected').removeClass('orange-button').siblings().removeClass('orange-button-selected').addClass('orange-button');

        //muestro/oculto items del tipo seleccionado
        if (type=='all') $('li.assign-materials-item').show();
        else {
            $('#facebox li.assign-materials-item > div.type-'+type).parent().show();
            $('#facebox li.assign-materials-item > div[class!=type-'+type+']').parent().hide();
        }

        //pongo boton selected en estado inicial
        $('#facebox .assign-materials-sorts > span').removeClass('orange-button-selected').addClass('orange-button');

        //pongo el filtro de folder en estado inicial
        $('#facebox .assign-materials-folders a[rel=all]').parent().addClass('selected').siblings().removeClass('selected');

        //actualizo contador
        $('#facebox .assign-materials-right > h3 > span').html( $('#facebox li.assign-materials-item:visible').length || '0' );

        return false;
    });

    //filtro carpetas
    $('#facebox .assign-materials-folders a').click(function(){
        var $$ = $(this);
        var folder = $$.attr('rel');
        //cambio estado
        $$.parent().addClass('selected').siblings().removeClass('selected');

        //muestro/oculto items del tipo seleccionado
        if (folder=='all') $('li.assign-materials-item').show();
        else {
            $('#facebox li.assign-materials-item').hide();
            $('#facebox li.assign-materials-item[folder*='+folder+']').show();
        }

        //pongo boton selected en estado inicial
        $('#facebox .assign-materials-sorts > span').removeClass('orange-button-selected').addClass('orange-button');

        //pongo el filtro de tipos en estado inicial
        $('#facebox .assign-materials-filters span[rel=all]').removeClass('orange-button').addClass('orange-button-selected').siblings().removeClass('orange-button-selected').addClass('orange-button');

        //actualizo contador
        $('#facebox .assign-materials-right > h3 > span').html( $('#facebox li.assign-materials-item:visible').length || '0' );

        return false;
    });

    //filtro author
    $('#facebox .assign-materials-author a').click(function(){
        var $$ = $(this);
        var author = $$.attr('rel');
        //cambio estado
        $$.parent().addClass('selected').siblings().removeClass('selected');

        //muestro/oculto items del tipo seleccionado
        if (author=='all') $('li.assign-materials-item').show();
        else {
            $('#facebox li.assign-materials-item').hide();
            $('#facebox li.assign-materials-item[mine='+author+']').show();
        }

        //pongo boton selected en estado inicial
        $('#facebox .assign-materials-sorts > span').removeClass('orange-button-selected').addClass('orange-button');

        //pongo el filtro de tipos en estado inicial
        $('#facebox .assign-materials-filters span[rel=all]').removeClass('orange-button').addClass('orange-button-selected').siblings().removeClass('orange-button-selected').addClass('orange-button');

        //actualizo contador
        $('#facebox .assign-materials-right > h3 > span').html( $('#facebox li.assign-materials-item:visible').length || '0' );

        return false;
    });

    //ordenacion por tiempo
    $('#facebox .assign-materials-date').change(function(){
        var $$ = $(this);
        var time = $$.val();
        //muestro/oculto items del tipo seleccionado
        if (time=='all') $('li.assign-materials-item').show();
        else {
            $('#facebox li.assign-materials-item').hide();
            $('#facebox li.assign-materials-item[time='+time+']').show();
        }

        //pongo el filtro de tipos en estado inicial
        $('#facebox .assign-materials-filters span[rel=all]').removeClass('orange-button').addClass('orange-button-selected').siblings().removeClass('orange-button-selected').addClass('orange-button');

        //actualizo contador
        $('#facebox .assign-materials-right > h3 > span').html( $('#facebox li.assign-materials-item:visible').length || '0' );

        return false;
    });

    //ordenacion alfabeticamente
    $('#facebox .assign-materials-sort').change(function(){
        switch ($(this).val()){
            case 'alpha':
                $("#facebox #assign-materials-list > ul > li").tsort("h3",{order:"asc"});
                break;
            case 'new':
                break;
            case 'old':
                break;
        }

        //pongo el filtro de tipos en estado inicial
        $('#facebox .assign-materials-filters span[rel=all]').removeClass('orange-button').addClass('orange-button-selected').siblings().removeClass('orange-button-selected').addClass('orange-button');

        //actualizo contador
        $('#facebox .assign-materials-right > h3 > span').html( $('#facebox li.assign-materials-item:visible').length || '0' );

        return false;
    });
/*
    $('#facebox .assign-materials-sorts select').change(function(){ //%%supongo que el usuario no te hace falta no? lo puedes coger de la sesion activa?
        $.post('/materials_order', { type: $(this).attr('rel'), criterio: $(this).val() }, function(data) {
                //%%aqui tendre que sustituir simplemente, por tanto lo mejor será que me devuelvas todo el tocho de html (todo lo que está dentro de #assign-materials-list)
                $('#assign-materials-list').html(data);
        });
        return false;
    });

*/
    $('#facebox #assign-materials-save').click(function(){
        var materials = [];
        $('#facebox li.assign-materials-item.selected').each(function(){
            materials.push( $(this).attr('rel') );
        });
        if (materials.length){
            $.post('/'+$("#application_type").val()+'/save_materials', { reference: $('#app_reference').val(), id_materials: materials.join(',') }, function(data) {
                if (data == "ok") {
                    $(document).trigger('close.facebox');
					if ($('#application_type').val() == "courses"){
	                    // Recargamos la pagina de materiales
	                    $('.filter-materials').each(function(){
	                        if ($(this).hasClass('orange-button-selected')) filter = $(this).attr('rel');
	                    });
	                    $('#bottom').css('opacity', '.2');
	                    $.post('/'+$("#application_type").val()+'/list_materials', { reference: $('#reference').val(), page: 1, type: filter, order: $('#order').val() }, function(data){
	                        $('#bottom').html(data).css('opacity', '1');
	                    });
					}
					if ($('#application_type').val() == "groups" || $('#application_type').val() == "events"){
	                    // Recargamos la pagina de materiales
 						loadResults(0);
					}
                }
            });
        }
        return false;
    });

    $('#facebox #assign-materials-cancel').click(function(){
        $(document).trigger('close.facebox');
        return false;
    });

    return false;
}



var admissionUtils = {
    init: function(){
        $("#adm_apply").live('click',function(){
            if (document.getElementById('nav_join')) return false;
            $.post('/admission/apply',{reference: $('#reference').val(), application: $('#application').val() },function(data) {
                if (data.length) $('#admission_button').html(data);
            });
            return false;
        });
        $("#adm_pay").live('click',function(){
            if (document.getElementById('nav_join')) return false;
            $.post('/admission/paynow',{reference: $('#reference').val(), application: $('#application').val(), type: type },function(data) {
                admissionUtils.getCurrentStatus();
            });
            return false;
        });
        $("#adm_showpay").live('click',function(){
            if (document.getElementById('nav_join')) return false;
            $.post('/admission/showpaynow',{reference: $('#reference').val(), application: $('#application').val() },function(data) {
                $.facebox(data);
            });
            return false;
        });
        $("#ignore_invitation").live('click',function(){
            if (document.getElementById('nav_join')) return false;
            $.post('/admission/ignore',{reference: $('#reference').val(), application: $('#application').val() },function(data) {
                if (data.length) $('#admission_button').html(data);
            });
            return false;
        });
        $("#ignore_invitation_teacher").live('click',function(){
            if (document.getElementById('nav_join')) return false;
            $.post('/admission/ignore_teacher',{reference: $('#reference').val(), application: $('#application').val() },function(data) {
                if (data.length) $('#admission_button').html(data);
            });
            return false;
        });
        $("#adm_paynow").live('click',function(){
            $$ = $(this);
            $.post('/admission/paynow', { reference: $('#reference').val(), application: $$.attr('rel') }, function(data) {
                if (data){ $.facebox(data); }
            });
        });
        $('#adm-gopay').live('click',function(){
            $$ = $(this);
            if (!$('#facebox input:radio:checked').length)
            {
                $('#facebox #messages').show();
                $('#facebox ul.errors #error_payment').slideDown('slow', function(){
                    setTimeout(function() { $('#facebox #messages').slideUp('slow'); }, 4000);
                });
            }
            else
            {
                var payment = $('#facebox input:radio:checked').val();

                if (payment == 'P') {
                    $(document).trigger('close.facebox');
                    $.post('/admission/paynow',{reference: $('#reference').val(), application: $$.attr('rel'), type: payment },function(data) {
                        admissionUtils.getCurrentStatus();
                    });

                    if ($$.attr('rel') == 'courses') $.get('/paypal/pay/COURSE/'+$('#reference').val(), function(fb) { $.facebox(fb); });
                    if ($$.attr('rel') == 'webclasses') $.get('/paypal/pay/WEBCLASS/'+$('#reference').val(), function(fb) { $.facebox(fb); });
                    if ($$.attr('rel') == 'events') $.get('/paypal/pay/EVENTS/'+$('#reference').val(), function(fb) { $.facebox(fb); });
                } else {
                    $(document).trigger('close.facebox');
                    $.post('/admission/paynow',{reference: $('#reference').val(), application: $$.attr('rel'), type: payment },function(data) {
                        admissionUtils.getCurrentStatus();
                    });
                }
            }
            return false;
        });
        $('#adm-gopay-confirm').live('click',function(){
            $$ = $(this);
            $(document).trigger('close.facebox');
            $.post('/admission/userpayanytime',{reference: $('#reference').val(), application: $$.attr('rel')},function(data) {
                if (data.length) $('#admission_button').html(data);
            });
        });
        $("#adm_invitation").live('click',function(){
            $$ = $(this);
            $.post('/admission/apply',{reference: $('#reference').val(), application: $$.attr('rel')},function(data) {
                if (data.length) $('#admission_button').html(data);
            });
            return false;
        });
        $("#adm_ignore_invitation").live('click',function(){
            $$ = $(this);
            $.post('/admission/ignore',{reference: $('#reference').val(), application: $$.attr('rel')},function(data) {
                if (data.length) $('#admission_button').html(data);
            });
            return false;
        });
        $("#adm_teach_invitation").live('click',function(){
            $$ = $(this);
            $.post('/admission/apply',{reference: $('#reference').val(), application: $$.attr('rel')},function(data) {
                if (data.length) $('#admission_button').html(data);
            });
            return false;
        });
        $("#adm_ignore_teach_invitation").live('click',function(){
            $$ = $(this);
            $.post('/admission/ignore',{reference: $('#reference').val(), application: $$.attr('rel')},function(data) {
                if (data.length) $('#admission_button').html(data);
            });
            return false;
        });
        $('#cancel_enrollment').live('click', function(){
            $$ = $(this);
            $.facebox.settings.opacity = 0;
            $.facebox.settings.modal = true;
            $.facebox( { ajax: '/'+$$.attr('rel')+'/cancel_enrollment' } );
            return false;
        });
        $('#cancel_coteaching').live('click', function(){
            $$ = $(this);
            $.facebox.settings.opacity = 0;
            $.facebox.settings.modal = true;
            $.facebox( { ajax: '/'+$$.attr('rel')+'/cancel_coteaching' } );
            return false;
        });
    },
    getCurrentStatus: function(){
        $.post('/admission/getbutton',{reference: $('#reference').val(), application: $('#application').val(), code: $('#invitation_code').val()}, function(data){
            $('#admission_button').html(data);
            if (document.getElementById('nav_join')) {
                $("#adm_apply").bind('click', join_click);
                $(".status_not_logged").bind('click', join_click);
            }
        });
    }
}

function shareIt() {
    //grab all the anchor tag with rel set to shareit
    $('a[rel=shareit]').hover(function() {
        //get the height, top and calculate the left value for the sharebox
        var height = $(this).height();
        var top = $(this).offset().top;

        //get the left and find the center value
        var left = $(this).offset().left + ($(this).width() /2) - ($('#shareit-box').width() / 2);

        //assign the value to variables and encode it to url friendly
        var url = encodeURIComponent($(this).attr('href'));
        if (url == '%23') url = encodeURIComponent(document.location.href);
        var title = encodeURIComponent($(this).attr('title'));
        if (!title.length) title = encodeURIComponent(document.title);

        //assign the height for the header, so that the link is cover
        $('#shareit-header').height(height);

        //display the box
        $('#shareit-box').show();

        //set the position, the box should appear under the link and centered
        $('#shareit-box').css({'top':top, 'left':left});

        //make the bookmark media open in new tab/window
        $('a.shareit-sm').attr('target','_blank');

        //Setup the bookmark media url and title
        $('a[rel=shareit-delicious]').attr('href', 'http://del.icio.us/post?v=4&amp;noui&amp;jump=close&amp;url=' + url + '&title=' + title);
        $('a[rel=shareit-facebook]').attr('href', 'http://www.facebook.com/share.php?u=' + url + '&t=' + title);
        $('a[rel=shareit-linkedin]').attr('href', 'http://www.linkedin.com/shareArticle?mini=true&url=' + url + '&title=' + title + '&source=sclipo.com');
        $('a[rel=shareit-twitter]').attr('href', 'http://twitter.com/home?status=' + title + '%20-%20' + url);
        $('a[rel=shareit-digg]').attr('href', 'http://digg.com/submit?phase=2&amp;url=' + url + '&amp;title=' + title);
        $('a[rel=shareit-stumbleupon]').attr('href', 'http://www.stumbleupon.com/submit?url=' + url + '&title=' + title);
        $('a.shareit-sm').click(function() { $('#shareit-box').hide();});
        $('#shareit-box').click(function(e){ e.stopPropagation();});
        $(document).click(function(){$('#shareit-box').hide();});
    });
}


function dashboard(){
    if ( !$('body#academy.dashboard').length) return; //Limito alcance del script

    $('.dash_menu').live("click", function() {
        $$ = $(this);
        if ($$.parent().hasClass('selected')) return false;
        $('#dashboard_menu li').removeClass('selected');
        $$.parent().addClass('selected').addClass('loading');
        $('#bottom').css('opacity', '.8').css('cursor', 'wait');
        $.post('/academy/dashboard', { tab: $$.attr('rel') }, function(data){
            $('#work-area').html(data);
            $('#dashboard_menu li').removeClass('loading'); $('#bottom').css('opacity', '1').css('cursor', 'default');
        });
        return false;
    });

    $("#del_back_button").live("click", function() {
        $('#backimage').val('N');
        $('#backtile').removeAttr('checked');
        $('#add_back_button').removeClass('hidden');
        $('#add_back_button').removeClass('hidden');
        $('#chg_back_button').addClass('hidden');
        $('#del_back_button').addClass('hidden');
        $('body').css('background-image', '');
        $('body').css('background-repeat', '');
        return false;
    });


    // pestaña promote

    $('.invitedirectemails').live('click', function(){
        if ($('#manually-invite').is(':hidden'))
        {
            if ($('#no-students').is(':hidden'))
            {
                inviteContactsbyEmail.hiddens();
                $.post('/import/send', { message: $('#invite_message').val(), emails: $('#invited_contacts_mails').val()}, function(data){
                    $('body').prepend('<div class="alertSystem" id="alertSystem">'+data+' '+$('#sent').text()+'</div>');
                    alertSystem();
                });
            }
            else
            {
                $('body').prepend('<div class="alertSystem" id="alertSystem">'+$('#message-manual').text()+'</div>');
                alertSystem();
                return false;
            }
        }
        else
        {
            if ( $.trim($('#invite_emails').val()) == '' )
            {
                $('#invite_emails').focus();
                $('body').prepend('<div class="alertSystem" id="alertSystem">'+$('#message-manual').text()+'</div>');
                alertSystem();
                return false;
            }
            $.post('/import/send', { message: $('#invite_message').val(), emails: $('#invite_emails').val()}, function(data){
                $('body').prepend('<div class="alertSystem" id="alertSystem">'+data+' '+$('#sent').text()+'</div>');
                alertSystem();
                $('#invite_emails').val('');
            });
        }
    });


    $('#import-mail').live("click", function() {
        $.facebox.settings.opacity = .2;
        $.facebox.settings.modal = true;
        $.facebox( { ajax: '/import/address' } );
        return false;
    })

    $('#copy-banner').live("click", function() {
        $('#banner-text').select();
    });

    $('#banner-text').live("click", function() {
        $(this).select();
    });

    // Pestanya Partners

    $('#view_referrals').live("click", function() {
        $('#main_partner_info').hide();
        $('#main_dashboard_partner').show();
        return false;
    });

    $('#promote_page').live("click", function() {
        $('#main_partner_info').show();
        $('#main_dashboard_partner').hide();
        return false;
    });

    $("#academy_url").keyup(function (C) {
        var D = $("#academy_url");
        if (D.val() != "") {
            if ($.inArray(C.keyCode, [16, 17, 18, 20, 27, 33, 34, 35, 37, 38, 39, 40, 144]) == -1) {
                clearTimeout(_tmp.checkNameAvailabilityTimer);
                var E = $(C.target).parent();
                E.find(".url span").text(D.val());
                var F = E.find(".availability");
                if (F.css("display") == "none") {
                    E.find(".msg_availability").fadeOut("medium", function () {
                        F.fadeIn("medium");
                    })
                }
                _tmp.checkNameAvailabilityTimer = setTimeout("checkNameAvailability()", 2000);
            }
        }
    });


    $("#save_custom").live("click", function() {
        var backtile = $('#backtile').is(':checked')?'Y':'N';
        $.postJSON('/academy/save_custom', {academy: $('#pretty_name').val(), url: $('#academy_url').val(), color: $('#color1').val(), backimage: $('#backimage').val(), backtile: backtile}, function(data){
            if (data.vanity) {
                $('#vanity').html(data.vanity).fadeIn('slow');
                $('#academy_url').focus();
                return false;
            }
            //$('#vanity:visible').fadeOut('slow');
            if (data.error) {
                $('body').prepend('<div class="alertSystem" id="alertSystem">'+data.error+'</div>');
                alertSystem();
                return false;
            }
            if (data.msg) {
                $('body').prepend('<div class="alertSystem" id="alertSystem">'+data.msg+'</div>');
                alertSystem();
                if ($('#backimage').val() == 'N') {
                    $('body').css('background-image', '');
                    $('body').css('background-repeat', '');
                } else {
                    var cTime = new Date();
                    var rnd = cTime.getTime();
                    $('body').css('background-image', 'url("http://static.sclipo.com/backgrounds/'+$('#backimage').val()+'?'+rnd+'")');
                    if (backtile == 'Y') {
                        $('body').css('background-repeat', 'repeat-x');
                    } else {
                        $('body').css('background-repeat', 'no-repeat');
                    }
                }
                $('body').css('background-color', $('#color1').val());
            }
        });
        return false;
    });

    $("img.deleteteacher").livequery(function() {
        $(this).hover(function() {
            $(this).attr("src","/scimg/orange-X.png");
        }, function() {
            $(this).attr("src","/scimg/gray-X.png");
        });
    });

    $("img.deleteteacher").live("click", function() {
        $$ = $(this);
        $.postJSON('/academy/get_teacher_activity', {teacher: $$.attr('rel')}, function(data){
            if (data) {
                $('.teaches_courses').text(data.courses);
                $('.teaches_live_session').text(data.sessions);
            }
        });
        $.facebox.settings.opacity = 0;
        $.facebox.settings.modal = true;
        $('.teacher_name').html($$.parents('tr').attr('rel'));
        $("#delete_button").attr('rel', $$.attr('rel'));
        $.facebox( { div: '#delete_teachers' } );
        return false;
    });

    $("#facebox #delete_button").live("click", function() {
        $$ = $(this);
        $.postJSON('/academy/admin_teachers', {action: 'del', teacher: $$.attr('rel')}, function(data){
            if (data.active) {
                $(document).trigger('close.facebox');
                $('#dashboard_table').find('tr[id='+$$.attr('rel')+']').effect('highlight',{},1000).remove();
                $('#active').html(data.active).parents('tr').effect('highlight',{},1000);
            }
        });
        return false;
    });

    $("a.activateteacher").live("click", function() {
        $$ = $(this);
        $.postJSON('/academy/admin_teachers', {action: 'upd', teacher: $$.attr('rel'), status: 'A'}, function(data){
            if (data.error) {
                $.facebox.settings.opacity = 0;
                $.facebox.settings.modal = true;
                $('.teacher_name').html($$.parents('tr').attr('rel'));
                $.facebox( { div: '#teacher_limit' } );
            } else {
                if (data.html_col1) {
                    $$.parents('tr').effect('highlight',{},1000);
                    $$.parents('td').html(data.html_col1).next().html(data.html_col2);
                    var total = parseInt($('#active').html()) + 1;
                    $('#active').html(total).parents('tr').effect('highlight',{},1000);
                }
            }
        });
        return false;
    });

    $("a.pauseteacher").live("click", function() {
        $$ = $(this);
        $.facebox.settings.opacity = 0;
        $.facebox.settings.modal = true;
        $("#pause_button").attr('rel', $$.attr('rel'));
        $('.teacher_name').html($$.parents('tr').attr('rel'));
        $.postJSON('/academy/get_teacher_activity', {teacher: $$.attr('rel')}, function(data){
            if (data) {
                $('.teaches_courses').text(data.courses);
                $('.teaches_live_session').text(data.sessions);
            }
        });

        $.facebox( { div: '#pause_teachers' } );
        return false;
    });

    $("#a_invite_more_teachers").live("click", function() {
        $(this).hide();
        $('#capa_invitacion').slideDown('slow');
        $('html, body').animate({scrollTop: $('#send_invitations').offset().top}, 'slow');
        return false;
    });

    $("#send_invitations").live("click", function() {
        inviteStudents.hiddens();
        $('html, body').animate({scrollTop:0}, 'slow');
        $.postJSON('/academy/invite_teachers', {message: $('#invite_message').val(), contacts: $('#invited_contacts').val(), mails: $('#invited_mails').val() }, function(data){
            if (data.invitations) {
                $('body').prepend('<div class="alertSystem" id="alertSystem">'+data.invitations+'</div>');
                alertSystem();
            }
            $.post('/academy/dashboard', { tab: 'teachers' }, function(data){
                $('#work-area').html(data);
                $('#dashboard_menu li').removeClass('loading'); $('#bottom').css('opacity', '1').css('cursor', 'default');
            });
        });
        return false;
    });

    $("#cancel_send_invitations").live("click", function() {
        $('html, body').animate({scrollTop:0}, 'slow');
        $('#capa_invitacion').slideUp('slow');
        $("#a_invite_more_teachers").show();
        return false;
    });

    $("#facebox #pause_button").live("click", function() {
        $$ = $(this);
        $.postJSON('/academy/admin_teachers', {action: 'upd', teacher: $$.attr('rel'), status: 'P'}, function(data){
            if (data.html_col1) {
                $(document).trigger('close.facebox');
                var tr = $('#dashboard_table').find('tr[id='+$$.attr('rel')+']');
                tr.effect('highlight',{},1000);
                tr.find('>td:nth-child(2)').html(data.html_col1).next().html(data.html_col2);
                var total = parseInt($('#active').html()) - 1;
                $('#active').html(total).parents('tr').effect('highlight',{},1000);
            }
        });
        return false;
    });

    $("#contacts-sclipo li > :checkbox").live("click", function() {
        $("#selectnone").css("display","inline");
    });
    $("#selectall").live("click", function() {
        $("#contacts-sclipo li > :checkbox").each(function(){
            if ($(this).parent().is(':visible')) $(this).click();
        });
        $("#contacts-sclipo li > :checkbox").attr("checked",false);
    });
    $("#selectnone").live("click", function() {
        $('#invite-students > li > a').click();
    });

    if ($('#chg_back_button').length){
        new AjaxUpload($('#chg_back_button'),{
            action: '/academy/background',
            name: 'background',
            onSubmit : function(file, ext){

                var arr_image = ['jpg', 'jpeg', 'png', 'gif'];
                if ( $.inArray(ext[0],arr_image) < 0 ) {
                    return false;
                }
                $.facebox.settings.opacity = .2;
                $.facebox.settings.modal = true;
                $.facebox( { div: '#select_background' } );
            },
            onComplete: function(file, response){
                $(document).trigger('close.facebox');
                var error = response.split(':')[0];
                if (error != '')
                {
                    alert('Error: ' + response);
                }
                else
                {
                    var image = response.split(':')[1];
                    var cTime = new Date();
                    var rnd = cTime.getTime();
                    $('body').css('background-image', 'url("http://static.sclipo.com/backgrounds/'+image+'?'+rnd+'")');
                    var backtile = $('#backtile').is(':checked')?'Y':'N';
                    if (backtile == 'Y') {
                        $('body').css('background-repeat', 'repeat-x');
                    } else {
                        $('body').css('background-repeat', 'no-repeat');
                    }
                    $('#backimage').val(image);
                    $('#add_back_button').addClass('hidden');
                    $('#chg_back_button').removeClass('hidden');
                    $('#del_back_button').removeClass('hidden');
                }
            }
        });
    }

    if ($('#add_back_button').length){
        new AjaxUpload($('#add_back_button'),{
            action: '/academy/background',
            name: 'background',
            onSubmit : function(file, ext){

                var arr_image = ['jpg', 'jpeg', 'png', 'gif'];
                if ( $.inArray(ext[0],arr_image) < 0 ) {
                    return false;
                }
                $.facebox.settings.opacity = .3;
                $.facebox.settings.modal = true;
                $.facebox( { div: '#select_background' } );
            },
            onComplete: function(file, response){
                $(document).trigger('close.facebox');
                var error = response.split(':')[0];
                if (error != '')
                {
                    alert('Error: ' + response);
                }
                else
                {
                    var image = response.split(':')[1];
                    var cTime = new Date();
                    var rnd = cTime.getTime();
                    $('body').css('background-image', 'url("http://static.sclipo.com/backgrounds/'+image+'?'+rnd+'")');
                    var backtile = $('#backtile').is(':checked')?'Y':'N';
                    if (backtile == 'Y') {
                        $('body').css('background-repeat', 'repeat-x');
                    } else {
                        $('body').css('background-repeat', 'no-repeat');
                    }
                    $('#backimage').val(image);
                    $('#add_back_button').addClass('hidden');
                    $('#chg_back_button').removeClass('hidden');
                    $('#del_back_button').removeClass('hidden');
                }
            }
        });
    }
}

function checkNameAvailability() {
var C = $("#academy_url").parent();
$.ajax({
    type: "GET",
    url: "/academy/academy_available",
    data: {
        academy: $("#academy_url").val()
    },
    dataType: "json",
    success: function (E) {
        var F = E.msg;
        var D = E.valid ? "green" : "red";
        C.find(".msg_availability").text(F).css("color", D);
    },
    complete: function () {
        C.find(".availability").fadeOut("medium", function () {
            C.find(".msg_availability").fadeIn("medium")
        });
        clearTimeout(_tmp.checkNameAvailabilityTimer);
    }
});
}


var paypal_plan = {
    init: function(){
        if ($('body#plan').length == 0) return;
        $('.paypal-plan-button').live('click', function(){
            if ($("#sign").length > 0)
            {
                $('form').append('<input type="hidden" name="premium" value="1">');
                $('#login').slideDown('fast'); //no esta logueado
            }
            else{
		if ($('#facebox #pay_month_year').length>0) {
			$('#facebox #pay_month_year').remove();
		}

                var plan = $(this).attr('rel');
                var prices = $(this).attr('value');
                $('#price_per_year').html(prices.split('/')[1]);
                $('#price_per_month').html(prices.split('/')[0]);
                $('#plan_selected').val(plan);
                $('#payment_option').attr('checked','checked');
                $.facebox.settings.opacity = 0.3;
                $.facebox.settings.modal = true;
                $.facebox( { div: '#pay_month_year' } );
            }
            return false;
        });
        $('#facebox .confirm_payment').live('click', function(){
            var plan = $('#plan_selected').val();
            var option = $('#facebox input:radio:checked').val();
            /*
            if (!option.length) {
                $('#facebox #payment_option_error').slideDown('fast');
                setTimeout(function() {
                    $('#facebox #payment_option_error').fadeOut('slow').slideUp('slow');
                }, 4000);
                return false;
            }
            */
            $.facebox( { ajax: '/paypal/pay/' + option + plan } );
            return false;
        });
    }
}


//New Test
var testUtils = function(){
    $('#new-question').live('click', function(){
        $('#another-question').show();
        return false;
    });
    $('.new-response').live('click', function(){
        $(this).parent().next().show();
        $(this).parent().next().find('input[type="checkbox"]').removeAttr("checked", 'checked');
        $(this).parent().next().find('input[type="text"]').val('');
        $(this).hide();
        return false;
    });
    $('.delete-response').live('click', function(){
        $(this).parent().prev().find('span').show();
        $(this).parent().hide();
        return false;
    });
    $('#response-type').live('change', function(){
        if ($(this).val() == 'T') $('#responses').hide(); else $('#responses').show();
    });
    $('#save-question').live('click', function(){
        if ($('#response-type').val() != 'T') {
            var one_response = false;
            $("#responses input[type='checkbox']:checked").each(function(){
                if ($(this).parent().css('display') != 'none') one_response = true;
            });
            if (!one_response) alert('check one response');
        }
    });
    $('#responses input[type="checkbox"]').live('click', function(){
        if ($('#response-type').val() != 'S') return true;
        $$ = $(this);
        $("#responses input[type='checkbox']:checked").each(function(){
            if ($(this).attr('rel') != $$.attr('rel')) $(this).removeAttr("checked", 'checked');
        });
        return true;
    });
}();


var onlinetest = {
    init: function(){
        if ($('body#academy.courses').length == 0) return;
        $('#createtest').live('click', function(){
            if ($("#sign").length > 0)
            {
                $('form').append('<input type="hidden" name="premium" value="1">');
                $('#login').slideDown('fast'); //no esta logueado
            }
            else{
                $.facebox.settings.opacity = 0.3;
                $.facebox.settings.modal = true;
				var task_id = 0;
				if ($('#task_id').length) task_id = $('#task_id').val();
		   		$.post('/onlinetest/create', { task_id: task_id }, function(data){
		            if (data) $.facebox( data );
				});
								
                // $.facebox( { ajax: '/onlinetest/create' } );
            }
            return false;
        });

        $('#opentest, #confirm_start_test_task_btn').live('click', function(){
            if ($("#sign").length > 0)
            {
                $('form').append('<input type="hidden" name="premium" value="1">');
                $('#login').slideDown('fast'); //no esta logueado
            }
            else{
                $.facebox.settings.opacity = 0.3;
                $.facebox.settings.modal = true;
				var id = $(this).attr('rel');
                $.facebox( { ajax: '/onlinetest/load_test/'+id } );
            }
            return false;
        });

        $('#facebox #start_test').live('click', function(){
            $.post('/onlinetest/start_test', { course: $('#reference').val(), task_id: $('#task_id').val(), reference: $('#facebox #test_reference').val(), total: $('#facebox #total_questions').val() }, function(data){
				if (parseInt($('#timeleft').html()) > 0){
					var minutes = parseInt($('#timeleft').html()) * 60;
                	$('#facebox #timeleft').countdown({initialValue: minutes, displayFormat:'HMS', onExpire: onlinetest.endTestTime});
				}
                $('#facebox #status_bar').fadeIn('fast');
                $('#facebox #question_no').html($('#facebox #next_question').val());
                $('#facebox #test_work_area').html(data);
                $('#facebox #next_question').val( parseInt($('#facebox #next_question').val()) + 1);
            });
        });

        $('#facebox #send_answer').live('click', function(){
            var answer = '';
			$('input:checked').each( function() {
                answer = answer + $(this).val() +',';
            });

			if (answer == '') { 
                $('#answer_required').slideDown('fast');
                setTimeout(function(){ $('#answer_required').slideUp('fast');  }, 4000);
				return false;
			}
            if (answer != '') answer = answer.replace(/,$/,""); // cut last ','

			var $$ = $(this);
			if ($$.hasClass('saving')) return false;
	        $$.addClass('saving');
			
            $.post('/onlinetest/next_question', { reference: $('#facebox #test_reference').val(), answer: answer, id_question: $(this).attr('rel'), question: $('#facebox #next_question').val(), total: $('#facebox #total_questions').val(), time: $('#facebox #timeleft').html(), test_id: $('#test_id').val(), task: $('#task_id').val() }, function(data){
                if ($('#facebox #next_question').val() == '1') {
                    $('#facebox #timeleft').countdown({initialValue: 30, displayFormat:'HMS', onExpire: onlinetest.endTestTime});
                    $('#facebox #status_bar').fadeIn('fast');
                }
                if ($('#facebox #next_question').val() > $('#facebox #total_questions').val())
                {
                    $('#facebox #status_bar').fadeOut('fast');
                }
                $('#facebox #question_no').html($('#facebox #next_question').val());
                $('#facebox #next_question').val( parseInt($('#facebox #next_question').val()) + 1);
                $('#facebox #test_work_area').html(data);
            });
        });

        $('#facebox .cancel_test').live('click', function(){
			window.clearTimeout(setTimeout("0")-1);
			// Ejecutamos alertSystem(); por si hay algun mensaje pendiente
			alertSystem();
			
	        $.post('/learningpath/view', { application: $('#application').val(), reference: $('#reference').val(), task: $('#task_id').val() }, function(data){
	            $('#learningpath').html(data);	
	        	$(document).trigger('close.facebox');
			});
	        return false;
        });

        $('#facebox #test_create_next_step').live('click', function(){

            if ($('#input_test_title').val() == $('#input_test_title').attr('default') || $('#input_test_title').val() == '')
            {
                $('#test_error_title').slideDown('fast');
                setTimeout(function(){ $('#test_error_title').slideUp('fast');  }, 4000);
                $('#input_test_title').focus();
                return false;
            }
/*
            if ($('#input_test_description').val() == $('#input_test_description').attr('default') || $('#input_test_description').val() == '')
            {
                $('#test_error_description').slideDown('fast');
                setTimeout(function(){ $('#test_error_description').slideUp('fast');  }, 4000);
                $('#input_test_description').focus();
                return false;
            }
*/
            if ($('#category').val() == '')
            {
                $('#test_error_category').slideDown('fast');
                setTimeout(function(){ $('#test_error_category').slideUp('fast');  }, 4000);
                $('#category').focus();
                return false;
            }
            if ($('#category').val() == 12 && $('#other_category').val() == '')
            {
                $('#test_error_other_category').slideDown('fast');
                setTimeout(function(){ $('#test_error_other_category').slideUp('fast');  }, 4000);
                $('#other_category').focus();
                return false;
            }

            if ($('#percent').val() == '')
            {
                $('#test_error_percent').slideDown('fast');
                setTimeout(function(){ $('#test_error_percent').slideUp('fast');  }, 4000);
                $('#percent').focus();
                return false;
            }

			var task_id = 0, course = '';
			if ($('#task_id').length){
				task_id = $('#task_id').val();
			}
			if ($('#reference').length){
				course = $('#reference').val();
			}
			 
            $.post('/onlinetest/create_test', { title: $('#facebox #input_test_title').val(), description: $('#facebox #input_test_description').val(), category: $('#category').val(), othercategory: $('#show_other_category').val(), duration: $('#duration').val(), attempts: $('#attempts').val(), percent: $('#percent').val(), level: $('#level').val(), task_id: task_id, course: course }, function(data){
                $('#facebox #test_work_area').html(data.html);
                $('body').prepend('<div class="alertSystem" id="alertSystem">'+data.msg+'</div>');
                alertSystem();
            }, 'json' );
            return false;
        });

		$('.add_answer').live('click', function(){
			var next_answer = $('#table-answers tr').length-3;
			if (next_answer > 6){
				return false;
			}
			$('.delete_one_question').show();
			if (next_answer == 6){
				$(this).css('display', 'none');
			}
			html = $('<div>').append($('#new_question_tpl').clone()).remove().html();
			html = html.replace('id="new_question_tpl" ','class="test_answer" ');
			html = html.replace("display: none; ",""); 
			html = html.replace('new_autoclean', 'do_autoclean');
			//html = html.replace("a_answer","a_answer"+next_answer);
			//html = html.replace("t_answer","t_answer"+next_answer);
			$('#table-answers tr#new_question_tpl').before(html);
			var contador = 1;
			$('#table-answers span.contador').each(function(){
				$(this).html(contador++);
			});			
			$('.do_autoclean').autoClean().removeClass('do_autoclean');
			return false;
		});

		$('#test_save_question').live('click', function(){
			var $$ = $(this);
			if ($$.hasClass('saving')) return false;
			
			var answer = 1,
			texto = '"answers": [ ',
			correctas = '',
			two_answers = 0;
			$('.test_answer').each(function(){
				var $this = $(this);
			    var textarea = $this.find("textarea");
			    var checkbox = $this.find("input:checkbox");
			    if (textarea.val() != textarea.attr('default') && $.trim(textarea.val())) {
					two_answers++;
			        texto = texto + '"'+textarea.val().replace('"',"'")+'",';
			        if (checkbox.attr('checked')){
			             correctas = correctas + answer + ',';
			        }
			    }   
			    answer++;
			});
			correctas = correctas.substr(0,correctas.length-1);
			if (correctas.length > 1) {
			    var respuestas = '{ "type": "M", '+texto.substr(0,texto.length-1)+' ] }';
			} else {
			    var respuestas = '{ "type": "U", '+texto.substr(0,texto.length-1)+' ] }';
			}

            if ($('#text_question').val() == $('#text_question').attr('default') || $.trim($('#text_question').val()) == ''){
            	$('body').prepend('<div class="alertSystem" id="alertSystem">'+$('#missing_question').val()+'</div>');
            	alertSystem();
				return false;
			}			
			if (two_answers < 2){
            	$('body').prepend('<div class="alertSystem" id="alertSystem">'+$('#missing_answers').val()+'</div>');
            	alertSystem();
				return false;
			}			
			
			if ($.trim(correctas) == ''){
            	$('body').prepend('<div class="alertSystem" id="alertSystem">'+$('#missing_correct').val()+'</div>');
            	alertSystem();
				return false;
			}
	        $$.addClass('saving');
			$$.html('<img style="margin-top: 6px;" src="/scimg/spinner.gif">');
	        $.post('/onlinetest/create_test', {  reference: $('#test_reference').val(), question: $('#facebox #question').val(), question_text: $('#facebox #text_question').val(), answers: respuestas, correct: correctas}, function(data){
	            $('#facebox #test_work_area').html(data.html);
				if (!$('#alertSystem').length){
	            	$('body').prepend('<div class="alertSystem" id="alertSystem">'+data.msg+'</div>');
	            	alertSystem();
				}
	        }, 'json' );
	        return false;		
		});

		$('.finish_edit_test').live('click', function(){
			var $$ = $(this);
			if ($$.hasClass('saving')) return false;

           	if ($('#text_question').val() == $('#text_question').attr('default') || $.trim($('#text_question').val()) == ''){
				$.post('/learningpath/view', { application: $('#application').val(), reference: $('#reference').val(), task: $('#task_id').val() }, function(data){
					$('#learningpath').html(data);
					$('#bottom').css('opacity', '1');
					$('#course-preview .courses-main-menu[rel=learningpath]').removeClass('loading');
				});	
			} else {
				var answer = 1,
				texto = '"answers": [ ',
				correctas = '',
				two_answers = 0;
				$('.test_answer').each(function(){
					var $this = $(this);
					var textarea = $this.find("textarea");
					var checkbox = $this.find("input:checkbox");
					if (textarea.val() != textarea.attr('default') && $.trim(textarea.val())) {
						two_answers++;
						texto = texto + '"'+textarea.val().replace('"',"'")+'",';
						if (checkbox.attr('checked')){
							correctas = correctas + answer + ',';
						}
					}   
					answer++;
				});
				correctas = correctas.substr(0,correctas.length-1);
				if (correctas.length > 1) {
					var respuestas = '{ "type": "M", '+texto.substr(0,texto.length-1)+' ] }';
				} else {
					var respuestas = '{ "type": "U", '+texto.substr(0,texto.length-1)+' ] }';
				}

				if ($('#text_question').val() == $('#text_question').attr('default') || $.trim($('#text_question').val()) == ''){
					$('body').prepend('<div class="alertSystem" id="alertSystem">'+$('#missing_question').val()+'</div>');
					alertSystem();
					return false;
				}			
				if (two_answers < 2){
					$('body').prepend('<div class="alertSystem" id="alertSystem">'+$('#missing_answers').val()+'</div>');
					alertSystem();
					return false;
				}			

				if ($.trim(correctas) == ''){
					$('body').prepend('<div class="alertSystem" id="alertSystem">'+$('#missing_correct').val()+'</div>');
					alertSystem();
					return false;
				}

				$$.addClass('saving');
				$$.html('<img style="margin-top: 6px;" src="/scimg/spinner.gif">');
				$.post('/onlinetest/edit_test', { reference: $('#test_reference').val(), id_question: $('#facebox #id_question').val(), question: $('#facebox #question').val(), question_text: $('#facebox #text_question').val(), answers: respuestas, correct: correctas}, function(data){
					if (!$('#alertSystem').length){
						$('body').prepend('<div class="alertSystem" id="alertSystem">'+data.msg+'</div>');
						alertSystem();
					}
					$(document).trigger('close.facebox');
					$('#bottom').css('opacity', '.2');
					$('#course-preview .courses-main-menu[rel=learningpath]').addClass('loading');	
					$.post('/learningpath/view', { application: $('#application').val(), reference: $('#reference').val(), task: $('#task_id').val() }, function(data){
						$('#learningpath').html(data);
						$('#bottom').css('opacity', '1');
						$('#course-preview .courses-main-menu[rel=learningpath]').removeClass('loading');
					});

				}, 'json' );	
			}		
			/*
		    $(document).trigger('close.facebox');
	        $('#bottom').css('opacity', '.2');
			$('#course-preview .courses-main-menu[rel=learningpath]').addClass('loading');	
	        $.post('/learningpath/view', { application: $('#application').val(), reference: $('#reference').val(), task: $('#task_id').val() }, function(data){
	            $('#learningpath').html(data);
	            $('#bottom').css('opacity', '1');
				$('#course-preview .courses-main-menu[rel=learningpath]').removeClass('loading');
            });			*/		
			return false;
		});
		
		$('#test_update_question').live('click', function(){
			var $$ = $(this);
			if ($$.hasClass('saving')) return false;
			
			var answer = 1,
			texto = '"answers": [ ',
			correctas = '',
			two_answers = 0;
			$('.test_answer').each(function(){
				var $this = $(this);
			    var textarea = $this.find("textarea");
			    var checkbox = $this.find("input:checkbox");
			    if (textarea.val() != textarea.attr('default') && $.trim(textarea.val())) {
					two_answers++;
			        texto = texto + '"'+textarea.val().replace('"',"'")+'",';
			        if (checkbox.attr('checked')){
			             correctas = correctas + answer + ',';
			        }
			    }   
			    answer++;
			});
			correctas = correctas.substr(0,correctas.length-1);
			if (correctas.length > 1) {
			    var respuestas = '{ "type": "M", '+texto.substr(0,texto.length-1)+' ] }';
			} else {
			    var respuestas = '{ "type": "U", '+texto.substr(0,texto.length-1)+' ] }';
			}

           	if ($('#text_question').val() == $('#text_question').attr('default') || $.trim($('#text_question').val()) == ''){
           		$('body').prepend('<div class="alertSystem" id="alertSystem">'+$('#missing_question').val()+'</div>');
           		alertSystem();
				return false;
			}			
			if (two_answers < 2){
           		$('body').prepend('<div class="alertSystem" id="alertSystem">'+$('#missing_answers').val()+'</div>');
           		alertSystem();
				return false;
			}			
		
			if ($.trim(correctas) == ''){
           		$('body').prepend('<div class="alertSystem" id="alertSystem">'+$('#missing_correct').val()+'</div>');
           		alertSystem();
				return false;
			}

	        $$.addClass('saving');
			$$.html('<img style="margin-top: 6px;" src="/scimg/spinner.gif">');
	        $.post('/onlinetest/edit_test', { reference: $('#test_reference').val(), id_question: $('#facebox #id_question').val(), question: $('#facebox #question').val(), question_text: $('#facebox #text_question').val(), answers: respuestas, correct: correctas}, function(data){
	            $('#facebox #test_work_area').html(data.html);
				if (!$('#alertSystem').length){
	            	$('body').prepend('<div class="alertSystem" id="alertSystem">'+data.msg+'</div>');
	            	alertSystem();
				}
	        }, 'json' );
	        return false;		
		});

		$('.navigate_questions').live('click', function(){
			$$ = $(this);
			var question_no = $$.attr('rel');
	        $.post('/onlinetest/navigate', { reference: $('#test_reference').val(), question: question_no }, function(data){
	            $('#facebox #test_work_area').html(data.html);
	        }, 'json' );
	        return false;			
		});

		$('.delete_one_question').live('click', function(){
			var next_answer = $('#table-answers tr').length-3;
			if (next_answer == 3){
				return false;
			}		
			if (next_answer == 4){
				$('.delete_one_question').hide();
			}	
			if (next_answer < 8){
				$('.add_answer').show();
			}			
			var $$ = $(this).parent().parent();
			$$.slideUp('fast').remove();
			var contador = 1;
			$('#table-answers span.contador').each(function(){
				$(this).html(contador++);
			});
			return false;
		});
        $('#publish_test').live('click', function(){
			$('#delete_task_id').val($(this).attr('rel'));
	        $.facebox.settings.opacity = 0.2;
	        $.facebox.settings.modal = true;
	        $.facebox( { div: '#publish_test_popup' } );	
	        return false;
        });

	    $("#confirm_publish_test_btn").live('click',function(){
		    $(document).trigger('close.facebox');
	        $('#bottom').css('opacity', '.2');
			$('#course-preview .courses-main-menu[rel=learningpath]').addClass('loading');	
            $.post('/onlinetest/publish', { reference: $(this).attr('rel') }, function(data){
				$('#course-preview .courses-main-menu[rel=learningpath]').addClass('loading');
		        $.post('/learningpath/view', { application: $('#application').val(), reference: $('#reference').val(), task: $('#task_id').val() }, function(data){
		            $('#learningpath').html(data);
		            $('#bottom').css('opacity', '1');
					$('#course-preview .courses-main-menu[rel=learningpath]').removeClass('loading');
		        });		
            });
	        return false;
		});
		
        $('#edit_test').live('click', function(){
            $.facebox.settings.opacity = 0.3;
            $.facebox.settings.modal = true;
	   		$.post('/onlinetest/edit', { reference: $(this).attr('rel') }, function(data){
	            if (data) $.facebox( data );
			});
	        return false;
        });	
	
		$('#test_edit_next_step').live('click', function(){
            if ($('#category').val() == '')
            {
                $('#test_error_category').slideDown('fast');
                setTimeout(function(){ $('#test_error_category').slideUp('fast');  }, 4000);
                $('#category').focus();
                return false;
            }
            if ($('#category').val() == 12 && $('#other_category').val() == '')
            {
                $('#test_error_other_category').slideDown('fast');
                setTimeout(function(){ $('#test_error_other_category').slideUp('fast');  }, 4000);
                $('#other_category').focus();
                return false;
            }

            if ($('#percent').val() == '')
            {
                $('#test_error_percent').slideDown('fast');
                setTimeout(function(){ $('#test_error_percent').slideUp('fast');  }, 4000);
                $('#percent').focus();
                return false;
            }

			var task_id = 0, course = '';
			if ($('#task_id').length){
				task_id = $('#task_id').val();
			}
			if ($('#reference').length){
				course = $('#reference').val();
			}
			 
            $.post('/onlinetest/edit_test', { reference: $('#test_reference').val(), category: $('#category').val(), othercategory: $('#show_other_category').val(), duration: $('#duration').val(), attempts: $('#attempts').val(), percent: $('#percent').val(), level: $('#level').val(), task_id: task_id, course: course }, function(data){
                $('#facebox #test_work_area').html(data.html);
                $('body').prepend('<div class="alertSystem" id="alertSystem">'+data.msg+'</div>');
                alertSystem();
            }, 'json' );
	        return false;
        });
		
    },
    endTestTime: function(){
		if ($('#finish').length){
        	$('#frame_question').html($('#finish').html());
			$('#question_footer').remove();
		}
    },

    showOther: function(){
        if ($('#facebox #category').val() == '12')
        {
            $('#facebox #show_other_category').show().focus();
        }
        else
        {
            $('#facebox #show_other_category').hide();
        }
    },

	addAnswer: function(){
		var next_answer = $('#table-answers tr').length-3;
		if (next_answer > 6){
			return false;
		}
		$('.delete_one_question').show();
		if (next_answer == 6){
			$('.add_answer').css('display', 'none');
		}
		html = $('<div>').append($('#new_question_tpl').clone()).remove().html();
		html = html.replace('id="new_question_tpl" ','class="test_answer" ');
		html = html.replace("display: none; ",""); 
		html = html.replace('new_autoclean', 'do_autoclean');
		//html = html.replace("a_answer","a_answer"+next_answer);
		//html = html.replace("t_answer","t_answer"+next_answer);
		$('#table-answers tr#new_question_tpl').before(html);
		var contador = 1;
		$('#table-answers span.contador').each(function(){
			$(this).html(contador++);
		});			
		$('.do_autoclean').autoClean().removeClass('do_autoclean');
		return false;
	}
}


function learningpath() {
    $('.filter-learning').live('click',function(){
        // Si han pulsado en el boton seleccionador no hacemos nada
        if ($(this).hasClass('orange-button-selected')) return false;
        $('.orange-button-selected').removeClass('orange-button-selected').addClass('orange-button');
        $(this).removeClass('orange-button');
        $(this).addClass('orange-button-selected');
        var filter = $(this).attr('rel');
        var order = $('#sort').val();
        $('#bottom').css('opacity', '.2');
		$('#course-preview .courses-main-menu[rel=learningpath]').addClass('loading');
		if (filter == 'progress'){
        	$.post('/learningpath/student_progress', { application: $('#application').val(), reference: $('#reference').val() }, function(data){
            	$('#learningpath-work-area').html(data);
            	$('#bottom').css('opacity', '1');
				$('#course-preview .courses-main-menu[rel=learningpath]').removeClass('loading');
        	});
		} else {
			$('#course-preview .courses-main-menu[rel=learningpath]').addClass('loading');
	        $.post('/learningpath', { application: $('#application').val(), reference: $('#reference').val() }, function(data){
	            $('#learningpath').html(data);
	            $('#bottom').css('opacity', '1');
				$('#course-preview .courses-main-menu[rel=learningpath]').removeClass('loading');
	        });		
		}
        return false;
    });

	$('#back2main').live('click',function(){
        $('#bottom').css('opacity', '.2');
		$('#course-preview .courses-main-menu[rel=learningpath]').addClass('loading');
        $.post('/learningpath', { application: $('#application').val(), reference: $('#reference').val() }, function(data){
            $('#learningpath').html(data);
            $('#bottom').css('opacity', '1');
			$('#course-preview .courses-main-menu[rel=learningpath]').removeClass('loading');
        });
        return false;
    });

 	$('.refresh_lp').live('click',function(){
        $('#bottom').css('opacity', '.2');
		$('#course-preview .courses-main-menu[rel=learningpath]').addClass('loading');
        $.post('/learningpath', { application: $('#application').val(), reference: $('#reference').val() }, function(data){
            $('#learningpath').html(data);
            $('#bottom').css('opacity', '1');
			$('#course-preview .courses-main-menu[rel=learningpath]').removeClass('loading');
        });
        return false;
    });

    $('.view_task_detail').live('click',function(){
        var task_id = $(this).parent().parent().parent().attr('id');
        $('#bottom').css('opacity', '.2');
		$('#course-preview .courses-main-menu[rel=learningpath]').addClass('loading');
        $.post('/learningpath/view', { application: $('#application').val(), reference: $('#reference').val(), task: task_id }, function(data){
            $('#learningpath').html(data);
            $('#bottom').css('opacity', '1');
			$('#course-preview .courses-main-menu[rel=learningpath]').removeClass('loading');
        });
        return false;
    });

	$('#write_students').live('click', function(){
		$.facebox.settings.opacity = 0.2;
        $.facebox.settings.modal = true;	
   		$.post('/learningpath/message', { reference: $('#reference').val(), task: $('#task_id').val() }, function(data){
            if (data) $.facebox( data );
		});
		return false;
	});

	$('#write_teachers').live('click', function(){
		$.facebox.settings.opacity = 0.2;
        $.facebox.settings.modal = true;	
   		$.post('/learningpath/message', { reference: $('#reference').val(), task: $('#task_id').val() }, function(data){
            if (data) $.facebox( data );
		});
		return false;
	});
	
	$('#send_lp_message').live('click', function(){
		var type = $(this).attr('rel');
		var error = false;
        $('#error_subject').hide();
        $('#error_body').hide();

        if ($('#msg_body').val() == '') {
            $('#error_body').show();
			$('#msg_body').focus();
            error = true;
        }
        if ($('#msg_subject').val() == '') {
            $('#error_subject').show();
			$('#msg_subject').focus();
            error = true;
        }
        if (error) {
            $('#messages').slideDown('slow', function(){
                setTimeout(function() { $('#messages').slideUp('slow'); }, 4000);
            });
			return false;
        }		
   		$.post('/learningpath/send_message', { reference: $('#reference').val(), text: $('#msg_body').val(), subject: $('#msg_subject').val(), task: $('#task_id').val() }, function(data){
			$(document).trigger('close.facebox');
			if (data){
                $('body').prepend('<div class="alertSystem" id="alertSystem">'+data+'</div>');
                alertSystem();				
			}
		});		
		return false;
	});
	
    $('.alert_info_box .close').live('click',function(){
        $.post('/learningpath/hide_hint', { reference: $('#reference').val() }, function(data){
            $('.alert_info_box').fadeOut();
        });
        return false;
    });

    $("img.delete-close").livequery(function() {
        $(this).hover(function() {
            $(this).attr("src","/scimg/orange-X.png");
        }, function() {
            $(this).attr("src","/scimg/gray-X.png");
        });
    });

    $("img.delete-task").livequery(function() {
        $(this).hover(function() {
            $(this).attr("src","/scimg/orange-X.png");
        }, function() {
            $(this).attr("src","/scimg/gray-X.png");
        });
    });

    $("#edit_task").live('click',function(){
		var id = $('#task_id').val();
        $.facebox.settings.opacity = 0.2;
        $.facebox.settings.modal = true;	
   		$.post('/learningpath/edit_task', { reference: $('#reference').val(), id: id }, function(data){
            if (data) $.facebox( data );
		    $("#task_deadline").removeClass('hasDatepicker').datepicker({ minDate: new Date() });
		});
        return false;
    });

    $(".delete-task").live('click',function(){
		$('#delete_task_id').val($(this).attr('rel'));
        $.facebox.settings.opacity = 0.2;
        $.facebox.settings.modal = true;
        $.facebox( { div: '#delete_task_popup' } );
        return false;
    });

    $(".delete_task_btn").live('click',function(){
        var id = $('#delete_task_id').val();
        $.post('/learningpath/delete_task', { reference: $('#reference').val(), id: id }, function(data){
			$(document).trigger('close.facebox');
			if ($('.task_list_'+id).length) { $('.task_list_'+id).fadeOut().remove() } else { $('#back2main').trigger('click'); }
        });
        return false;
	});

    $(".clone-task").live('click',function(){
		$('#delete_task_id').val($(this).attr('rel'));
	    $.facebox.settings.opacity = 0.2;
	    $.facebox.settings.modal = true;
	    $.facebox( { div: '#duplicate_task_popup' } );
	    return false;
	});
 
    $("#confirm_duplicate_task_btn").live('click',function(){
        var id = $(this).attr('rel');
        $('#bottom').css('opacity', '.2');
		$('#course-preview .courses-main-menu[rel=learningpath]').addClass('loading');
        $.post('/learningpath/clone_task', { course: $('#reference').val(), task: id }, function(data){
	        $(document).trigger('close.facebox');
	        $.post('/learningpath/view', { application: $('#application').val(), reference: $('#reference').val(), task: data.task_id }, function(data){
	            $('#learningpath').html(data);
	            $('#bottom').css('opacity', '1');
				$('#course-preview .courses-main-menu[rel=learningpath]').removeClass('loading');
	        });	
        }, "json");
        return false;
	});
	
    $("#select_task_type").live($.browser.msie ? "click" : "change",function(){
        if ($(this).val() != 'none') {
            $.facebox.settings.opacity = 0.2;
            $.facebox.settings.modal = true;
			$('.time_to_complete').show();
			if ($("#select_task_type option:selected").val() == 'tt'){
				$('.time_to_complete').hide();
			}
            $.facebox( { div: '#create_task_popup' } );
	        var context = $('#facebox');

            $('#task_type', context).html($("#select_task_type option:selected").text());
		    $("#task_deadline", context).removeClass('hasDatepicker').datepicker({ minDate: new Date() });
        }
        return false;
    });

    $(".add_new_task").live('click',function(){
        var context = $('#facebox');
        var errors = false;
        $('#display_errors', context).children("li").addClass('hidden');
        if ($('#task_complete',context).val() == '' && $('.time_to_complete').is(':visible')){
            $('#task_complete',context).focus();
            $('#msg_3',context).removeClass('hidden');
            errors = true;
        }
        if ($('#task_title',context).val() == ''){
            $('#task_title',context).focus();
            $('#msg_1',context).removeClass('hidden');
            errors = true;
        }
        if (errors) {
            $('#display_errors', context).slideDown();

            setTimeout(function() { $('#display_errors', context).slideUp().children("li").addClass('hidden'); }, 6000);
            return false;
        }
        $('#bottom').css('opacity', '.2');
		$('#course-preview .courses-main-menu[rel=learningpath]').addClass('loading');		
        $.postJSON('/learningpath/add_task', { order: $('#table-task tr').length+1, application: $('#application').val(), reference: $('#reference').val(), title: $('#task_title',context).val(), deadline: $('#task_deadline', context).val(), complete: $('#task_complete',context).val(), time: $('#task_time', context).val(), type: $('.select_task_type').val()  }, function(data){
            if (data) {
                $('.no_tasks').hide().remove();
                $('#publish_learning_path').removeClass('hidden');
                // Anyadir nueva tarea al final de la tabla
                $('#table-task tr:last').after(data.html);
		        $.post('/learningpath/view', { application: $('#application').val(), reference: $('#reference').val(), task: data.task_id }, function(data){
		            $('#learningpath').html(data);
		            $('#bottom').css('opacity', '1');
					$('#course-preview .courses-main-menu[rel=learningpath]').removeClass('loading');
		        });
            }
        });
        $(".select_task_type option[value='none']").attr('selected', 'selected');
        $(document).trigger('close.facebox');
        return false;
    });


    $(".save_task").live('click',function(){
        var context = $('#facebox');
        var errors = false;
        $('#display_errors', context).children("li").addClass('hidden');
        if ($('#task_complete',context).val() == ''){
            $('#task_complete',context).focus();
            $('#msg_3',context).removeClass('hidden');
            errors = true;
        }
        if ($('#task_title',context).val() == ''){
            $('#task_title',context).focus();
            $('#msg_1',context).removeClass('hidden');
            errors = true;
        }
        if (errors) {
            $('#display_errors', context).slideDown();

            setTimeout(function() { $('#display_errors', context).slideUp().children("li").addClass('hidden'); }, 6000);
            return false;
        }
		$('#bottom').css('opacity', '.2');
		$('#course-preview .courses-main-menu[rel=learningpath]').addClass('loading');
		var task_id = $('#task_id', context).val();
        $.post('/learningpath/save_task', { task: task_id, reference: $('#reference').val(), title: $('#task_title',context).val(), deadline: $('#task_deadline', context).val(), complete: $('#task_complete',context).val(), time: $('#task_time', context).val()  }, function(data){    
	        $.post('/learningpath/view', { application: $('#application').val(), reference: $('#reference').val(), task: task_id }, function(data){
	            $('#learningpath').html(data);
	            $('#bottom').css('opacity', '1');
				$('#course-preview .courses-main-menu[rel=learningpath]').removeClass('loading');
	        });
        });
        $(document).trigger('close.facebox');
        return false;
    });

	$("#save-instructions").live('click', function(){
		var button = $(this);
		button.attr('disabled', 'disabled');
        var id = button.attr('rel');
		$('#wysiwyg-wait').show();
		$('body').css('cursor', 'wait');
		$('.wait_overlay').show();
        $.post('/learningpath/saveInstructions', { reference: $('#reference').val(), task: id, instructions: $('#instructions').val() }, function(data){
			button.removeAttr('disabled');
			$('body').css('cursor', 'default');
			$('.wait_overlay').hide();
			$('#wysiwyg-wait').hide();
        });
		return false;
	});

    $(".cancel_task").live('click',function(){
        $(".select_task_type option[value='none']").attr('selected', 'selected');
        $(document).trigger('close.facebox');
        return false;
    });

    $(".end_test").live('click',function(){
		window.clearTimeout(setTimeout("0")-1);
		// Ejecutamos alertSystem(); por si hay algun mensaje pendiente
		alertSystem();
        $.post('/learningpath/view', { application: $('#application').val(), reference: $('#reference').val(), task: $('#task_id').val() }, function(data){
            $('#learningpath').html(data);	
        	$(document).trigger('close.facebox');
		});
        return false;
    });

    $('.publish_learning_path').live('click',function(){
	    $.facebox.settings.opacity = 0.2;
	    $.facebox.settings.modal = true;
	    $.facebox( { div: '#publish_lp_popup' } );
        return false;
    });

    $('.publish_lp_btn').live('click',function(){
        $.post('/learningpath/publish', { reference: $('#reference').val() }, function(data){
	        $(document).trigger('close.facebox');
	        $('.publish_learning_path').fadeOut();
        });
        return false;
    });

    $('#complete_task_btn').live('click',function(){
        $.facebox.settings.opacity = 0.2;
        $.facebox.settings.modal = true;
        $.facebox( { div: '#complete_task_popup' } );
        return false;
    });

	$('#start_task_btn').live('click',function(){
	    $.facebox.settings.opacity = 0.2;
	    $.facebox.settings.modal = true;
	    $.facebox( { div: '#start_task_popup' } );
        return false;
    });

	$('.start_test_task_btn').live('click',function(){
	    $.facebox.settings.opacity = 0.2;
	    $.facebox.settings.modal = true;
	    $.facebox( { div: '#start_test_task_popup' } );
        return false;
    });

	$('.repeat_test_task_btn').live('click',function(){
        $(document).trigger('close.facebox');
	    $.facebox.settings.opacity = 0.2;
	    $.facebox.settings.modal = true;
	    $.facebox( { div: '#start_test_task_popup' } );
        return false;
    });


    $('#confirm_complete_task_btn').live('click',function(){
		var task_id = $('#task_id').val();
        $.post('/learningpath/complete_task', { course: $('#reference').val(), task: task_id }, function(data){
	        $.post('/learningpath/view', { application: $('#application').val(), reference: $('#reference').val(), task: task_id }, function(data){
	            $('#learningpath').html(data);
		        $(document).trigger('close.facebox');
	        });
	    });
        return false;
    });

	$('#confirm_start_task_btn').live('click',function(){
		var task_id = $('#task_id').val();		
        $.post('/learningpath/start_task', { course: $('#reference').val(), task: task_id }, function(data){
	        $.post('/learningpath/view', { application: $('#application').val(), reference: $('#reference').val(), task: task_id }, function(data){
	            $('#learningpath').html(data);
		        $(document).trigger('close.facebox');
	        });
        });
        return false;
    });

	$('.paginate_task').live('click',function(){
		$('#bottom').css('opacity', '.2');
		$('body').css('cursor', 'wait');
		$('#course-preview .courses-main-menu[rel=learningpath]').addClass('loading');
        $.post('/learningpath/view', { application: $('#application').val(), reference: $('#reference').val(), order: $(this).attr('rel') }, function(data){
            $('#learningpath').html(data);
			$('#bottom').css('opacity', '1');
			$('body').css('cursor', 'default');
			$('#course-preview .courses-main-menu[rel=learningpath]').removeClass('loading');
        });		
        return false;
	});		

}

