var ISMFG = function($) {

    // All DOM operations to be created when page loads
    $(document).ready(function() {

        // Clear input box values
        $('input.ism_clear_focus').bind("focus",function() {
            if (this.name == 'password' && this.value != "password") {
                return;
            }
            else {
                this.value = '';
            }
        });

        // Open the help window
        $('#ism_help_nav_window').unbind().bind('click', function() {
            $('.ism_window_wrapper').hide(); // All windows
            window_problem_elements('hidden');                
            $('#ism_help_window').vCenter();
            $('#ism_help_window').show();
            var height = $('#ism_help_window .ism_window_slide').height();
            $('#ism_help_window .ism_window_content').animate(
                {height: height}, 'slow'
            );
            return false;     
        });

        // Open Close page help
        $('#ism_help_wrap').hide();
        $('#ism_help_me').click( function() {
        var help = $('#ism_help_wrap');
        if (help.is(':visible')) {
            help.slideUp();
            } else {
            help.slideDown();
            }
        }); 

        // Close a window
        $('.ism_close_window').unbind().bind('click', function() {
            $('.ism_window_wrapper').hide(); // All windows
            window_problem_elements('visible');                
            return false;
        });

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

        // Show profile
        $('#ism_player_nav_profile').unbind().bind('click',function() {
            var height = $('#ism_player_profile').height();
            $('#ism_graph_wrapper').hide();
            $('#ism_player_window .ism_window_content').animate({height: height}, 'slow');
            $('#ism_player_window .ism_window_slide').animate({top: '0px'}, "fast");    
        });

        // Show history
        $('#ism_player_nav_history').unbind().bind('click',function() {
            var height = $('#ism_player_history').height();
            var offset = 0 - $('#ism_player_profile').height();
            $('#ism_graph_wrapper').hide();
            $('#ism_player_window .ism_window_content').animate({height: height}, 'slow');
            $('#ism_player_window .ism_window_slide').animate({top: offset}, "fast");
        
        });

        // Show fixtures
        $('#ism_player_nav_fixtures').unbind().bind('click',function() {
            var height = $('#ism_player_fixtures').height();
            var offset = 0 - $('#ism_player_profile').height()
                           - $('#ism_player_history').height();
            $('#ism_graph_wrapper').hide();
            $('#ism_player_window .ism_window_content').animate({height: height}, 'slow');
            $('#ism_player_window .ism_window_slide').animate({top: offset}, "fast");
        });

        // Show graph
        $('#ism_player_nav_graph').unbind().bind('click',function() {
            $('.ism_news_scroller').hide();
            // Populate element drop downs
            var callback_key = ism_callback_class + "|json_element_graph_lists_cb"
            var url = "/M/ajax?" + callback_key + "=" + elid;
            $.getJSON(url,
                function(data) {
                    var options = '<option>'+select+'</option>';
                    var last_team = '';
                    for (var i=0; i<data.length;i++) {
                        if (last_team != data[i].team) {
                            options += '<option class="ism_graph_club">' + data[i].team + '</option>';
                            last_team = data[i].team;
                        }
                        options += '<option class="ism_graph_player" value="'+data[i].id+'">' + data[i].name + ' . ' + data[i].points + pts + ' . ' + currency + data[i].cost + '</option>';
                    }
                    for (var j=1; j<=graph_choices; j++) {
                        $('select#ism_element_'+j).html(options);
                        $('select#ism_element_'+j)[0].selectedIndex = 0;
                    }
                }
            );
            show_element_graph();
            var height = $('#ism_player_graph').height();
            var offset = 0 - $('#ism_player_profile').height()
                           - $('#ism_player_history').height()
                           - $('#ism_player_fixtures').height();
            $('#ism_player_window .ism_window_content').animate({height: height}, 'slow');
            $('#ism_player_window .ism_window_slide').animate({top: offset}, "fast");    
        });

        // Plot graph button
        $('#ism_plot_graph').unbind().bind('click',function() {
            show_element_graph();
            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
        $('#ism').find('img[@src$=.png]').pngfix();

        //DRAG WINDOWS
        if ($(".ism_window_wrapper").draggable) {
            $(".ism_window_wrapper").draggable();
        }

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

    });

    /////////////////////////////////////////////////////////////////////////

    // Private variables
    var window_problem_selectors = new Array(
        "#ni_google",
        "form#ism_filters",
        "select#ism_event_id",
        "select#ism_language_selector"
    );
    var window_problem_linux_selectors = new Array(
        "#ism_banner",
        "#ism_mpu_advert",
        '#ism_skyscraper'
    )
    var elid; // Current element being viewed
    var wildcard_invalid_teams = {}; // Map of teams which can't be selected

    /////////////////////////////////////////////////////////////////////////

    // Private functions

    // Handle elements which cause problems with our windows
    // Pass either visibilty or hidden as a property
    function window_problem_elements(property) {
        $.each(window_problem_selectors, function(index,selector) {
            $(selector).css({visibility: property});
        });
        if (navigator.platform.indexOf("Linux") > -1) {
            $.each(window_problem_linux_selectors, function(index,selector) {
                $(selector).css({visibility: property});
            });
        }
    }

    // Element graph 
   function show_element_graph() {    
        var graphdata = $('#ism_graphdata').val();
        var cumulative = $('#ism_cumulative').attr('checked') ? 1 : 0;
        var els = elid;
        for (var i=1; i<=graph_choices; i++) {
            if (parseInt($('select#ism_element_'+i).val())) {
                els += ( "," + $('select#ism_element_'+i).val() );
            }
        }
        $('#ism_graph_wrapper').load('/M/element_graph_flash.mc?els='+els+'&graphdata='+graphdata+'&cumulative='+cumulative);
        $('#ism_graph_wrapper').show();
        $('#ism_plot_graph').show();
    }


    /////////////////////////////////////////////////////////////////////////

    return {
        
        // Public variables, set using script sections in components
        vars : {
            bank : undefined, // How much in bank
            callback_class : undefined, // Callback class
            cb_add : undefined, // add_entry callback
            cb_autocomplete : undefined, // add_entry callback
            cb_make_tranfers : undefined, // make_transfers callback
            ed : [], // Element details
            err_already_chosen : undefined, // Player already in team
            err_all_selected : undefined, // Maximum number of players
            err_formation : undefined, // Chosing an invalid formation
            err_incomplete_squad : undefined, // Squad not full
            err_no_transfers : undefined, // No transfers
            filter_exclude_elements : {}, // Elements not to show
            filter_exclude_teams : {}, // Teams not to show
            filter_exclude_types : {}, // Types not to show
            filter_tospend : undefined, // Maximum to spend
            formations : {}, // Details of formations
            img_i : undefined, // Info icon
            img_d : undefined, // Info icon (Doubtful)
            img_n : undefined, // Info icon (News)
            img_bench_in : undefined, // Bring a player from the bench
            img_bench_out : undefined, // Put a player on the bench
            img_bench_out_cancel : undefined, // Cancels putting a player bench
            img_in : undefined, // Adding a player
            img_in_cancel : undefined, // Cancel an addition
            img_out : undefined, // Removing a player
            img_out_cancel : undefined, // Cancel a removal
            img_captain : undefined, // Captain icon
            invalid_captain_types : [], // Types which can't be captain
            live : undefined, // Is the game live?
            num_types : undefined, // Number of Element Types
            num_teams : undefined, // Number of Teams
            picks : [], // Details of existing picks
            pd: [], // Price details for current picks (sell / buy)
            play_max : [], // Maximum playing for each ElementType
            play_min : [], // Minimum playing for each ElementType
            pr : [], // Price ranges 
            play_size : undefined, // Number of elements playing
            selection_player_limit : undefined, // How many to show 
            show_full_name : '', // Full name showed in element window?
            si : [], // Shirt images
            st : [], // Map of stat names to ease lookups in the ed array
            squad_max : [], // Maximum selected for each ElementType
            squad_min : [], // Minimum selected for each ElementType
            squad_size : undefined, // Number of elements in squad
            team_limit : [], // Elements from each Team
            teamlimit_wildcard : [], // Wildcard team limit
            td : [], // Team details
            tn : [], // Element Type names
            to_spend : [], // Amount to spend
            txt_close : 'Close window', // Close text for windows
            txt_drag_me : '', //DRAG ME TEXT
            txt_no_joker : '', // Text for no prediction error
            code  : '', // Game code
            transfers_used_alert : 1, // Alert if all transfers used
            use_png_shirts : 0, // Are we using png shirts?
            'zzzzzz' : 'zzzzz' // Just so we don't forget the last one (no ,)!
        },
        
        // Public functions

        // EVENT WILD CARD RELATED FUNCTIONS ----------------------------------

        draw_element_wildcard : function(pos) {

            // Get jQuery objects for all elements
            var $shirt = $("#ism_selection_"+pos+"_shirt"); 
            var $action = $("#ism_selection_"+pos+"_action");
            var $actioni = $("#ism_selection_"+pos+"_action_image");
            var $info = $("#ism_selection_"+pos+"_info_link");
            var $infoi = $("#ism_selection_"+pos+"_info_image");
            var $dti = $("#ism_selection_"+pos+"_dreamteam_image");
            var $name = $("#ism_selection_"+pos+"_name");
            var $stat = $("#ism_selection_"+pos+"_stat");

            // Check ism_elout and ism_elin or use ed
            var original_el_id = ISMFG.vars.picks[pos];        
            var el;
            var team_shirt;
            // We are proposing to remove this player
            if ($('#ism_elout').val() == original_el_id) {
                if ($('#ism_elin').val()) {
                    el = ed[$('#ism_elin').val()];
                    team_shirt = el[_team_id];
                    // Action
                    $actioni
                        .attr("src",ISMFG.vars.img_in_cancel.src)
                        .attr("alt",ISMFG.vars.img_in_cancel.alt)
                        .attr("title",ISMFG.vars.img_in_cancel.alt);
                    $action.attr("href","javascript:ISMFG.cancel_element_wildcard("+pos+")");
                }
                else {
                    el = ed[original_el_id];
                    team_shirt = 0;
                    // Action
                    $actioni
                        .attr("src",ISMFG.vars.img_out_cancel.src)
                        .attr("alt",ISMFG.vars.img_out_cancel.alt)
                        .attr("title",ISMFG.vars.img_out_cancel.alt);
                    $action.attr("href","javascript:ISMFG.remove_element_wildcard("+pos+")");
                }
            }
            else {
                el = ed[original_el_id];
                team_shirt = el[_team_id];
                // Action
                $actioni.attr("src",ISMFG.vars.img_out.src)
                    .attr("alt",ISMFG.vars.img_out.alt)
                    .attr("title",ISMFG.vars.img_out.alt);
                $action.attr("href","javascript:ISMFG.cancel_element_wildcard("+pos+")");
            }

            // Shirt
            if (el[_element_type_id] == 1) {
                $shirt.attr("src", gsi[team_shirt].src);
            }
            else {
                $shirt.attr("src", si[team_shirt].src);
            }
            $shirt.attr("alt", si[team_shirt].alt);
            $shirt.attr("title", si[team_shirt].alt);
            if (ISMFG.vars.use_png_shirts) {
                $shirt.pngfix();
            }

            // Info
            $info.attr("href","javascript:draw_element_view("+el[_id]+")");
            if (el[_id][_doubtful]) {
                $infoi.attr("src",infoposs_image.src);
            }
            else if (el[_id][_news]) {
                $infoi.attr("src", infowarn_image.src);
            }
            else {
                $infoi.attr("src", info_image.src);
            }
            $infoi.show();

            // Dream Team
            $dti.hide();

            // Name
            $name.html(wrap_text(el[_web_name]));

            // Stat
            $stat.html(el[_now_cost].toFixed(1));

        },

        add_element_wildcard : function(id) {
            if ($('#ism_elout').val() && !$('#ism_elin').val()) {
                $('#ism_elin').val(id);
                var elout = $('#ism_elout').val();
                for (var i=1; i<=squadsize; i++) {
                    if (ISMFG.vars.picks[i] == elout) {
                        ISMFG.draw_element_wildcard(i);
                        $('#ism_play_wildcard').show();
                        break;
                    }
                }
            $('#ism_event_wild_card_tospend_value').parent().css('visibility','hidden');
            }
        },

        cancel_element_wildcard : function(pos) {
            

            // Cancelling the replacement
            if (($('#ism_elout').val())) {
                var el=ed[$('#ism_elout').val()];
                if (ISMFG.vars.picks[pos] != el[_id]) return;
                $('#ism_event_wild_card_tospend_value').parent().css('visibility','visible');
            }
            // Looking to find a replacement
            else {
                var el = ed[ISMFG.vars.picks[pos]];
                $('#ism_elout').val(el[_id]);
                $('#ism_pitch_grid div.ism_element_name').not('#ism_selection_'+pos+'_name').parent().fadeTo("fast", 0.5);
                for (var i=1; i<=numtypes; i++) {
                    if (el[_element_type_id] == i) {
                        $("#ism_element_filter option[value='et_"+i+"']").attr('selected',1);
                    }
                    else {
                        ISMFG.vars.filter_exclude_types[i] = 1;
                        $("#ism_element_filter option[value='et_"+i+"']").attr('disabled',1);
                    }
                }

                // Tospend filter
                $('#ism_event_wild_card_tospend_value').html(el[_now_cost].toFixed(1)).parent().css('visibility','visible');
                ISMFG.vars.filter_tospend = el[_now_cost];

                // Remove teams which we have the limit of
                var team_selections = new Array;
                for (var i=1; i<=squadsize; i++) {
                    if (ISMFG.vars.picks[i] == el[_id]) continue;
                    var team = ed[ISMFG.vars.picks[i]][_team_id];
                    if (ISMFG.vars.filter_exclude_teams[team]) continue;
                    if(team_selections[team] == undefined) {
                        team_selections[team] = 1;
                    }
                    else {
                        team_selections[team]++;
                    }
                    if (team_selections[team] >= ISMFG.vars.teamlimit_wildcard[team]) {
                        ISMFG.vars.filter_exclude_teams[team] = 1;
                        $("#ism_element_filter option[value='te_"+team+"']").attr('disabled',1);
                        wildcard_invalid_teams[team] = 1;
                    }
                }
                get_element_data(1);
            }
            $('#ism_elin').val('');
            $('#ism_play_wildcard').hide();
            ISMFG.draw_element_wildcard(pos);
        },

        remove_element_wildcard : function(pos) {
            $('#ism_play_wildcard').hide();
            $('#ism_elout').val('');
            ISMFG.draw_element_wildcard(pos);
            $('#ism_pitch_grid div').fadeTo("fast",1.0);
            for (var i=1; i<=numtypes; i++) {
                $("#ism_element_filter option[value='et_"+i+"']").attr('disabled',0);
            }
            ISMFG.vars.filter_exclude_types = {};
            $("#ism_element_filter option:first").attr('selected',1);
            $('#ism_event_wild_card_tospend_value').html('').parent().css('visibility','hidden');
            ISMFG.vars.filter_tospend = undefined;

            // Reset teams removed by teamlimit
            $.each(wildcard_invalid_teams, function(team,value) {
                ISMFG.vars.filter_exclude_teams[team] = undefined;
                $("#ism_element_filter option[value='te_"+team+"']").attr('disabled',0);
            });
            wildcard_invalid_teams = {};

            get_element_data(1);
        },

        // END OF EVENT WILD CARD RELATED FUNCTIONS ---------------------------

        // DRAW THE ELEMENT OVERLAY -------------------------------------------

        draw_element_view : function(id) {
            elid = id;
            //$('.ism_window_wrapper').hide();
            window_problem_elements('hidden');                
            var callback_key = ism_callback_class + "|json_element_cb"
            var url = '/element_json/' + id + '.json';
            $.getJSON(url,
                function(data) {
                    $('#ism_player_name').html(data.first_name == '' || ISMFG.vars.show_full_name == 0 ? data.web_name : data.first_name+' '+data.second_name);
                    $('#ism_player_club').html(data.team_name);
                    $('#ism_future_team_name').html(data.team_name);
                    $('#ism_player_position').html(data.type_name);
                    $('#ism_player_price').html(data.now_cost);
                    $('#ism_selected_by').html(data.selected_by + '%');
                    $('#ism_total').html(data.total);
                    $('#ism_event_total').html(data.event_total);
                    $('#ism_next_fixture').html(data.next_fixture);
                    if (data.news != '') {
                        $('#ism_news_wrapper').show();
                        $('#ism_news').html(data.news);
                    }
                    else {
                        $('#ism_news_wrapper').hide();
                    }
                    $('#ism_image_overlay').html('<img src="' + element_image(data) + '" id="ism_player_photo"/>')
                    $('#ism_player_fixtures_table tbody').empty();
        
                    // Event explain
                    $('#ism_event_explain tbody').empty();
                    for (var i=0; i<data.event_explain.length; i++) {
                        var points = data.event_explain[i][2] == null ? 0 : data.event_explain[i][2];
                        $('#ism_event_explain').append("<tr><td>"+data.event_explain[i][0]+"</td><td>"+data.event_explain[i][1]+"</td><td>"+points+"</td></tr>");
                    }
        
                    // Fixtures
                    for (var i=0; i<data.fixtures.length; i++) {
                        var opponent = data.fixtures[i][2];        
                        if (!no_home_away && opponent) {
                            opponent += " ";
                            opponent += data.fixtures[i][3] ? txt_away : txt_home;                     
                        }
                        $('#ism_player_fixtures_table tbody').append("<tr><td>"+data.fixtures[i][0]+"</td><td>"+data.fixtures[i][1]+"</td><td>"+opponent+"</td></tr>");                 
                    }
        
                    // Fixture History
                    $('#ism_player_history_table tbody').empty();
                    for (var i=0; i<data.fixture_history.length; i++) {
                        var row = '';
                        for (var j = 0; j<data.fixture_history[i].length; j++) {
                            row += '<td>' + data.fixture_history[i][j] + '</td>';
                        }
                        $('#ism_player_history_table tbody').append("<tr>"+row+"</tr>");                 
                    }
                    $("#ism_player_history_table tbody tr:nth-child(odd)").addClass("ism_row_1");
                    $("#ism_player_history_table tbody tr:nth-child(odd)").addClass("ism_row_0");
        
                    // Season history
                    $('#ism_player_season_history_table tbody').empty();
                    for (var i=0; i<data.season_history.length; i++) {
                        var row = '';
                        for (var j = 0; j<data.season_history[i].length; j++) {
                            row += '<td>' + data.season_history[i][j] + '</td>';
                        }
                        $('#ism_player_season_history_table tbody').append("<tr>"+row+"</tr>");                 
                    }
                    $("#ism_player_season_history_table tbody tr:nth-child(odd)").addClass("ism_row_1");
                    $("#ism_player_season_history_table tbody tr:nth-child(odd)").addClass("ism_row_0");
        
                    // Code to provide add / delete watch list functionality
                    if (document.getElementById('ism_watchlist')) {
                        var found = 0;
                        for (var i =0; i< wl.length; i++) {
                            if (wl[i] == id) {
                                var params = {};
                                params[del_wl_cb] = id;
                                $('#ism_watchlist').unbind().bind("click",function(){
                                    $.get("/M/ajax", params, function(data) {
                                        wl.splice(i,1);
                                        $('#ism_watchlist').hide();
                                        if ($('#ism_element_filter').val() == 'watchlist') {
                                            get_element_data();
                                        }
                                    });
                                });
                                $('#ism_watchlist')
                                    .html(del_wl)
                                    .css('cursor','pointer')
                                    .show()
                                ;
                                found = 1;
                                break;
                            }
                        }
                        if (!found) {
                            if ( wl.length >= watch_list_max) {
                                $('#ism_watchlist')
                                    .unbind()
                                    .bind("click",function(){
                                        return false;
                                    })
                                    .html(limit_wl)
                                    .show()
                                ;
                            }
                            else {
                                var params = {};                
                                params[add_wl_cb] = id;
                                $('#ism_watchlist').unbind().bind("click",function(){
                                    $.get("/M/ajax", params, function(data) {
                                        wl.splice(0,0,id);
                                        $('#ism_watchlist').hide();
                                        if ($('#ism_element_filter').val() == 'watchlist') {
                                            get_element_data();
                                        }
                                        var $message = $('<div/>')
                                            .attr('id','ism_watchlist_message')
                                            .text(where_wl)
                                        ; 
                                        $('#ism_watchlist')
                                            .unbind()
                                            .bind("click",function(){
                                                return false;
                                            })
                                            .css('cursor','default')
                                            .html($message)
                                            .show()
                                        ;
                                    });
                                });
                                $('#ism_watchlist')
                                    .html(add_wl)
                                    .css('cursor','pointer')
                                    .show();
                            }
                        }
                    }
                    // If already showing, no need to reposition
                    if ($('#ism_player_window').css('display') == 'none') {
                        $('#ism_player_window').vCenter();
                    }
                    $('form#ism_filters').css({visibility: "hidden"});
                    $('select#ism_event_id').css({visibility: "hidden"});
                    if (navigator.platform.indexOf("Linux") > -1) {
                        $('#ism_banner').hide();
                        $('#ism_mpu_advert').hide();
                    }
                    $('#ism_player_window').show();
                    $('#ism_player_nav_profile').click();
                }
            );
        }


    };
    
}(jQuery);


// jQuery additions

// 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) { ISMFG.draw_element_view(id); }
