

// ***  Setting-up automatic ajax content loading  *** //
function ajax_loader_exec (obj, event)
{
    event.preventDefault();

    var O = $(obj);

    var functions = O.attr('rel') ? O.attr('rel').split('|') : new Array ();
    var validator = (functions  &&  (functions.length >= 1)) ? functions [0] : false;
    var callback = (functions  &&  (functions.length >= 2)) ? functions [1] : false;

    var follow = true;
    if (validator) eval ('follow = ' + validator + ' (obj);');

    if (follow)
    {
        var exec_target = O.attr('target');
        var exec_params = (obj.tagName == 'FORM') ? O.serializeArray() : {};
        var exec_url = (obj.tagName == 'FORM') ? O.attr('action') : O.attr('href');

        exec_params.r = Math.random();  // Preventing IE caching
        exec_url = exec_url.replace ('.html', '.ajax');  // Telling to core

        $(exec_target).children().filter(':visible').fadeTo(0, 0.4);
        $(exec_target).load(exec_url, exec_params, function(){

            ajax_loader (exec_target);
            if (callback) eval (callback + ' ();');

        });
    }
    return false;
}

function ajax_loader (raiz)
{
    var R = $( raiz ? raiz : document );
    R.find('.ajax_loader').each(function(){

        $(this).removeClass('ajax_loader');
        if (this.tagName == 'FORM')
        {
            $(this).submit(function(e){  return ajax_loader_exec (this, e);  });
        }
        else  // tagName IN { 'A', 'LI' }
        {
            $(this).click(function(e){  return ajax_loader_exec (this, e);  });
        }
    });
}


// ***  Managing home news carousel  *** //

var carousel_timer = null;
var carousel_position = 0;

function carousel_update (position)
{
    if (!isNaN (position))
    {
        clearTimeout (carousel_timer);

        var news_list = $('ul.news_carousel li.news');

        if (position >= news_list.length) position = 0;
        if (position < 0) position = news_list.length - 1;

        var block_1 = Math.floor (carousel_position / 11);
        var block_2 = Math.floor (position / 11);
        if (block_1 != block_2)
        {
            var block_position = - (block_2 * (54 * 11));
            $('div.news_carousel div.news_pager ul').animate({  left: block_position + 'px'  }, 1000);
        }

        news_list.hide().eq(position).fadeIn(500);
        carousel_position = position;
    }
    $('div.news_carousel div.news_pager li').removeClass('active').eq(carousel_position).addClass('active');
    carousel_timer = setTimeout ('carousel_update (' + (carousel_position + 1) + ');', 15000);
}


// ***  Managing tabs (news gallery, video detail, etc  *** //

function tabs_activation (root)
{
    $(root).find('a').each(function(){

        if ($(this).hasClass('selected')) $($(this).attr('href')).show();
        else $($(this).attr('href')).hide();

    }).not('.disabled').click(function(){

        var ancestor = $(this).parent().parent();
        var tab_active = ancestor.attr('rel');
        if (tab_active)
        {
            $(tab_active).hide();
            ancestor.find('a[href=' + tab_active + ']').removeClass('selected');
        }
        tab_active = $(this).addClass('selected').attr('href');
        if (tab_active) $(tab_active).show();
        ancestor.attr('rel',tab_active);
        return false;

    }).filter('.selected').click();
}


// ***  Function to load SWF objects, players and animations  *** //

function load_swf (where, what)
{
    var swf_box = $(where);

    var swf_path = what;
    var swf_width = parseInt (swf_box.css('width'), 10);
    var swf_height = parseInt (swf_box.css('height'), 10);
    if (!swf_path  ||  !swf_width  ||  !swf_height) return;

    var swf_id = swf_box.attr ('id');
    if (!swf_id)
    {
        swf_id = 'tmp_' + Math.random ();
        swf_id = swf_id.replace ('.', '_');
        swf_box.attr ('id', swf_id);
    }
    swf_id += '__swf';

    var swf_play = 'true';
    if (!swf_box.find('#' + swf_id).length)
    {
        var swf_wrap = '<div style="width: ' + swf_width + 'px; height: ' + swf_height + 'px;" id="' + swf_id + '"></div>';
        swf_box.append(swf_wrap);
        swf_play = 'false';
    }

    var swf_parameters =
    {
        allowscriptaccess: 'always',
        allowfullscreen: 'true',
        autoplay: 'true',
        quality: 'high',
        wmode: 'transparent'
    };
    swfobject.embedSWF ( swf_path, swf_id, swf_width, swf_height, '9.0.115', '/player/expressInstall.swf', { autoPlay: swf_play }, swf_parameters, {} );
}


// ***  Opening and closing cover layout  *** //

function open_carpet ()
{
    $(document.body).append('<div id="carpet"></div>');
    $('#carpet').click(function(){  close_carpet ();  });
}

function close_carpet ()
{
    $('#carpet').remove();
}

// ***  Football live commentary  *** //

function football_setup ()
{
    $('.news_directo .actualizar a').click(function(){  football_reloader ();  return false;  });
}

function football_reloader ()
{
    var div_formation = $('.news_directo .formacion');
    div_formation.load(div_formation.attr('rel'), {  r: Math.random()  }, function(){  football_setup ();  });

    var div_timeline = $('.news_directo .directo');
    div_timeline.load(div_timeline.attr('rel'), {  r: Math.random()  }, function(){  football_setup ();  });
}


// ***  Setting up comments box  *** //
function comments_setup ()
{
    tabs_activation ('#comments_tabs');  // Activating tabs in comments area
    $('textarea#com_texto').keyup(function(){  $('#charCount span').html(500 - this.value.length);  });  // Count comment's chars
    $('input#com_reset').click(function(){  $('a[name=list_comment]').click();  });  // Reset comments form
    $('img#img_captcha').click(function(){  var d = new Date ();  this.src = '/vendors/math_captcha/image.php?r=' + d.getTime ();  $('#com_captcha').focus();  }).click();  // Captcha reloader
    $('a.comments_add').click(function(){  $('a[name=add_comment]').click();  });  // Add a comment
    $('span.comment_quote a').click(function(){  // Quote a comment

        $('a[name=add_comment]').click();
        $('input#com_titulo').val('A: ' + $(this).parent().parent().find('span.comments_who').html());

    });
    $('div#comments_error').click(function(){  $(this).fadeOut('fast');  });
}

function comments_validator (obj_form)
{
    var com_error = false;
    for (i = obj_form.elements.length; i > 0; -- i)
    {
        com_el = obj_form.elements [i - 1];
        if (com_el.type != 'text'  &&  com_el.type != 'textarea') continue;
        if (com_el.value == '') com_error = com_el.id;
    }
    if (com_error)
    {
        alert ('Rellenar todos los campos, por favor.');
        $('#' + com_error).focus();
        return false;
    }
    else
    {
        if (!window.confirm ('\u00BF Confirmas el env\u00EDo del comentario ?')) return false;
    }
    return true;
}


// ***  Main javascript, run on page ready  *** //

$(document).ready(function(){

    // ***  Opening photo gallery  *** //
    $('a.load_gallery').removeClass('load_gallery').click(function(){

        open_carpet ();
        var auto_load = $(this).attr('rel');
        $('#carpet').load($(this).attr('href'), null, function(){

            $('#gallery_wrapper').click(function(e){  e.stopPropagation();  });
            $('#gallery_closer').click(function(){  close_carpet ();  });

            ajax_loader ('#carpet');
            $('#gallery_images a').click(function(){  $('#gallery_images a.selected').removeClass('selected');  $(this).addClass('selected');  });

            if (auto_load) $('#carpet #thumb_' + auto_load).click();
            else $('#gallery_images a').eq(0).click();

        });
        return false;

    });

    // ***  Activating news carousel  *** //
    $('div.news_carousel div.news_pager li').each(function(i){  $(this).click(function(){  carousel_update (i);  });  });
    $('div.news_carousel div.news_pager div.arrow_left').click(function(){  carousel_update (carousel_position - 1);  });
    $('div.news_carousel div.news_pager div.arrow_right').click(function(){  carousel_update (carousel_position + 1);  });

    carousel_update ();

    // ***  Animates vertical boundary  *** //
    $('td#col_boundary').click(function(){

        $('td#col_lateral').toggle();
        $('table#cols').toggleClass('full_width');

    });

    // ***  Activating tabs in news gallery  *** //
    tabs_activation ('.news_gallery_subtitle');

    // ***  Activating tabs in video detail  *** //
    tabs_activation ('#video_tabs_header');

    // ***  Setup comments box  *** //
    comments_setup ();

    // ***  Auto-loading of SWF objects, players and animations  *** //
    $('.load_swf').removeClass('load_swf').each(function(){  load_swf (this, $(this).attr('rel'));  });

    // ***  Animates lateral mini player  *** //
    $('div.mini_player').each(function(){

        $(this).find('div.mini_player_gallery a').click(function(){

            var video_box = $(this).parent().parent();
            video_box.find('div.mini_player_lateral').css('backgroundImage','url(' + $(this).find('img').attr('src') + ')');

            var video_rel = $(this).attr('rel').split('||');
            var video_title = $(this).attr('title').split(' -- ');

            video_box.find('div.mini_player_date').html(video_rel [1]);
            video_box.find('div.mini_player_title').html(video_title [1]);
            video_box.find('div.mini_player_headline').html(video_title [0]);

            load_swf (video_box.find('div.mini_player_lateral').get(0), '/video_' + video_rel [0] + '/medium.swf');

        }).eq(0).click();

    });

    // ***  Adjusting news gallery on 2 columns, due to IE lack  *** //
    $('ul.news_container_2cols li.news:even').addClass('news_even');
    $('ul.news_container_2cols li.news:odd').addClass('news_odd');

    // ***  Zoom for lateral flash elements  *** //
    $('.lateral_zoom a').click(function(){

        open_carpet ();
        $('#carpet').load('/banner/iframe/' + $(this).parent().attr('rel') + '.html', null, function(){

            $('.carpet_closer a').click(function(){  carpet_close ();  });

        });
        return false;

    });

    // ***  Activating ajax loaders  *** //
    ajax_loader ();

    // ***  Football live commentary  *** //
    if ($('.news_directo').length)
    {
        football_setup ();  // Setup "Actualizar" button
        setInterval ('football_reloader ();', 20000);  // Each 20 seconds
    }

    // News print pop-up
    $('a.news_print').click(function(){

        window.open (this.href, null, 'directories=0, resizable=0, scrollbars=1, status=0, menubar=0, toolbar=0, top=150, left=150, width=700, height=550');
        return false;

    });

});

