var lib_ism = function($) {

    // Private variables
    var eiw_element; // Element id currently displayed in the EIW

    // Private functions
    
    // All DOM operations to be created when page loads
    $(document).ready(function() {
		
        // Make EIW draggable /////////////////////////////////////////////////
        $("#ism_eiw").draggable({ handle: '#ism_eiw_header' });

        // EIW navigation /////////////////////////////////////////////////////
        $('#ism_eiw_nav a').bind('click',function(e) {

            var $clicked_on = $(e.target);
            var height;
            var offset;

            switch($clicked_on.attr('href')) {

                case '#summary':
                    height = $('#ism_eiw_summary').outerHeight(true);
                    offset = 0;
                    break;

                case '#history':
                    height = $('#ism_eiw_history').outerHeight(true);
                    offset = 0 - $('#ism_eiw_summary').outerHeight(true);
                    break;

                case '#fixtures':
                    height = $('#ism_eiw_fixtures').outerHeight(true);
                    offset = 0 - $('#ism_eiw_summary').outerHeight(true)
                    - $('#ism_eiw_history').outerHeight(true)
                    break;

                case '#form':

                    // Populate element drop downs
                    var callback_key = lib_ism.vars.callback_class 
                    + "|json_element_graph_lists_cb"
                    var url = "/M/ajax?" + callback_key + "=" + eiw_element;
                    $.getJSON(url,function(data) {
                        var last_team = '';
                        var options = '';
                        $.each(data,function(i,val) {
                            if (last_team != val.team) {
                                options += '<option class="ism_graph_club">' + val.team + '</option>';
                                last_team = val.team;
                            }
                            options += '<option class="ism_graph_player" value="'+val.id+'">' + val.name + ' . ' + val.points + lib_ism.vars.txt_pts + ' . ' + lib_ism.vars.txt_currency + val.cost + '</option>';
                        });
                        $('#ism_eiw_graph_options select.ism_element_select')
                        .each(function() {
                            $(this).find('option:gt(0)').remove();
                            $(this).append(options);
                            this.selectedIndex = 0;
                        });
                    });

                    // Plot graph
                    $('#ism_graph_plot input').trigger('click');

                    // Show frame
                    height = $('#ism_eiw_form').outerHeight(true);
                    offset = 0 - $('#ism_eiw_summary').outerHeight(true)
                    - $('#ism_eiw_history').outerHeight(true)
                    - $('#ism_eiw_fixtures').outerHeight(true);
                    break;

                default:
                    alert('No handler for ' + $clicked_on.attr('href'));
                    return;

            }

            $('#ism_eiw_nav a.ism_selected').removeClass('ism_selected');
            $clicked_on.addClass('ism_selected');

            $('#ism_eiw_content').animate({height: height+'px'},'slow');
            $('#ism_eiw_content_slider').animate({top: offset},'slow');

            return false;

        });

        // EIW close link /////////////////////////////////////////////////////
        $('#ism_eiw_header_close').bind('click', function(e) {

            $('#ism_eiw').hide();
            return false;

        });

        // EIW history navigator ///////////////////////////////////////////////
        var event_navigating = 0;
        $('#ism_eiw_history_nav a').bind('click',function(e) {

            if (event_navigating == 1) return false;

            var $clicked_on = $(e.target);

            var $table = $('#ism_eiw_history_table');
            var $content = $table.find('tbody.ism_eiw_history_content');
            var show_cols = lib_ism.vars.eiw_history_cols;
            var history_cols = $content
                .eq(0)
                .find('tr:eq(0) td')
                .length;
            var $el_list = $('#ism_eiw_history_event_list div ul');
            var col_width = $('tr#ism_eiw_history_points td:visible:eq(1)')
            .outerWidth(true);
            var left_now = parseFloat($el_list.css('left'));

            // Get second visible column (first is header)
            // Then count all siblings to find out index of <td>
            var first_visible_col  = $content
                .eq(0)
                .find('td:visible:eq(1)')
                .prevAll()
                .length;

            var show_col;
            var hide_col;
           
            switch($clicked_on.attr('href')) {

                case '#next':
                    hide_col = first_visible_col;
                    show_col = first_visible_col + show_cols;
                    if (show_col > (history_cols - 1)) return;
                    left_now -= col_width;
                    break;

                case '#prev':
                    if (first_visible_col <= 1) return;
                    show_col = first_visible_col - 1;
                    hide_col = first_visible_col + show_cols - 1;
                    left_now += col_width;
                    break;

                default:
                    alert('No handler for ' + $clicked_on.attr('href'));
                    return;

            }

            // Add 1 to acount for header col
            show_col++;
            hide_col++;

            $content.fadeTo('fast',0,function() {

                //$content.css('visibility','hidden');
                $content
                    .find('td:nth-child('+hide_col+')')
                    .hide();
                $content
                    .find('td:nth-child('+show_col+')')
                    .show();

            });

            // Scroll event list
            event_navigating = 1;
            $el_list.animate({
                    left: left_now + 'px'
                },
                'normal',
                'swing',
                function() {
                    $content.fadeTo('fast',100);
                    //$content.css('visibility','visible');
                    event_navigating = 0;
                }
            );

            // Do we need to show previous link?
            if ( show_col <= 2) {
                $('#ism_eiw_history_prev').css('visibility','hidden');
            }
            else {
                $('#ism_eiw_history_prev').css('visibility','visible');
            }

            // Do we need to show next link?
            if (show_col >= (history_cols - 1)) {
                $('#ism_eiw_history_next').css('visibility','hidden');
            }
            else {
                $('#ism_eiw_history_next').css('visibility','visible');
            }

            return false;

        });

        // EIW history sections open / close //////////////////////////////////
        var category_animating = 0;
        $('#ism_eiw_history_table')
        .find('tr.ism_eiw_history_category a').bind('click',function(e) {

            if (category_animating == 1) return false;

            // Content
            var $content = $(this)
                .parents('tbody:first')
                .next('tbody.ism_eiw_history_content')
                .eq(0)
            ;
            var content_height = $content.height();
            var current_height = $('#ism_eiw_content').height();

            // Hidden need to grow window and show, else hide
            if ($content.is(':hidden')) {
                $content.show();
                category_animating = 1;
                $('#ism_eiw_content')
                    .animate({height: current_height + content_height + 'px'}
                    ,'normal'
                    ,'swing'
                    ,function() {
                        category_animating = 0;
                    }
                );
                $(this).addClass('ism_open');
            }
            else {
                $('#ism_eiw_content').height(current_height - content_height);
                $content.hide();
                $(this).removeClass('ism_open');
            }

            return false;

        });

        // EIW watchlist functionality ////////////////////////////////////////
        $('#ism_eiw_wl form').bind("click",function(){
            $('#ism_eiw_wl').children().hide();
            $('#ism_wl_loader').show();
            var $this = $(this);
            var $hidden = $this.children('[type="hidden"]').eq(0);
            var params = {};
            params[$hidden.attr('name')] = eiw_element;
            $.post("/M/ajax", params, function(data) {
                $('#ism_wl_loader').hide();
                // Put submit buttons back which have been hidden by ism_submit!
                $('#ism_eiw_wl .ism_submit').css('visibility','visible');
                if ($this.attr('id') == 'ism_wl_add') {
                    lib_ism.vars.wl.push(eiw_element);
                    $('#ism_wl_where').show();
                }
                else if ($this.attr('id') == 'ism_wl_del') {
                    $.each(lib_ism.vars.wl,function(i,val) {
                        if (val == eiw_element) {
                            lib_ism.vars.wl.splice(i,1);
                            return false;
                        }
                    });
                    $('#ism_wl_add').show(); 
                }
                wl = lib_ism.vars.wl; // Legacy
                // If viewing WL reload
                if ($('#ism_element_filter').val() == 'watchlist') {
                    get_element_data();
                 }
            });
            return false;
        });

        // EIW plot graph
        $('#ism_graph_plot input').bind('click',function(){

            var graphdata = $('#ism_graphdata').val();
            var cumulative = $('#ism_cumulative').attr('checked') ? 1 : 0;
            var els = eiw_element;
            $('#ism_eiw_graph_options select.ism_element_select')
            .each(function() {
                if (parseInt($(this).val())) {
                    els += ( "," + $(this).val() );
                }
            });
            $('#ism_eiw_graph_wrapper').load('/M/element_graph_flash.mc?els='+els+'&graphdata='+graphdata+'&cumulative='+cumulative);

            $(this).css('visibility','visible');
            return false;

        });
      

        // Change ism_thickbox links to pages that don't use autohandler //////
        $('a.ism_thickbox').each(function() {
            var $this = $(this);
            var href = $this.attr('href');
            if (href.match(/(rules|help)\.mc/)) {
                href = href.replace(/(rules|help)\.mc/,"tb_$1.mc");
            }

            // Add height and width parameters
            //if (href.match(/\.mc$/)) {
                //href += '?';
            //}
            //else {
                //href += '&';
            //}
            //href += "width=700&height=450";
            $this.attr('href',href);

        });

        // PNG fixes //////////////////////////////////////////////////////////
        if (typeof($.ifixpng) != 'undefined') {
            $.ifixpng('/images/shared/pixel_iepng.gif');
            $('#ism').find('img[src$=".png"]').ifixpng();
        }

        // IE6 select fixes
        if (typeof($.fn.bgiframe) != 'undefined') {
            $("#ism_eiw").bgiframe();
        }

        // Cluetip help
        $('.ism_cluetip_help').cluetip({
        	cluetipClass: 'ism',
    		width: '160px',
    		height: 'auto',
        	showTitle: true,
        	arrows: true,
        	splitTitle: '|',
        	dropShadow: 'false',
        	onShow: function() {
                if (typeof($.ifixpng) != 'undefined') {
                    // Should also do inner and outer but doesn't work"
                    $('#cluetip-arrows').ifixpng();
                }
            }
        });

        // Open the profile window
        $('.ism_view_profile').bind('click',function() {
            var regexp = /#(\d+)/;
            var r_id = regexp.exec(this.href);
            draw_element_view(r_id[1]);
            return false;
        });

        // Draw shirt
        if (lib_ism.vars.colour_shirt) {

            $('div.ism_the_shirt')
                .css({'background-color' : lib_ism.vars.colour_shirt});
            if (lib_ism.vars.colour_stripes) {    
                $('li.ism_colorwell_stripe')
                    .css({'background-color' : lib_ism.vars.colour_stripes});
                $('#ism_hoops').hide();
            }
            else if (lib_ism.vars.colour_hoops) {
                $('li.ism_colorwell_hoop')
                    .css({'background-color' : lib_ism.vars.colour_hoops});
                $('#ism_stripes').hide();
            }
            else {
                $('#ism_stripes').hide();
                $('#ism_hoops').hide();
            }

            $('li.ism_colorwell_sleeve')
                .css({'background-color' : lib_ism.vars.colour_sleeve});
            $('div.ism_shorts')
                .css({'background-color' : lib_ism.vars.colour_shorts});
            $('div.ism_socks')
                .css({'background-color' : lib_ism.vars.colour_socks});

            if (lib_ism.vars.colour_socks_stripes) {
                $('li.ism_colorwell_sock')
                .css({'background-color' : lib_ism.vars.colour_socks_stripes});
            }
            else {
                $('#ism_socks_stripes_list').hide();
            }

        }

        // Click on a PC tab
        $('#ism_pc_tabs a').bind('click',function() {
            var $this = $(this);
            $this.parent().siblings('li').removeClass('ism_active_tab');
            $this.parent().addClass('ism_active_tab');
            if (this.id == 'ism_tab_graphical') {
                $('#ism_pc_wrapper').removeClass('ism_stats_view_active')
                    .addClass('ism_graphical_view_active');
                $('#ism_pitch_grid').fadeIn('slow');
                $('#ism_data_view').hide();
            }
            else if (this.id == 'ism_tab_data') {
                $('#ism_pc_wrapper').removeClass('ism_graphical_view_active')
                    .addClass('ism_stats_view_active');
                $('#ism_pitch_grid').hide();
                $('#ism_data_view').fadeIn('slow');
            }
            return false;
        });

        // Scoreboard help
        $('a#ism_title_help').bind('click',function() {
            var help = $('#ism_title_help_section').height();
            var height = $('#ism_title_help_wrapper').height();
            if(help == 0) {
                $('#ism_title_help_section').animate({height: height + 10});
            } else {
                $('#ism_title_help_section').animate({height: '0'});
            }
            return false;
        });

        // Links that need confirming
        $('.ism_confirm_submit').bind('click',function() {
            var $this = $(this);
            if ($this.attr('title')){
                if(!confirm($this.attr('title'))) {
                    return false;
                }
            }
        });

        // Hide non js filter submit button
        $('#ism_filter_submit').hide();

        // Filter changes
        $('#ism_element_filter').unbind().bind('change',function(){
            $('#ism_pricerange_filter').val('');
            $('#ism_filters').trigger('submit');
        });
        $('#ism_stat_filter').unbind().bind('change',function(){
            $('#ism_filters').trigger('submit');
        });
        $('#ism_pricerange_filter').unbind().bind('change',function(){
            $('#ism_filters').trigger('submit');
        });

        // Drop downs with URL's as values
        $('select.ism_load_url_value').bind('change',function() {
            window.location.href=this.options[this.selectedIndex].value
        });



    });


    // Public variables and functions
    return {

        // Public variables, accessed via lib_ism.vars
 
        vars : {
            badge_dir: undefined, // Badge directory
            badge_ext: undefined, // Badge extension
            callback_class: undefined, // Callback class
            colour_shirt : undefined,
            colour_stripes : undefined,
            colour_hoops : undefined,
            colour_sleeve : undefined,
            colour_shorts : undefined,
            colour_socks : undefined,
            colour_socks_stripes : undefined,
            eiw_history_cols: undefined, // Number of history cols in window
            forum_characters: undefined, // Amount of forum characters available
            game_code: undefined, // game->code
            game_stats: [], // Game specific stats
            icon_dir : undefined, // Icon directory
            icon_ext : undefined, // Icon extension
            live: undefined, // Is game live?
            no_home_away: undefined, // Don't show Home / Away status
            regular_season_ends : undefined, // Last Event for txt_no_game
            shirt_dir : undefined, // Shirt directory
            shirt_ext : undefined, // Shirt extension
            show_full_name: 0, // Full name shown in element window?
            summary_last_games: undefined, // Shown in element window
            summary_upcoming_games: undefined, // Shown in element window
            txt_away : '', // Text to represent away team
            txt_currency : '', // Text to represent currency
            txt_home : '', // Text to represent home team
            txt_no_game: '', // Text to be used when no fixture
            txt_pts : '', // Text to represent points
            txt_unlimited: '', // Text for unlimited transfers
            wl: [], // Watch list
            wl_max : undefined // Maximum in watch list
        },


        // Public functions

        // Populate the EIW
        draw_element_view : function(id) {

            eiw_element = id;

            // Blank header data
            $('#ism_eiw_header_name').html('');
            $('#ism_eiw_header_team').html(''); 
            $('#ism_eiw_header_cost_value').html('');
            $('#ism_eiw_nav a.ism_selected').removeClass('ism_selected');
            $('#ism_eiw_wl').children().hide();

            // Show the window with loader
            var $loader = $('#ism_eiw_loader');
            $('#ism_eiw').vCenter();
            $('#ism_eiw').show();
            $loader.show();
            $('#ism_eiw_content').height($loader.height());
            $('#ism_eiw_content_slider').css('top',0);

            // Remove old history data
            $('table#ism_eiw_history_table col:not(#ism_col_header):not(#ism_col_total)').remove();
            $('table#ism_eiw_history_table td:not(.ism_header_col):not(.ism_total_col)').remove();
            $('table#ism_eiw_history_table a').removeClass('ism_open');

            // Construct the URL
            var callback_key = lib_ism.vars.callback_class + '|json_element_cb';
            var url = '/M/ajax?' + callback_key + '=' + id;

            $.getJSON(url,
                function(data) {

                    // Player name
                    $('#ism_eiw_header_name').html(data.first_name == '' || lib_ism.vars.show_full_name == 0 ? data.web_name : data.first_name + ' ' + data.second_name);

                    // Team name
                    $('#ism_eiw_header_team').html(data.team_name); 

                    // Cost
                    $('#ism_eiw_header_cost_value') 
                        .html(lib_ism.vars.txt_currency + data.now_cost);

                    // Image
                    $('#ism_eiw_summary_image')
                        .empty()
                        .append(lib_ism.element_image(data))
                    ;

                    // Position
                    $('#ism_eiw_summary_position').html(data.type_name);

                    // Selected by
                    $('#ism_eiw_summary_selected').html(data.selected_by);

                    // Next opponent
                    $('#ism_eiw_summary_next_opp').html(data.next_fixture);

                    // Total points
                    $('#ism_eiw_summary_total').html(data.total);

                    // News
                    $('#ism_eiw_summary_news').html(data.news);

                    // Event explain
                    if (data.fixture_history.length) {
                        $('#ism_this_event_points').html(data.event_total);
                        var $this_event_tbody = 
                            $('#ism_eiw_summary_this_event table tbody'); 
                        $this_event_tbody.empty();
                        $.each(data.event_explain, function(i,val) {
                            var points = val[2] == null ? 0 : val[2];
                            $this_event_tbody.append("<tr><td>"+val[0]+"</td><td>"+val[1]+"</td><td>"+points+"</td></tr>");
                        });
                        $('#ism_eiw_summary_this_event').show();
                    }
                    else {
                        $('#ism_eiw_summary_this_event').hide();
                    }

                    // Last games
                    if (data.fixture_history.length) {
                        var number_of_games = data.fixture_history.length;
                        if (number_of_games
                        > lib_ism.vars.summary_last_games) {
                            number_of_games = 
                            lib_ism.vars.summary_last_games;
                        }
                        var $last_games_tbody = 
                        $('#ism_eiw_summary_last_fixtures table tbody');
                        $last_games_tbody.empty();

                        // We loop through twice as need to know range for graph
                        var fixture_history_length = data.fixture_history.length;
                        var max_value = 0;
                        var min_value = 0;
                        var game_count = 1;
                        for (var i = (fixture_history_length - 1); i>0; i--) {
                            var el_data = data.fixture_history[i-1];
                            var total = parseInt(el_data[(el_data.length - 1)]);
                            if (total > max_value)  max_value = total;
                            if (total < min_value)  min_value = total;
                            game_count++;
                            if (game_count >= lib_ism.vars.summary_last_games) {
                                break;
                            }
                        }
                        var range = max_value - min_value;
                        game_count = 1;
                        for (var i = (fixture_history_length - 1); i>0; i--) {
                            var el_data = data.fixture_history[i-1];
                            var total = parseInt(el_data[(el_data.length - 1)]);
                            var width;
                            if (total == min_value) {
                                width = 1;
                            }
                            else {
                                width = parseInt(75 * ( (total + Math.abs(min_value)) / range));
                            }
                            if(el_data[2] == '-' && lib_ism.vars.txt_no_game) {
                                $last_games_tbody.prepend('<tr><td>'+el_data[1]+'</td><td class="ism_slf_data">'+lib_ism.vars.txt_no_game+'</td></tr>');
                            }
                            else {
                                $last_games_tbody.prepend('<tr><td>'+el_data[1]+'</td><td class="ism_slf_data"><div class="ism_float_left ism_slf_chart" style="width: '+width+'%"></div><div class="ism_float_left">'+total+'</div><div class="ism_clear"></div></td></tr>');
                            }
                            game_count++;
                            if (game_count >= lib_ism.vars.summary_last_games) {
                                break;
                            }
                            $('#ism_eiw_summary_last_fixtures').show();
                        }
                    }
                    else {
                        $('#ism_eiw_summary_last_fixtures').hide();
                    }

                    // Upcoming games
                    var number_of_fixtures = data.fixtures.length;
                    if (number_of_fixtures 
                    > lib_ism.vars.summary_upcoming_games) {
                        number_of_fixtures = 
                        lib_ism.vars.summary_upcoming_games;
                    }

                    var $tbody = 
                    $('#ism_eiw_summary_upcoming_fixtures table tbody');
                    $tbody.empty();

                    for (var i = 0; i < number_of_fixtures; i++) {

                        var opponent = data.fixtures[i][2];
                        if (!lib_ism.vars.no_home_away && opponent) {
                            opponent += " ";
                            opponent += data.fixtures[i][3] 
                            ? lib_ism.vars.txt_away : lib_ism.vars.txt_home;
                        }
                        else if (opponent == '' && data.fixtures[i][4] 
                        <= lib_ism.vars.regular_season_ends) {
                            opponent = lib_ism.vars.txt_no_game;
                        }

                        $tbody.append("<tr><td>"+data.fixtures[i][4]
                        +"</td><td>"+opponent+"</td><td>"+data.fixtures[i][0]
                        +"</td></tr>");
                    }

                    // History
                    var history_cols = 1;
                    var show_cols = lib_ism.vars.eiw_history_cols;

                    // List to navigate events
                    var $event_list = $('<ul>');

                    var $table = $('table#ism_eiw_history_table');

                    // We'll build HTML strings up as is much faster than
                    // inserting small items in DOM
                    var table_data = [];
                    table_data['col'] = ''; 
                    table_data['event'] = ''; 
                    table_data['date'] = ''; 
                    table_data['opponent'] = '';
                    var data_cols = ['results','transfers','values','points'];
                    $.each(data_cols.concat(lib_ism.vars.game_stats),
                    function(i,val) {
                        table_data[val] = '';    
                    });

                    // How wide should each col be?
                    var col_width = ( ( $('#ism_eiw_history_table').outerWidth(true) - $('tr#ism_eiw_history_dates td.ism_header_col').outerWidth(true) ) / (show_cols + 1) );

                    // Write all the cols we need
                    for (var i = 1; i<= show_cols; i++) {
                        table_data['col'] += 
                        '<col id="ism_col_'+i+'"/>';
                    }
                    
                    // Season history
                    $.each(data.season_history,function(i, val) {

                        // Event
                        table_data['event'] +=
                        '<li class="ism_float_left">'+val.shift()+'</li>';

                        // Date, Opponent, Results, Transfers
                        table_data['date'] += ('<td>&nbsp;</td>');
                        table_data['opponent'] += ('<td>&nbsp;</td>');
                        table_data['results'] += ('<td>&nbsp;</td>');
                        table_data['transfers'] += ('<td>&nbsp;</td>');

                        $.each(lib_ism.vars.game_stats,function(i2,val2) {
                            table_data[val2] += '<td>'+val.shift()+'</td>';
                        });

                        table_data['values'] += '<td>'+val.shift()+'</td>';
                        table_data['points'] += '<td>'+val.shift()+'</td>';

                        history_cols++;

                    });

                    // Current game history
                    $.each(data.fixture_history,function(i,val) {
   
                        if ( i == ( fixture_history_length - 1) ) {
                            // Totals
                            $('#ism_eiw_history_points td.ism_total_col')
                                .html(val.pop());
                            // Game stats 
                            $.each(lib_ism.vars.game_stats,function(i2,val2) {
                                $('#ism_eiw_history_'+val2+' td.ism_total_col')
                                .html(val[i2+3]);
                            });
                            return false;
                        } 

                        table_data['date'] += ('<td>'+val.shift()+'</td>');

                        table_data['event'] +=
                        '<li class="ism_float_left">'+val.shift()+'</li>';

                        var fix_info = val.shift().split(' ');
                        if (fix_info[0] == '-') {
                            table_data['opponent'] += 
                            '<td>'+lib_ism.vars.txt_no_game+'</td>';
                            table_data['results'] += '<td>-</td>';
                        }
                        else {
                            table_data['opponent'] += 
                            '<td>'+fix_info[0]+'</td>';
                            table_data['results'] += '<td>'+fix_info[1]+'</td>';
                        }

                        table_data['points'] += '<td>'+val.pop()+'</td>';
                        table_data['values'] += '<td>'+val.pop()+'</td>';
                        table_data['transfers'] += '<td>'+val.pop()+'</td>';

                        $.each(lib_ism.vars.game_stats,function(i2,val2) {
                            table_data[val2] += '<td>'+val.shift()+'</td>';
                        });

                        history_cols++;

                    });
                    var cols_with_data = history_cols - 1;

                    // Class names for fixture columns
                    var fix_table_class_names = new Array;
                    $('table#ism_eiw_fixtures_table thead th')
                    .each(function(i) {
                        fix_table_class_names.push(this.className);
                    });


                    var fix_rows = '';
                    // Results
                    $.each(data.results,function(i, val) {
                        // Opponent
                        var opponent = val[2];
                        if (!lib_ism.vars.no_home_away && opponent) {
                            opponent += " ";
                            opponent += val[3] 
                            ? lib_ism.vars.txt_away : lib_ism.vars.txt_home;
                        }
                        else if (opponent == '') {
                            opponent = lib_ism.vars.txt_no_game;
                        }
                        fix_rows += 
                            '<tr><td class="' +
                            fix_table_class_names[0] +
                            '">'+val[0] +
                            '</td><td class="' +
                            fix_table_class_names[1] +
                            '">';
                        if (val[2] != '') {
                            if (lib_ism.vars.shirt_dir 
                            && lib_ism.vars.shirt_ext) {
                                fix_rows +=
                                    '<img src="'+lib_ism.vars.shirt_dir+
                                    '/data_view/shirt_' + 
                                    val[1] + 
                                    '.'+lib_ism.vars.shirt_ext+'"/>';
                            }
                            else {
                                fix_rows +=
                                    '<img src="/images/' +
                                    lib_ism.vars.game_code +
                                    '/shirts/stats_view/shirt_' + 
                                    val[1] + 
                                    '.png"/>';
                            }
                        }
                        fix_rows +=
                            opponent +
                            '</td><td class="' +
                            fix_table_class_names[2] + 
                            '">' +
                            val[4] + 
                            '</td></tr>';
                    }); 

                    // Fixtures
                    $.each(data.fixtures,function(i, val) {

                        // Event number
                        table_data['event'] +=
                        '<li class="ism_float_left">'+val[4]+'</li>';

                        // Date
                        table_data['date'] += ('<td>'+val[0]+'</td>');

                        // Opponent
                        var opponent = data.fixtures[i][5];
                        var opponent_long = data.fixtures[i][2];
                        if (!lib_ism.vars.no_home_away && opponent) {
                            opponent += " ";
                            opponent_long += " ";
                            opponent += data.fixtures[i][3] 
                            ? lib_ism.vars.txt_away : lib_ism.vars.txt_home;
                            opponent_long += data.fixtures[i][3] 
                            ? lib_ism.vars.txt_away : lib_ism.vars.txt_home;
                        }
                        else if (opponent == '' && data.fixtures[i][4] 
                        <= lib_ism.vars.regular_season_ends) {
                            opponent = lib_ism.vars.txt_no_game;
                            opponent_long = lib_ism.vars.txt_no_game;
                        }
                        table_data['opponent'] += ('<td>'+opponent+'</td>');

                        // Blank out the rest
                        $.each(data_cols.concat(lib_ism.vars.game_stats),
                        function(i,val) {
                            table_data[val] += '<td>&nbsp;</td>';
                        });

                        history_cols++;

                        fix_rows += 
                            '<tr><td class="' +
                            fix_table_class_names[0] +
                            '">'+val[4] +
                            '</td><td class="' +
                            fix_table_class_names[1] +
                            '">';
                        if (val[6] != '') {
                            if (lib_ism.vars.shirt_dir 
                            && lib_ism.vars.shirt_ext) {
                                fix_rows +=
                                    '<img src="'+lib_ism.vars.shirt_dir+
                                    '/data_view/shirt_' + 
                                    val[6] + 
                                    '.'+lib_ism.vars.shirt_ext+'"/>';
                            }
                            else {
                                fix_rows +=
                                    '<img src="/images/' +
                                    lib_ism.vars.game_code +
                                    '/shirts/stats_view/shirt_' + 
                                    val[6] + 
                                    '.png"/>';
                            }
                        }
                        fix_rows +=
                            opponent_long +
                            '</td><td class="' +
                            fix_table_class_names[2] + 
                            '">' +
                            val[0] + 
                            '</td></tr>';
                    });


                    // Insert table_data
                    $table.find('col#ism_col_total').before(table_data['col']);

                    // Set width of cols
                    $table.find('col:not(#ism_col_header)')
                        .width(col_width);

                    $event_list.append(table_data['event']);

                    $('tr#ism_eiw_history_dates td.ism_total_col')
                        .before(table_data['date']);

                    $('tr#ism_eiw_history_opponents td.ism_total_col')
                        .before(table_data['opponent']);

                    $.each(data_cols.concat(lib_ism.vars.game_stats),
                    function(i,val) {
                        $('tr#ism_eiw_history_'+val+' td.ism_total_col')
                            .before(table_data[val]);
                    });
                   
                    // Append a clearing li to the navigation_list
                    $('<li/>')
                        .addClass('ism_clear')
                        .appendTo($event_list)
                    ;

                    // Hide columns
                    var hide_cols = cols_with_data - show_cols; // First cols
                    if (hide_cols < 0) hide_cols = 0;
                    var col_start = show_cols + 2; // Last cols 
                    if (hide_cols > 0) {
                        for (var i=1; i <= hide_cols; i++) {
                            $table.find('td:not(.ism_total_col):nth-child('+(i+1)+')').hide();
                            col_start++;
                        }
                    }
                    for (var i = col_start; i <= history_cols; i++) {
                        $table.find('td:nth-child('+i+')').hide();
                    }

                    // Set widths for li based on first column
                    $event_list.find('li').width(col_width); 
                    if (hide_cols > 0) {
                        $event_list.css(
                            'left', (col_width * hide_cols * -1) + 'px'
                        );
                    }

                    // Create the td we need to insert the list in
                    var $td = $('<td/>')
                        .attr('colSpan',show_cols)
                        .append('<div/>')
                        .insertBefore('tr#ism_eiw_history_event_list td.ism_total_col')
                    ;

                    // Now set height and width of div and add the event list
                    $td 
                        .find('div')
                        .width(col_width * show_cols)
                        .height($td.height())
                        .append($event_list)

                    ;

                    // Do we need to show previous link?
                    if (hide_cols > 0) {
                        $('#ism_eiw_history_prev').css('visibility','visible');
                    }
                    else {
                        $('#ism_eiw_history_prev').css('visibility','hidden');
                    }

                    // Do we need to show next link?
                    if (hide_cols + show_cols >= (history_cols - 1)) {
                        $('#ism_eiw_history_next').css('visibility','hidden');
                    }
                    else {
                        $('#ism_eiw_history_next').css('visibility','visible');
                    }

                    // Hide categories
                    $table
                        .find('tr.ism_eiw_history_category a')
                        .each(function(){
                            $(this).parents('tbody:first')
                            .next('tbody.ism_eiw_history_content')
                            .hide()
                            ;
                        });
                    ;

                    // Populate fixtures table
                    $('table#ism_eiw_fixtures_table tbody')
                        .empty()
                        .append(fix_rows)
                    ;
                    
                    // Prepare Watch List functionality
                    var found = 0;
                    $.each(lib_ism.vars.wl,function(i,val) {
                        if (eiw_element == val) {
                            found = 1;
                            return false;
                        } 
                    });

                    if (found) {
                        $('#ism_wl_del').show();
                    }
                    else {
                        // Maximum
                        if (lib_ism.vars.wl.length >= lib_ism.vars.wl_max) {
                            $('#ism_wl_limit').show();
                        }
                        else {
                            $('#ism_wl_add').show();
                        }
                    }

                    // Fix any pngs in ie6
                    // Commented out for now as ignores css sizing
                    //if (typeof($.ifixpng) != 'undefined') {
                        //$('#ism_eiw').find('img[src$=".png"]').ifixpng();
                    //}
      
                    // Hide the loader and show the summary
                    $loader.hide();
                    $('#ism_eiw_nav a:first').trigger('click');

                }

            );

     
        },

        // Which image to show - can easily be replaced by redeclaring
        // Must return a jQuery image object
        element_image : function(data) {
            if (lib_ism.vars.shirt_dir && lib_ism.vars.shirt_ext) {
                var $img = 
                    $('<img>')
                    .attr('src',lib_ism.vars.shirt_dir+
                    '/profile/shirt_'+data.team_id+'.'+lib_ism.vars.shirt_ext)
                ;
                return $img;
            }
            else {
                var $img = 
                    $('<img>')
                    .attr('src','/images/'+lib_ism.vars.game_code+
                    '/shirts/profile/shirt_'+data.team_id+'.png')
                ;
                return $img;
            }
        }

    };


}(jQuery);

// vCenter - positions elements 20 px below #ism or top of window
(function($){
    $.fn.vCenter = function(options) {
        var window_top = 20;
        var ism_top = $('#ism').offset().top;
        var scroll_top = $(document).scrollTop();
        window_top += scroll_top > ism_top ? scroll_top : ism_top;
        return this.each(function(index) {
            if (index == 0) {
                var $this = $(this);
                $this.css({
                    position: 'absolute',
                    marginTop: '0',
                    top: window_top
                });
            }
        });
    };
})(jQuery);

// Backwards compatability
function draw_element_view(id) { lib_ism.draw_element_view(id); }
var wl = new Array;
var live = lib_ism.vars.live;
var ism_stats_view_class = 'ism_stats_view_active';
var ism_graphical_view_class = 'ism_data_view_active';
