var transpose_image_h3_in_slideshows = function()
{
    $('ul.slideshow li').each(function(){
        var h3     = $('h3', this)
        ,   im     = $('img:first', this)
        ,   new_h3 = h3.clone(true)
        ,   new_im = im.clone(true);
        $(this).prepend(new_h3)
               .prepend(new_im)
        ;
        h3.remove();
        im.remove();
    });
};

var advance_slideshow = function( img_context )
{
    var visible_li = $('ul.slideshow li.visible');
    var next_li    = visible_li.next('li');
    var nxt = next_li.length > 0 ? next_li : $('ul.slideshow > li:first');
    visible_li.removeClass('visible').hide();
    $(nxt).addClass('visible').show();
};


var regress_slideshow = function( img_context )
{
    var visible_li = $('ul.slideshow li.visible');
    var next_li    = visible_li.prev('li');
    var nxt = next_li.length > 0 ? next_li : $('ul.slideshow > li:last');
    visible_li.removeClass('visible').hide();
    $(nxt).addClass('visible').show();
};



var insert_slideshow_controls = function()
{
    $('ul.slideshow > li').each(function(){    
        var controls      = $( document.createElement('div') ).attr('class','controls');
        var ul            = $( document.createElement('ul') );
        var first_li      = $( document.createElement('li') );
        var back_arrow    = $( document.createElement('img') ).attr('src','/images/layout/arrow_back.gif');
            back_arrow.attr('id', 'back_arrow');
        var second_li     = $( document.createElement('li') );
        var forward_arrow = $( document.createElement('img') ).attr('src','/images/layout/arrow_forward.gif');
            forward_arrow.attr('id', 'forward_arrow');

        back_arrow.click(function(){
            regress_slideshow(this);
        });
        forward_arrow.click(function(){
            advance_slideshow(this);
        });
        ul
          .append( first_li.append(back_arrow) )
          .append( second_li.append(forward_arrow) )
        ;
        $(this).append( $(controls).append(ul) )
    });
};


var hide_not_visible_slideshow_slides = function()
{
    $('ul.slideshow > li:not(.visible)').hide();
};



$(function(){
    transpose_image_h3_in_slideshows();
    insert_slideshow_controls();
    hide_not_visible_slideshow_slides();
})