$(document).ready(function(){

    toggleMenuInfoGeneral();
    bindLoginAreaPrivada();
    bindSuscripcionNewsletter();
    tabsMenuAD();
    slideShow();
    bindBrotativoNavBar();
    bindClickPaginas();
    bindClickImgContent();
    $('ul.sf-menu').superfish();
    $('.addFav').jFav();//return;
setInterval(function(){//era lo menos complicado
	$('#bannerRotativo .content').each(function(){
		try{this.style.zoom = '0';}catch(e){;}
		try{this.style.filter = ''}catch(e){;}
	});
},500);
});


function toggleMenuInfoGeneral()
{
    $('#menuInfoGeneral .nivel1 ul[data-Desplegable]').css('display', 'none');


    $('#menuInfoGeneral a[data-Desplegador]')
	.each(function(){
		this.switchBk = function(){
			var jqthis = jQuery(this).parents('span:first');
			if(!this.prev_bk)
				this.prev_bk = '#2A6D7F';
			var curr_bk = jqthis.css('background-color');
			jqthis.css('background-color', this.prev_bk);
			this.prev_bk = curr_bk;
		}
		this.switchFore = function(){
			var jqthis = jQuery(this);
			if(!this.prev_fore)
				this.prev_fore = '#FFFFFF';
			var curr_fore = jqthis.css('color');
			jqthis.css('color', this.prev_fore);
			this.prev_fore = curr_fore;
		}
		this.switchClass = function(){
			var jqthis = jQuery(this);
			if(jqthis.hasClass('itemMenu')){
				jqthis.removeClass('itemMenu');
			}
			else{
				jqthis.addClass('itemMenu');
			}	
		}
		this.switchDot = function(){
			var jqthis = jQuery(this);
			var jqel = jqthis.parents('li:first');
			if(!this.dot_switch){
				jqel.css('list-style','none');
				this.dot_switch = true;
			}
			else{
				jqel.css('list-style','disc');
				this.dot_switch = false;
			}
		}
		this.doclick = function(doslide){
			if(!jQuery(this).hasClass('aNivel1')){
				this.switchBk();
				this.switchFore();
				this.switchClass();
				this.switchDot();
			}
			if(doslide==null || doslide)
				$('#menuInfoGeneral ul[data-Desplegable=' + $(this).attr('data-Desplegador') + ']').slideToggle(1000);
		}
	})
	.click(function(){
    	this.doclick();
    });
    
    var gets = $.getUrlVars();
    if(gets['Modulo'] != 'undefined' && gets['Modulo'] == 'paginas')
    {
    	var id_pagina = gets['Id'];
    	var jqlink = $('#menuInfoGeneral a[href*=Modulo\=paginas&Id\=' + id_pagina + ']');
        var parentEls = jqlink
	        .parents()
	        .map(function ()
	        {
	            return $(this).attr('data-Desplegable');
	        })
		;
		var jqdesplegable = jqlink.parents('[data-Desplegable]:first');
		//window.console.log(jqdesplegable[0].doclick);
		var jqdesplegadorclickeable = jQuery('a', jqlink.parents('ul:first').prev('span'));
		if(jqdesplegadorclickeable.length)
			jqdesplegadorclickeable[0].doclick(false);

        $(parentEls).each(function(){
            $('#menuInfoGeneral .nivel1 ul[data-Desplegable=' + this + ']').css('display', 'block');
        });


        //$('#menuInfoGeneral a[href*=Modulo\=paginas&Id\=' + gets['Id'] + ']').parent().parent().parent().css('display', 'block');
    }
}


function bindLoginAreaPrivada()
{
    $('#loginAreaPrivada input.btnEnviar').click(function(){

        $.ajax({
            url: CONF_URL_APP + '/includes/actions.php',
            type:'post',
            data: {
                    'do': 'loginAreaPrivada',
                    CursoUsername: $('#CursoUsername').val(),
                    CursoPassword: $('#CursoPassword').val()
                  },
            cache:false,
            dataType:'json',
            success: function(data)
                     {
                        bloquearPantalla(data.msg, true);
                        setTimeout
                        (
                            function(){
                            $.unblockUI();
                            if(data.dow)
                                doDow(data.dow);
                        }, 3000);
                        
                     }
        });

    });

    $('#loginAreaPrivada input.btnLogout').click(function(){

        $.ajax({
            url: CONF_URL_APP + '/includes/actions.php',
            type:'post',
            data: {
                    'do': 'logoutAreaPrivada'
                  },
            cache:false,
            dataType:'json',
            success: function(data)
                     {
                        bloquearPantalla(data.msg, true);
                        setTimeout
                        (
                            function(){
                            $.unblockUI();
                            if(data.dow)
                                doDow(data.dow);
                        }, 3000);

                     }
        });

    });

}



function bindSuscripcionNewsletter()
{
    $('#addToNewsletter input.btnEnviar').click(function(){
		if(!jQuery('.chkNewsletter')[0].checked){
			alert("Debe aceptar las condiciones para poder suscribirse");
			return;
		}
			
        $.ajax({
            url: CONF_URL_APP + '/includes/actions.php',
            type:'post',
            data: {
                    'do': 'addToNewsletter',
                    Nombre: $('#addToNewsletter .txtNewsletterNombre').val(),
                    Email: $('#addToNewsletter .txtNewsletterEmail').val(),
                    Telefono: $('#addToNewsletter .txtNewsletterTelefono').val(),
                    Profesion: $('#addToNewsletter .txtNewsletterProfesion').val()
                  },
            cache:false,
            dataType:'json',
            success: function(data)
                     {
                        bloquearPantalla(data.msg, true);
                        setTimeout
                        (
                            function(){
                            $.unblockUI();
                            if(data.dow)
                                doDow(data.dow);
                        }, 3000);

                     }
        });

    });

}




function tabsMenuAD()
{
    $("#menuAccesosDirectos").tabs({
        event: 'mouseover'
    });
    /*
Default:
    '<li><a href="#{href}"><span>#{label}</span></a></li>'*/
}




function slideGaleria()
{
    $('#slideGaleria').cycle({
        fx:      'fade',
        speedIn:  2500,
        speedOut: 500,
        sync:     0,
        delay:   -4000
    });
}


function bindBrotativoNavBar()
{
    $('#brotativoNavBar div.prev').click( function(){ gallery('prev'); } );
    $('#brotativoNavBar div.next').click( function(){ gallery('next'); } );
}


function slideShow() {

    if(!$('#bannerRotativo').length)
        return;
    
	//Set the opacity of all images to 0
	$('#bannerRotativo a').css({opacity: 0.0});

	//Get the first image and display it (set it to full opacity)
	$('#bannerRotativo a:first').css({opacity: 1.0});

	//Set the caption background to semi-transparent
	$('#bannerRotativo .caption').css({opacity: 0.7});

	//Resize the width of the caption according to the image width
	//$('#bannerRotativo .caption').css({width: $('#bannerRotativo a').find('img').css('width')});

	//Get the caption of the first image from REL attribute and display it
	$('#bannerRotativo .content').html($('#bannerRotativo a:first').find('img').attr('rel'))
	.animate({opacity: 0.7}, 400);
	$('#bannerRotativo .content').each(function(){
		try{this.style.zoom = '0';}catch(e){;}
	});

	//Call the gallery function to run the slideshow, 6000 = change to next image after 6 seconds
	//setInterval('gallery('next')',6000);

}

function gallery(prevORnext) {
    var current = ($('#bannerRotativo a.show') ?  $('#bannerRotativo a.show') : $('#bannerRotativo a:first'));

    var next = ((current.next().length) ? ((current.next().hasClass('caption'))? $('#bannerRotativo a:first') :current.next()) : $('#bannerRotativo a:first'));
    var prev = ((current.prev().length) ? ((current.prev().hasClass('caption'))? $('#bannerRotativo a:last') :current.prev()) : $('#bannerRotativo a:last'));

    var caption = prevORnext == 'prev' ? prev.find('img').attr('rel') : next.find('img').attr('rel');
    var slide = prevORnext == 'prev' ? prev : next;

    slide.css({opacity: 0.0})
    .addClass('show')
    .animate({opacity: 1.0}, 1000);

    current.animate({opacity: 0.0}, 1000)
    .removeClass('show');

    $('#bannerRotativo .caption').animate({opacity: 0.0}, { queue:false, duration:0 }).css('display', 'none');
    $('#bannerRotativo .caption').animate({opacity: 0.7},100 ).slideDown();
    $('#bannerRotativo .content').html(caption);
	$('#bannerRotativo .content').each(function(){
		try{this.style.zoom = '0';}catch(e){;}
	});

}


function bindClickPaginas()
{
    $('li[data-Url]', '#menuCentroVirtual, #menuInfoGeneral, #menuAccesosDirectos').click(function(){
       window.location = $(this).attr('data-Url');
    });
}

function doDow(dow)
{
    for(var i = 0; i < dow.length; i++)
    {
    //console.log(dow[i]);
    eval(dow[i]);

    }
}


function doFontSizer(control, accion, targets)
{
    $(control).fontSizer({
        action: accion,
        elements: targets,
        increment: 1,
        max: 30,
        min: 8
    });
}

function doPrintable()
{

    $(function()
        {
        $('.optImpresion').click(function()
        {

            var cont = '';
            $('.printable').each(function(){
               cont = cont + $(this).html();
            });

            $.ajax({
                    url: CONF_URL_APP + '/includes/print.template.php',
                    type:'post',
                    data: {
                            Contenido: cont
                          },
                    cache:false,
                    dataType:'html',
                    success: function(data){
                        var $html = $('<div></div>').append(data);
                        var $printContent = $html;
                        $printContent.print();
                    }
            });
           
        });
    });
}


function doSendToFriendForm(titulo, asunto, textoLink)
{
    $(function()
        {

        $('.optEmail').click(function(){

            $.ajax({
                url: CONF_URL_APP + '/includes/actions.php',
                type:'post',
                data: {
                        'do': 'sendToFriendGetForm',
                        Titulo: titulo,
                        Asunto: asunto,
                        TxtLink: textoLink
                      },
                cache:false,
                dataType:'html',
                success: function(data)
                         {
                            bloquearPantalla(data, true);
                            $('#frmSendToFriend #ToName, #frmSendToFriend #FromName').unbind('blur').blur(function(){
                                $('#suNombre').remove();
                                $('#tuNombre').remove();
                                $('#Asunto').prepend('<span id="suNombre">' + $('#ToName').val() + ', </span><span id="tuNombre">' + $('#FromName').val() + '</span> ');
                            });
                            $('#frmSendToFriend #btnCancelar').unbind('click').click(function(){
                               $.unblockUI();
                            });
                            $('#frmSendToFriend #btnEnviar').unbind('click').click(function(){
                                $('#frmSendToFriend .msgResultado').html('Aguarde un momento por favor...').fadeIn();
                                $.ajax({
                                    url: CONF_URL_APP + '/includes/actions.php',
                                    type:'post',
                                    data: {
                                            'do': 'sendToFriend',
                                            FromEmail: $('#frmSendToFriend #FromEmail').val(),
                                            FromName:$('#frmSendToFriend #FromName').val(),
                                            ToEmail:$('#frmSendToFriend #ToEmail').val(),
                                            ToName:$('#frmSendToFriend #ToName').val(),
                                            Asunto:$('#frmSendToFriend #Asunto').html(),
                                            Mensaje:$('#frmSendToFriend #Mensaje').val(),
                                            TxtLink:$('#frmSendToFriend #TxtLink').html()
                                          },
                                    cache:false,
                                    dataType:'json',
                                    success: function(data)
                                             {
                                                if(data.dow)
                                                    doDow(data.dow);
                                             }
                                });
                            });


                         }
            });

        });

    });
}