 ///<reference name="MicrosoftAjax.js"/>
///<reference name="Telerik.Web.UI.Common.Core.js" assembly="Telerik.Web.UI"/>
var PE =
{
    Random:
    {
        Int: function (min, max)
        {
            return Math.floor(Math.random() * (max - min + 1)) + min;
        }
    },

    Log: function (info)
    {
        //for debugging purposes only		window.log(info);
    },

    Grid:
    {
        SetDataSource: function(GridID, Data)
        {
            var tableView = $find(GridID).get_masterTableView();
            tableView.set_dataSource(Data);
            tableView.dataBind();

            // custom properties, save for easy update later
            tableView.dataSource = Data;
            tableView.updateTimes = {};

            for (var idx = 0, count = tableView.dataSource.length; idx < count; ++idx)
            {
                tableView.updateTimes[tableView.dataSource[idx].id] = {};
                for (o in tableView.dataSource[idx]) if (o != "id") tableView.updateTimes[tableView.dataSource[idx].id][o] = 0;
            }
        },

        DoHighlight: function (GridID)
        {
            //update datagrid
            var tableView = $find(GridID).get_masterTableView();
            var items = tableView.get_dataItems();
			var now = new Date().getTime();

			//todo: invert those 2 loops
//            for (var i = 0, n = tableView.updateTimes.length; i < n; ++i)
//            {
//				for (o in tableView.updateTimes[i])
//				{
//            		alert(i + ':' + o);
//            		alert(i + ':' + tableView.updateTimes[i][o]);
//            	}
//            }

            for (var i = 0, n = items.length; i < n; ++i)
            {
                var id = items[i].getDataKeyValue('id');
                if (tableView.updateTimes[id])
                {
                    for (o in tableView.updateTimes[id])
                    {
                        var cell = $(tableView.getCellByColumnUniqueName(items[i], o));

                        // remove highlight
                        if (tableView.updateTimes[id][o] < (now - (HIGHLIGHT_SEC * 1000)))
                        {
                            /*if(cell.hasClass('update'))*/cell.removeClass('update');
                        }
                        // add highlight
                        else
                        {
                            /*if (!cell.hasClass('update'))*/cell.addClass('update');
                        }
                    }
                }
            }
        },

        // Arguments : GridID, KeyName, KeyValue OR GridID, RowIndex
        HighlightSingleRow: function (GridID, KeyNameOrIdx, KeyValue)
        {
            var tableView = $find(GridID).get_masterTableView();
            $(tableView.get_element()).find('.highlight').removeClass('highlight');

            PE.Grid.HighlightRow(GridID, KeyNameOrIdx, KeyValue);
        },

        // Arguments : GridID, KeyName, KeyValue OR GridID, RowIndex
        HighlightRow: function (GridID, KeyNameOrRowIdx, KeyValue)
        {
            var tableView = $find(GridID).get_masterTableView();
            var items = tableView.get_dataItems();
            var tr = false;

            if (KeyValue)
            {
                for (var i = 0, n = items.length; i < n; ++i)
                {
                    if (items[i].getDataKeyValue(KeyNameOrRowIdx) == KeyValue)
                    {
                        tr = items[i].get_element(); break; // we should never have 2 rows with the same key
                    }
                }
            }
            else
            {
                tr = items[KeyNameOrRowIdx].get_element();
            }

            if (tr)
            {
                $(tr).addClass('highlight');
            }
        },

        StateManager:
        {
            _statebag: new Object(),

            AddHighlight: function (GridID, RowIndex, ColumnIndex)
            {
                var tr = $find(GridID).get_masterTableView().get_dataItems()[RowIndex].get_element();
                $(tr.cells[ColumnIndex]).addClass('hlc');
                $(tr).addClass('hlr');
            },

            RemoveHighlight: function (GridID, RowIndex, ColumnIndex)
            {
                var tr = $find(GridID).get_masterTableView().get_dataItems()[RowIndex].get_element();
                $(tr.cells[ColumnIndex]).removeClass('hlc');

                if ($(tr).find('td.hlc').length == 0)
                    $(tr).removeClass('hlr');
            },

            ResetState: function (sender, args)
            {
                if (args.get_commandName() == "Sort")
                {
                    PE.Grid.StateManager._statebag[sender.get_id()] = false;
                }
            },
            UpdateState: function (sender, args)
            {
                var GridID = sender.get_id();
                // get the grid
                var grid_control = $find(GridID);
                // get grid data items
                var data_items = grid_control.get_masterTableView().get_dataItems();

                // initialize data
                var is_update = (PE.Grid.StateManager._statebag[GridID] && (PE.Grid.StateManager._statebag[GridID].length == data_items.length));

                if (!is_update)
                {
                    var state_data = new Array();

                    // loop through grid
                    for (var idx = 0; idx < data_items.length; ++idx)
                    {
                        state_data.push(new Array());

                        var cells = data_items[idx].get_element().cells;
                        for (var col_index = 0; col_index < cells.length; ++col_index)
                        {
                            state_data[state_data.length - 1].push({ "data": cells[col_index].innerHTML, "changed_at": null, "timer": null });
                        }
                    }

                    // put in state bag
                    PE.Grid.StateManager._statebag[GridID] = state_data;
                }
                else
                {
                    // get the old data
                    var state_data = PE.Grid.StateManager._statebag[GridID];

                    // only highlight if old and new data contain the same number of rows
                    if (state_data.length == data_items.length)
                    {
                        // loop through the grid
                        for (var idx = 0; idx < data_items.length; ++idx)
                        {
                            var row = data_items[idx].get_element();
                            var cells = row.cells;
                            var changed = false;

                            for (var col_index = 0; col_index < cells.length; ++col_index)
                            {
                                var cell = cells[col_index];

                                // check for a change
                                if (state_data[idx][col_index].data != cell.innerHTML)
                                {
                                    // set changed to true, will be used to highlight th rest of the row
                                    changed = true;

                                    // add CSS class
                                    PE.Grid.StateManager.AddHighlight(GridID, idx, col_index);

                                    // set change datetime
                                    PE.Grid.StateManager._statebag[GridID][idx][col_index].changed_at = new Date();

                                    // set new data
                                    PE.Grid.StateManager._statebag[GridID][idx][col_index].data = cell.innerHTML;

                                    // automatically remove highlight after 60 seconds ... 5 for now
                                    if (PE.Grid.StateManager._statebag[GridID][idx][col_index].timer) clearTimeout(PE.Grid.StateManager._statebag[GridID][idx][col_index].timer);
                                    PE.Grid.StateManager._statebag[GridID][idx][col_index].timer = setTimeout("PE.Grid.StateManager.RemoveHighlight('" + GridID + "', " + idx + ", " + col_index + ");", 60000);
                                }
                                else
                                {
                                    // first time, no change
                                    if (state_data[idx][col_index].changed_at == null)
                                    {
                                        // do nothing
                                    }
                                    // last change is within a minute
                                    else
                                    {
                                        if (state_data[idx][col_index].changed_at.getTime() >= new Date().getTime() - 60000)
                                        {
                                            // highlight the cell
                                            PE.Grid.StateManager.AddHighlight(GridID, idx, col_index);

                                            // will highlight the row
                                            changed = true;
                                        }
                                        // no change within the last minute
                                        else
                                        {
                                            // make sure he cell is not highlighted
                                            PE.Grid.StateManager.RemoveHighlight(GridID, idx, col_index);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }

            }
        },

        Rebind: function (grid_id)
        {
            $find(grid_id).get_masterTableView().fireCommand("Rebind", "");
        },

        UpdatePreference: function (s, a)
        {
            var strCols = '';
            var cols = a.get_gridColumn().get_owner().get_columns();
            for (var i = 0; i < cols.length; ++i)
            {
                var col = cols[i];
                if (col.get_visible())
                {
                    strCols += col.get_uniqueName() + ',';
                }
            }
            strCols = strCols.substr(0, strCols.length - 1);
            var gridid = a.get_gridColumn().get_owner().get_owner().get_id();

            gridid = gridid.substr(gridid.lastIndexOf(PE.IDSeparator) + 1);

            $.ajax('?gridcols=1&grid=' + gridid + '&cols=' + strCols, {});
        },

        MustLogin: function (s, a)
        {
            a.set_cancel(true);
            if (!$('#gridlogindiv').size())
            {
                $(document).append('<div id="gridlogindiv"/>')
            }
            PE.Window.ShowSignin($('#gridlogindiv')[0], location.href);
        },

        Formatters:
        {
            //           new FInjuryInfo(dic["S_TH_MOREDETAILS"], dic["S_LGD_MOREDETAILS"], COL_STATUS.ToString(), SORT_ASC, ESTATUS, EID, INJ_DETAIL),
            //           new FInjuryDetail(dic["S_TH_COMMENT2"], dic["S_LGD_COMMENT2"], COL_DETAIL.ToString(), SORT_ASC, INJ_DETAIL),
            //           new FString(dic["S_TH_INJTYPE"], dic["S_LGD_INJTYPE"], COL_INJ_TYPE.ToString(), SORT_ASC, INJ_TYPE)

            FInjuryDetail:
            {
                Write: function (eid, lang)
                {
                    return '<div style="text-align:center;"><a onclick="showInjuryInfo(' + eid + '); return false;" href="#">' + (lang == 'fr' ? 'd&eacute;tails' : 'details') + '</a></div>';
                }
            },

            FDate:
            {
                Write: function (intDate, lang)
                {
                    var theDate = PE.Date.IntToDate(intDate);
                    var strDate = '';

                    var monthname = PE.Date.GetMonthName(theDate.getMonth(), lang);

                    if (lang == 'fr')
                        strDate = theDate.getDate() + ' ' + monthname;
                    else
                        strDate = monthname.substr(0, 1).toUpperCase() + monthname.substr(1, monthname.length) + ' ' + theDate.getDate();

                    return strDate;
                }
            },

            FPlayer:
            {
                Write: function (firstname, lastname, id, type, status, pool_id, ui)
                {
                    return '<a onclick="showPlayerUI(' + id + ',' + PE.Date.DateToInt(Date().toString()) + ',' + type + ',\'' + pool_id + '\',\'' + ui + '\'); return false;" href="#">' + firstname + ' ' + lastname + '</a>';
                }
            },

            FEType:
            {
                // If somethng is changed here, must change PoolExpert/DBCst.cs and www_aspx/App_GlobalResources/Strings(.fr).resx too !
                Write: function (type, lang)
                {
                    var str_type = '';
                    if (type)
                    {
                        if (lang == 'en')
                        {
                            switch (type)
                            {
                                case 1: // DBCst.dbGoalie:
                                    str_type = "G";
                                    break;
                                case 2: // DBCst.dbTeam:
                                    str_type = "T";
                                    break;
                                case 3: // DBCst.dbCentre:
                                    str_type = "C";
                                    break;
                                case 4: // DBCst.dbRightWing:
                                    str_type = "RW";
                                    break;
                                case 5: // DBCst.dbLeftWing:
                                    str_type = "LW";
                                    break;
                                case 6: // DBCst.dbDefenseman:
                                    str_type = "D";
                                    break;
                                case 7: // DBCst.dbSkater:
                                    str_type = "S";
                                    break;
                                case 8: // DBCst.dbForward:
                                    str_type = "F";
                                    break;

                                case 10: // DBCst.dbTeamBB:
                                    str_type = "T";
                                    break;
                                case 11: // DBCst.dbStartingPitcher:
                                    str_type = "SP";
                                    break;
                                case 12: // DBCst.dbReliefPitcher:
                                    str_type = "RP";
                                    break;
                                case 13: // DBCst.dbCatcher:
                                    str_type = "C";
                                    break;
                                case 14: // DBCst.dbFirstBase:
                                    str_type = "1B";
                                    break;
                                case 15: // DBCst.dbSecondBase:
                                    str_type = "2B";
                                    break;
                                case 16: // DBCst.dbThirdBase:
                                    str_type = "3B";
                                    break;
                                case 17: // DBCst.dbShortStop:
                                    str_type = "SS";
                                    break;
                                case 18: // DBCst.dbInnerField:
                                    str_type = "IF";
                                    break;
                                case 19: // DBCst.dbLeftField:
                                    str_type = "LF";
                                    break;
                                case 20: // DBCst.dbCenterField:
                                    str_type = "CF";
                                    break;
                                case 21: // DBCst.dbRightField:
                                    str_type = "RF";
                                    break;
                                case 22: // DBCst.dbOuterField:
                                    str_type = "OF";
                                    break;
                                case 23: // DBCst.dbDesignatedHitter:
                                    str_type = "DH";
                                    break;
                                case 24: // DBCst.dbOtherPosition:
                                    str_type = "OT";
                                    break;
                                case 35: // DBCst.dbBatter:
                                    str_type = "B";
                                    break;
                                case 36: // DBCst.dbPitcher:
                                    str_type = "P";
                                    break;
                            }
                        }
                        else
                        {
                            switch (type)
                            {
                                case 1: // DBCst.dbGoalie:
                                    str_type = "G";
                                    break;
                                case 2: // DBCst.dbTeam:
                                    str_type = "Eq.";
                                    break;
                                case 3: // DBCst.dbCentre:
                                    str_type = "C";
                                    break;
                                case 4: // DBCst.dbRightWing:
                                    str_type = "AD";
                                    break;
                                case 5: // DBCst.dbLeftWing:
                                    str_type = "AG";
                                    break;
                                case 6: // DBCst.dbDefenseman:
                                    str_type = "D";
                                    break;
                                case 7: // DBCst.dbSkater:
                                    str_type = "P";
                                    break;
                                case 8: // DBCst.dbForward:
                                    str_type = "A";
                                    break;

                                case 10: // DBCst.dbTeamBB:
                                    str_type = "Eq.";
                                    break;
                                case 11: // DBCst.dbStartingPitcher:
                                    str_type = "LP";
                                    break;
                                case 12: // DBCst.dbReliefPitcher:
                                    str_type = "LR";
                                    break;
                                case 13: // DBCst.dbCatcher:
                                    str_type = "R";
                                    break;
                                case 14: // DBCst.dbFirstBase:
                                    str_type = "1B";
                                    break;
                                case 15: // DBCst.dbSecondBase:
                                    str_type = "2B";
                                    break;
                                case 16: // DBCst.dbThirdBase:
                                    str_type = "3B";
                                    break;
                                case 17: // DBCst.dbShortStop:
                                    str_type = "AC";
                                    break;
                                case 18: // DBCst.dbInnerField:
                                    str_type = "AC";
                                    break;
                                case 19: // DBCst.dbLeftField:
                                    str_type = "CG";
                                    break;
                                case 20: // DBCst.dbCenterField:
                                    str_type = "CC";
                                    break;
                                case 21: // DBCst.dbRightField:
                                    str_type = "CD";
                                    break;
                                case 22: // DBCst.dbOuterField:
                                    str_type = "C";
                                    break;
                                case 23: // DBCst.dbDesignatedHitter:
                                    str_type = "FD";
                                    break;
                                case 24: // DBCst.dbOtherPosition:
                                    str_type = "AU";
                                    break;
                                case 35: // DBCst.dbBatter:
                                    str_type = "F";
                                    break;
                                case 36: // DBCst.dbPitcher:
                                    str_type = "L";
                                    break;
                            }
                        }
                    }
                    return str_type;
                }
            }
        }
    },

    DisableSubmitOnEnter: false,
    t:
	{
	    //Telerik controls supported functions
	    vc: function (s, a)	//ValueChanged
	    {
	        blnChange = true;
	    },
	    vcr: function (s, a)	//ValueChangedReset
	    {
	        blnChange = false;
	    },
	    are: function (s, a)	//AjaxResponseEnd
	    {
	        PE.t.vcr(s, a);
	        if (typeof _gaq !== "undefined" && _gaq !== null)
	        {
	            _gaq.push(['_trackPageview', '/ajax']);
	            //_gaq.push(['_trackPageview', $(location).attr('pathname')]);
	        }
	    }
	},


    PubSub:
    {
        Initialize: function ()
        {
            fm.utilities.log.enabled = false;
            if (PE.QueryString.Get("websyncdebug") == "1")
            {
                fm.utilities.log.enabled = true;
                fm.utilities.error.verbose = true;
            }
            fm.websync.client.initialize({
                key: '11111111-1111-1111-1111-111111111111', // for WebSync On-Demand, specify your public API key, other it is still necessary internally to be a valid GUID.
                onSuccess: function (args)
                {
                    fm.utilities.log("Initialized!");
                },
                onFailure: function (args)
                {
                    fm.utilities.log("Could not initialize. " + args.error);
                }
            });
            /*
            fm.websync.client.registerExtension({
            extensionName: 'autoresubscribeToManual',
            before: {
            subscribe: function(e) {
            if (e.methodConfig.isResubscribe) {
            fm.websync.utilities.log('auto-resubscribe to manual called');

            // turn off the isResubscribe flag so we don't trigger
            // an infinite loop, then call subscribe to send out
            // an individual subscribe request (no batching)
            // this is for IE with cross-domain issues only.
            e.methodConfig.isResubscribe = false;
            fm.websync.client.subscribe(e.methodConfig);

            // cancel the resubscribe
            e.cancel = true;
            }
            }
            }
            });
            */
        },
        Connect: function (on_reconect)
        {
            PE.PubSub.Connect.Retries = 0;

            fm.websync.client.connect({
                stayConnected: true,
                onSuccess: function (args)
                {
                    PE.PubSub.Connect.Retries = 0;
                    if (args.isReconnect)
                    {
                        fm.websync.utilities.log('Reconnected!');
                        if (arguments.length == 1 && jQuery.isFunction(on_reconect))
                            on_reconect(args);
                    } else
                    {
                        fm.websync.utilities.log('Connected!');
                    }
                },
                onFailure: function (args)
                {
                    if (++PE.PubSub.Connect.Retries < 10)
                    {
                        fm.websync.utilities.log('Increasing reconnect count to: ' + PE.PubSub.Connect.Retries);
                        args.reconnect = true;
                    }

                    if (args.isReconnect)
                    {
                        fm.websync.utilities.log('Could not reconnect: ' + args.error);
                    } else
                    {
                        fm.websync.utilities.log('Could not connect: ' + args.error);
                    }
                },
                onStreamFailure: function (args)
                {
                    if (args.willReconnect)
                    {
                        fm.websync.utilities.log('Connection to server lost, reconnecting...');
                    } else
                    {
                        fm.websync.utilities.log('Connection to server lost permanently.');
                    }
                }
            });
        },
        Disconnect: function ()
        {
            fm.websync.client.disconnect({
                onSuccess: function (args)
                {
                    fm.websync.utilities.log('Disconnected!');
                },
                onFailure: function (args)
                {
                    fm.websync.utilities.log('Could not disconnect: ' + args.error);
                }
            });
        },
        Bind: function (k, v)
        {
            if (k == null || k == '' || v == null) return;

            fm.websync.client.bind({
                record: {
                    key: k,
                    value: v
                    //					value: {
                    //						email: 'jdoe@isp.com',
                    //						username: 'johndoe'
                    //					},
                    //					private: true
                },
                onSuccess: function (args)
                {
                    if (args.isRebind)
                    {
                        fm.websync.utilities.log('Rebound!');
                    } else
                    {
                        fm.websync.utilities.log('Bound!');
                    }
                },
                onFailure: function (args)
                {
                    if (args.isRebind)
                    {
                        fm.websync.utilities.log('Could not rebind: ' + args.error);
                    } else
                    {
                        fm.websync.utilities.log('Could not bind: ' + args.error);
                    }
                }
            });
        },
        Unbind: function (k)
        {
            if (k == null || k == '') return;

            fm.websync.client.unbind({
                record: {
                    key: k
                },
                onSuccess: function (args)
                {
                    fm.websync.utilities.log('Unbound!');
                },
                onFailure: function (args)
                {
                    fm.websync.utilities.log('Could not unbind: ' + args.error);
                }
            });
        },

        Subscribe: function (channels, on_receive, on_success)
        {
            // make sure we have an array
            if (!(channels instanceof Array)) channels = [channels];

            if (!channels.length) return;

            fm.websync.client.subscribe({
                channels: channels,

                //onReceive: on_receive
                onReceive: function (args)
                {
                    fm.websync.utilities.log('Received message: ' + fm.json.stringify(args.data));
                    if (jQuery.isFunction(on_receive))
                        on_receive(args);
                },
                onSuccess: function (args)
                {
                    if (args.isResubscribe)
                    {
                        fm.websync.utilities.log('Resubscribed to ' + args.channel + '!');
                    } else
                    {
                        fm.websync.utilities.log('Subscribed to ' + args.channel + '!');
                    }
                    //					if( args.meta )
                    //	                    fm.websync.utilities.log('Received meta: ' + fm.json.stringify(args.meta));
                    if (jQuery.isFunction(on_success))
                        on_success(args);
                },
                onFailure: function (args)
                {
                    if (args.isResubscribe)
                    {
                        fm.websync.utilities.log('Could not resubscribe to ' + args.channel + ': ' + args.error);
                    } else
                    {
                        fm.websync.utilities.log('Could not subscribe to ' + args.channel + ': ' + args.error);
                    }
                }
            });
        },
        Unsubscribe: function (channels, on_success)
        {
            // make sure we have an array
            if (!(channels instanceof Array)) channels = [channels];

            if (!channels.length) return;

            fm.websync.client.unsubscribe({
                channels: channels,
                onSuccess: function (args)
                {
                    fm.websync.utilities.log('Unsubscribed from ' + args.channel + '!');
                    if (jQuery.isFunction(on_success))
                        on_success(args);
                },
                onFailure: function (args)
                {
                    fm.websync.utilities.log('Could not unsubscribe from ' + args.channel + ': ' + args.error);
                }
            });
        },
        startBatch: function ()
        {
            fm.websync.client.startBatch();
        },
        endBatch: function ()
        {
            fm.websync.client.endBatch();
        },
        BindGridToChannel: function (grid_id, channel)
        {
            PE.PubSub.Subscribe(channel, function (args) { PE.Grid.Rebind(grid_id); });
        }
    },

    Array:
    {
        Randomize: function (arr)
        {
            var arr2 = new Array();
            var count = arr.length;
            while (arr2.length < count)
            {
                var randomnumber = Math.floor(Math.random() * (arr.length + 1));
                if (!isNaN(arr[randomnumber]))
                {
                    arr2.push(arr[randomnumber]);
                    arr.splice(randomnumber, 1);
                }
            }
            return arr2;
        }
    },

    Strings:
    {
        Get: function (varname)
        {
            return eval('PE.Strings.' + varname + '_' + PE.Cookies.Get('lang') + ';');
        },

        Loading_fr: "Chargement ...", Loading_en: "Loading ...",
        ChoosePlayer_fr: "Veuillez choisir un joueur", ChoosePlayer_en: "Please select a player",

        S_HOME_CREATE_fr: "Créez votre pool", S_HOME_CREATE_en: "Register your pool",
        S_HOME_NOW_fr: "maintenant", S_HOME_NOW_en: "now",
        home_DK_text_fr: "Acheter votre kit", home_DK_text_en: "Buy your kit",

        From_fr: "De", From_en: "From",
        To_fr: "À", To_en: "To",

        testimonialsLink_fr: "jvs/testimonials_f.xml", testimonialsLink_en: "jvs/testimonials_e.xml"
    },

    Redirect: function (url, context)
    {
        if (context == undefined)
            context = top;
        context.location.href = url;
    },

    IDSeparator: '_',
    NameSeparator: '$',
    IDFromServerID: function (serverID)
    {
        return $('[id$=' + PE.IDSeparator + serverID + ']')[0].id;
        //$('[name$=' + PE.NameSeparator + serverID + ']')[0].id;
    },

    DOM:
    {
        Up: function (elem, howmany)
        {
            var ret = elem;
            for (var i = 0; i < howmany; ++i)
            {
                ret = ret.parent();
            }
            return ret;
        }
    },

    Input:
    {
        ForceInt: function (input, min, max)
        {
            while (Math.floor(input.value * 1) != input.value && input.value.length > 0)
            {
                input.value = input.value.substring(0, input.value.length - 1);
            }
            if (input.value != '')
            {
                input.value *= 1;
                if (!isNaN(min) && input.value < min)
                    input.value = min;
                if (!isNaN(max) && input.value > max)
                    input.value = max;
            }
        },
        HiddenToQS: function (container)
        {
            var from = (container != null ? container : document);
            var elems = from.getElementsByTagName('input');
            var qs = '';

            for (var i = 0, n = elems.length; i < n; ++i)
                if (elems[i].type == 'hidden')
                    qs += elems[i].name + '=' + elems[i].value + '&';

            if (qs.length > 0)
                qs = qs.substring(0, qs.length - 1);

            return qs;
        }
    },
    Cookies:
    {
        GetExpiry: function (days)
        {
            var timeSpan = days * 24 * 60 * 60 * 1000;
            var expDate = new Date();

            expDate.setTime(expDate.getTime() + timeSpan);
            return expDate;
        },

        GetCookieVal: function (offset)
        {
            var endstr = document.cookie.indexOf(";", offset);

            if (endstr == -1)
                endstr = document.cookie.length;
            return unescape(document.cookie.substring(offset, endstr));
        },

        Get: function (name)
        {
            var arg = name + "=";
            var alen = arg.length;
            var clen = document.cookie.length;
            var i = 0;

            while (i < clen)
            {
                var j = i + alen;
                if (document.cookie.substring(i, j) == arg)
                    return getCookieVal(j);
                i = document.cookie.indexOf(" ", i) + 1;
                if (i == 0) break;
            }
            return null;
        },

        Set: function (name, value)
        {
            var argv = arguments;
            var argc = arguments.length;

            var expires = (argc > 2) ? argv[2] : null;
            var path = (argc > 3) ? argv[3] : "/";
            var domain = (argc > 4) ? argv[4] : null;
            var secure = (argc > 5) ? argv[5] : false;

            document.cookie = name + "=" + escape(value) +
                              ((expires == null) ? "" : ("; expires=" + expires.toGMTString())) +
                              ((path == null) ? "" : ("; path=" + path)) +
                              ((domain == null) ? "" : ("; domain=" + domain)) +
                              ((secure == true) ? "; secure" : "");
        },

        Delete: function (name)
        {
            PE.Cookies.Set(name, null, new Date(0));
        },

        SetLang: function (value, domain)
        {
            var expires = PE.Cookies.GetExpiry(30);
            PE.Cookies.Set("lang", value, expires, "/", domain);
            PE.Cookies.Set("lang", value, expires, "/", "www.poolexpert.com");
        }
    },

    QueryString:
    {
        Get: function ()
        {
            if (!PE.QueryString.Values)
            {
                PE.QueryString.Values = new Object();

                // get the query string, ignore the ? at the front.
                var querystring = location.search.substring(1);

                // parse out name/value pairs separated via &
                var args = querystring.split('&');

                // split out each name = value pair
                for (var i = 0; i < args.length; i++)
                {
                    var pair = args[i].split('=');

                    // Fix broken unescaping
                    temp = unescape(pair[0]).split('+');
                    temp0 = temp.join(' ');

                    temp = unescape(pair[1]).split('+');
                    temp1 = temp.join(' ');

                    PE.QueryString.Values[temp0] = temp1;
                }
            }

            var strKey = arguments[0];
            var strDefault = arguments[1] || null;

            var value = PE.QueryString.Values[strKey];
            if (value == null)
            {
                value = strDefault;
            }

            return value;
        },

        QSP_PLAYER_ID: 'h',
        QSP_DATE: 'i',
        QSP_TYPE: '6',
        QSP_POOL_ID: 'j',
        QSP_NAMES: 'k',
        QSP_NUM: 'l',
        QSP_PTS: 'm',
        QSP_COMP_FIRSTNAME: 'n',
        QSP_COMP_LASTNAME: 'o',
        QSP_VALUES: 'p',
        QSP_COMP_ID: 'ba',
        QSP_COMP_ID_2: 'cid',
        QSP_MESSAGE_ID: 'b',
        QSP_DATEFROM: 'df',
        QSP_DATETO: 'dt',
        QSP_PERIOD: 'per',

        QSV_PERIOD_CUSTOM: 'c'

    },

    /* finds any element using Telerik's $find(), then jQuery's $(), adds and sets a boolean property to the returned object (IsTelerik) */
    Find: function ()
    {
        var i = 0;
        var n = arguments.length;
        var o = null;

        while (i < n && o == null)
        {
            try
            {
                o = $find(arguments[i]);
                if (o == null)
                {
                    o = $(arguments[i]);
                    if (o != null) o.IsTelerik = false;
                }
                else
                {
                    o.IsTelerik = true;
                }
            }
            catch (ex)
            {
                o = null;
            }
            ++i;
        }
        return o;
    },

    FilterGridEqualTo: function (GridID, ColumnName, Value)
    {
        $find(GridID).get_masterTableView().filter(ColumnName, Value, Telerik.Web.UI.GridFilterFunction.EqualTo);

        //Grid.set_value("df=" + DateFrom + "&dt=" + DateTo + "&per=" + Period);
    },

    Window:
    {
        Manager: null,
        ShowLogin: function (elem)
        {
            elem = $(elem);
            if (PE.Window.Manager == null) PE.Window.Manager = GetRadWindowManager();
            //            var wndLogin = PE.Window.Manager.open("ajax/loginform.aspx", "wndLogin");
            var wndLogin = PE.Window.Manager.open("loginform.aspx", "wndLogin");

            var elem_offset = elem.offset();
            wndLogin.setSize(328, 258);
            wndLogin.moveTo(elem_offset.left + elem.width() + 30, elem_offset.top - (wndLogin.get_height() / 2));
        },
        ShowSignin: function (elem, redirect_url)
        {
            elem = $(elem);
            if (PE.Window.Manager == null) PE.Window.Manager = GetRadWindowManager();
            //            var wndSignin = PE.Window.Manager.open("ajax/signinform.aspx", "wndSignin");
            var wndSignin = PE.Window.Manager.open("signinform.aspx" + (redirect_url ? "?rd=" + redirect_url : ""), "wndSignin");

            var elem_offset = elem.offset();
            wndSignin.setSize(328, 286);
            wndSignin.moveTo(elem_offset.left, elem_offset.top + elem.height());
        },

        ShowPlayer: function (elem, playerID, date, type, poolid)
        {
            if (!elem)
            {

            }

            //            elem = $(elem);
            if (PE.Window.Manager == null) PE.Window.Manager = GetRadWindowManager();

            var wndPlayer = PE.Window.Manager.open('gplayer.aspx?poppub=1&' + QSP_PLAYER_ID + '=' + playerID + '&' + QSP_DATE + '=' + date + '&' + QSP_TYPE + '=' + type + '&' + QSP_POOL_ID + '=' + poolid, "wndPlayer");
            //            wndPlayer.setSize(600, 300);
            //            wndPlayer.show();
            //            var elem_offset = elem.offset();
            //            wndPlayer.moveTo(elem_offset.left, elem_offset.top + elem.height());
        },

        OnShow: function (s)
        {
            $('.TelerikModalOverlay').click(function ()
            {
                s.SetVisible(false);
                $('.TelerikModalOverlay').hide();
            });
        },

        OnPageLoad: function (s)
        {
            //s.set_title('');
        },

        //This code is used to provide a reference to the radwindow "wrapper"
        GetRadWindow: function ()
        {
            var oWindow = null;
            if (window.radWindow) oWindow = window.radWindow;
            else if (window.frameElement.radWindow) oWindow = window.frameElement.radWindow;
            return oWindow;
        }
    },

    OpenWindow: function (windowId)
    {
        var oWnd = PE.Find(windowId);
        oWnd.show();
        return oWnd;
    },

    Date:
    {
        DATE_DAY_0: Date.parse('Apr 30, 1999'),
        MsInEachDay: (1000 * 60 * 60 * 24),
        DateToInt: function (DateString)
        {
            if (isNaN(Date.parse(DateString))) DateString = DateString.replace('-', '/');
            return Math.floor(Date.parse(DateString) / PE.Date.MsInEachDay) - Math.floor(PE.Date.DATE_DAY_0 / PE.Date.MsInEachDay);
        },
        IntToDate: function (iDate)
        {
            dDate = new Date(0);
            if (iDate > 0)
            {
                dDate = PE.Date.Round(new Date(PE.Date.DATE_DAY_0 + (iDate * PE.Date.MsInEachDay)));
            }
            return dDate;
        },
        Round: function (dDate)
        {
            var up = (dDate.getHours() > 11);

            dDate.setHours(0);
            dDate.setMinutes(0);
            dDate.setSeconds(0);
            if (up) dDate.setDate(dDate.getDate() + 1);

            return dDate;
        },

        GetMonthName: function (num, lang)
        {
            return (lang == 'fr' ? ['janvier', 'f&eacute;vrier', 'mars', 'avril', 'mai', 'juin', 'juillet', 'ao&ucirc;t', 'septembre', 'octobre', 'novembre', 'd&eacute;cembre'] : ['january', 'february', 'march', 'april', 'may', 'june', 'july', 'august', 'september', 'october', 'november', 'december'])[num];
        }
    },

    AJAX:
    {
        PreventScrollBack: function ()
        {
            var prm = Sys.WebForms.PageRequestManager.getInstance();

            prm.add_beginRequest(function ()
            {
                prm._scrollPosition = null;
            });
        },

        ResourcePopup: function (element, res_key)
        {
            element.style.cursor = 'wait';

            if (res_key == PE.AJAX.ResourcePopup.LastKey && PE.AJAX.ResourcePopup.LastValue != '')
            {
                var popup = PE.Find('#pex_respu');
                var popupArrow = PE.Find('#pex_respuArrow');

                popup.show();
                popupArrow.show();

                popup = popup[0];
                popupArrow = popupArrow[0];

                popup.innerHTML = PE.AJAX.ResourcePopup.LastValue;
                popup.style.left = $(element).offset().left - ($('#pex_respu').width() / 2) + "px";
                popup.style.top = $(element).offset().top - ($('#pex_respu').height() + 11) + "px";

                popupArrow.style.left = $(element).offset().left + 1 + "px";
                popupArrow.style.top = $(element).offset().top - 4 + "px";

                $(element)[0].style.cursor = 'help';

                $(element).mouseleave(function ()
                {
                    $('#pex_respu').hide();
                    $('#pex_respuArrow').hide();
                });
            }
            else
            {
                PE.AJAX.ResourcePopup.LastKey = res_key;
                PE.AJAX.ResourcePopup.LastValue = '';

                var req = $.ajax
                (
                    {
                        url: "ajax/resource.aspx?key=" + res_key,
                        context: element,
                        success: function (data, textStatus, requestObject)
                        {
                            //alert(requestObject);
                            // store for future reference (without calling the server)
                            PE.AJAX.ResourcePopup.LastValue = data;

                            var popup = PE.Find('#pex_respu');
                            var popupArrow = PE.Find('#pex_respuArrow');
                            if (popup[0] == undefined)
                            {
                                popup = document.createElement("div");
                                popup.id = 'pex_respu';

                                popup.style.position = 'absolute';

                                document.body.appendChild(popup);

                                popupArrow = document.createElement("div");
                                popupArrow.id = 'pex_respuArrow';
                                popupArrow.style.position = 'absolute';
                                document.body.appendChild(popupArrow);

                                $(popup).hide();
                                $(popupArrow).hide();
                            }
                            else
                            {
                                $(popup).show();
                                $(popupArrow).show();

                                popup = popup[0];
                                popupArrow = popupArrow[0];
                            }

                            popup.innerHTML = data;

                            $(popup).show();
                            $(popupArrow).show();

                            popup.style.left = $(this).offset().left - ($('#pex_respu').width() / 2) + "px";
                            popup.style.top = $(this).offset().top - ($('#pex_respu').height() + 11) + "px";
                            popupArrow.style.left = $(this).offset().left + 1 + "px";
                            popupArrow.style.top = $(this).offset().top - 4 + "px";

                            $(this)[0].style.cursor = 'help';

                            $(this).mouseleave(function ()
                            {
                                $('#pex_respu').hide();
                                $('#pex_respuArrow').hide();
                            });

                            //alert(data);
                            //$(this).addClass("done");
                        }
                    }
                    );
                element.req = req;
                $(element).mouseleave(function ()
                {
                    $(this)[0].req.abort();
                });
            }

        },

        SaveAvatar: function (filename, competitor_id)
        {
            filename = filename.substring(filename.lastIndexOf('/') + 1);

            var req = $.ajax
            (
                {
                    url: "ajax/avatars.aspx?ba=" + competitor_id + '&aa=' + filename,
                    context: PE.AJAX.AvatarSelector.Element,
                    success: function (data, textStatus, requestObject)
                    {
                        var popup = PE.Find('#pex_avsel');
                        if (popup[0] != undefined) popup.remove();

                        if (data != '')
                        {
                            $('.pex_avatar' + competitor_id).attr('src', data);
                        }

                        PE.AJAX.AvatarSelector.Element = null;
                    }
                }
                );

        },

        AvatarSelector: function (element, competitor_id)
        {
            //if($(element).offset().left == 0 ) return;

            document.onclick = function ()
            {
                if (PE.Find('#pex_avsel')) PE.Find('#pex_avsel').remove();
            }

            element.style.cursor = 'wait';

            //            if (competitor_id == PE.AJAX.AvatarSelector.LastID && PE.AJAX.AvatarSelector.LastValue != '')
            //            {
            //                var popup = PE.Find('#pex_avsel');

            //                popup.show();
            //                popup = popup[0];
            //                popup.innerHTML = PE.AJAX.AvatarSelector.LastValue;
            //                popup.style.left = $(element).offset().left - ($('#pex_avsel').width() / 2) + "px";
            //                popup.style.top = $(element).offset().top - ($('#pex_avsel').height() + 11) + "px";

            //                $(element)[0].style.cursor = 'pointer';
            //            }
            //            else
            {
                PE.AJAX.AvatarSelector.LastID = competitor_id;
                PE.AJAX.AvatarSelector.Element = element;
                PE.AJAX.AvatarSelector.LastValue = '';

                var req = $.ajax
                (
                    {
                        url: "ajax/avatars.aspx?ba=" + competitor_id,
                        context: element,
                        success: function (data, textStatus, requestObject)
                        {
                            // store for future reference (without calling the server)
                            PE.AJAX.AvatarSelector.LastValue = data;

                            var popup = PE.Find('#pex_avsel');
                            if (popup[0] == undefined)
                            {
                                popup = document.createElement("div");
                                popup.id = 'pex_avsel';
                                popup.className = 'pex_divAvatars';
                                popup.style.position = 'absolute';

                                document.body.appendChild(popup);
                                $(popup).hide();
                                //document.onclick = function() { PE.Find('#pex_avsel').hide(); }
                            }
                            else
                            {
                                $(popup).show();
                                popup = popup[0];
                            }

                            popup.innerHTML = data;

                            $(popup).show();

                            popup.style.left = $(this).offset().left + "px";
                            popup.style.top = $(this).offset().top + "px";

                            $(this)[0].style.cursor = 'pointer';
                        }
                    }
                    );
            }
        }
    },

    PlayerPopup:
    {
        Close: function ()
        {
            if (PE.PlayerPopup.ArrowElement != undefined)
            {
                $(PE.PlayerPopup.ArrowElement).remove();
                $(PE.PlayerPopup.PopupElement).remove();

                PE.PlayerPopup.ArrowElement = PE.PlayerPopup.PopupElement = PE.PlayerPopup.OpenerElement = undefined;
            }
            document.onclick = function ()
            {
            };
        },

        Open: function (opener, url)
        {
            // do not allow opening from frames, for now
            if (window != top) return;

            opener.style.cursor = 'wait';

            PE.PlayerPopup.Close();

            // set arrow element
            var arrow;
            if (PE.PlayerPopup.ArrowElement == undefined)
            {
                PE.PlayerPopup.ArrowElement = arrow = document.createElement('div');
                arrow.style.display = 'none';
                document.body.appendChild(arrow);
                $(arrow).css({ 'position': 'absolute', 'z-index': 9000, 'background-color': 'red', 'width': '20px', 'height': '20px' });
            }
            else
            {
                arrow = PE.PlayerPopup.ArrowElement;
                $(arrow).fadeOut(1);
            }

            // set popup element
            var popup;
            if (PE.PlayerPopup.PopupElement == undefined)
            {
                PE.PlayerPopup.PopupElement = popup = document.createElement('div');
                popup.style.display = 'none';
                document.body.appendChild(popup);

                $(popup).css({ 'position': 'absolute', 'z-index': 9000 });
                $(popup).click(function (e)
                {
                    e.preventDefault();
                });
            }
            else
            {
                popup = PE.PlayerPopup.PopupElement;
            }

            //transition effect
            //	        $(arrow).fadeTo("slow", 0.5);

            //	        $(popup).css({'top':  ($(opener).offset().top < 200 ? 0 : $(opener).offset().top - 200), 'left': $(arrow).offset().left + $(arrow).width()});
            //transition effect

            PE.PlayerPopup.OpenerElement = opener;

            if (popup.iframe == undefined)
            {
                popup.iframe = document.createElement('iframe');
                popup.appendChild(popup.iframe);

                $(popup.iframe).css({ 'width': '98%', 'height': '98%' });

                popup.iframe.onload = function ()
                {
                    document.onclick = function ()
                    {
                        PE.PlayerPopup.Close();
                    };

                    var iframe_doc = (this.contentDocument ? this.contentDocument : this.contentWindow.document);

                    $(iframe_doc).find('.pex_background').css('background', '#fff none');

                    $(iframe_doc).find('a').click(function (e)
                    {
                        var curr_loc = iframe_doc.location.href;
                        curr_loc = curr_loc.substring(0, curr_loc.indexOf('?'));
                        curr_loc = curr_loc.substring(curr_loc.lastIndexOf('/'));

                        e.preventDefault();

                        if (this.href.indexOf(curr_loc) < 0)
                        {
                            top.location.href = this.href;
                        }
                        else
                        {
                            iframe_doc.location.replace(this.href);
                        }

                    });

                    var elem = $(PE.PlayerPopup.PopupElement);
                    elem.width(750);
                    elem.height(700);

                    var opener = $(PE.PlayerPopup.OpenerElement);
                    var arrow = $(PE.PlayerPopup.ArrowElement);
                    //position the popup window
                    arrow.css({ 'top': opener.offset().top, 'left': opener.offset().left + opener.width() + 4 });
                    arrow.fadeIn(250);
                    elem.css({ 'top': (opener.offset().top < 200 ? 0 : opener.offset().top - 200), 'left': arrow.offset().left + arrow.width() });
                    elem.fadeIn(500);

                    PE.PlayerPopup.OpenerElement.style.cursor = '';
                }

                $(popup).hide();
            }

            if (popup.iframe.src != url)
                popup.iframe.src = url;

            $(popup).css({ 'top': -10000, 'left': -10000 });
            $(popup).show();
            $(popup).fadeOut(1);

            return false;

        }
    },

    wndPlayer: null,
    ShowPlayerUI: function (playerID, date, type, poolid, ui)
    {
        var url, width, height, couleurFond, fond, couleurTexte, typePolice, tailleCaracteres;
        url = 'gplayer.aspx?poppub=1&' + PE.QueryString.QSP_PLAYER_ID + '=' + playerID + '&' + PE.QueryString.QSP_DATE + '=' + date + '&' + PE.QueryString.QSP_TYPE + '=' + type + '&' + PE.QueryString.QSP_POOL_ID + '=' + poolid;

        width = 620;
        height = 320;
        LeftPosition = (screen.width) ? (screen.width - width - 10) : 100;
        TopPosition = 0;

        PE.wndPlayer = window.open(url, 'player', 'top=' + TopPosition + ',left=' + LeftPosition + ',toolbar=no,location=no,directories=no,status=no,scrollbars=no,menubar=no,resizable=yes,copyhistory=no,width=' + width + ',height=' + height + '');
        if (PE.wndPlayer.focus)
            PE.wndPlayer.focus();

        return false;
    },
    ShowPlayer: function (playerID, date, type, poolid)
    {
        return PE.ShowPlayerUI(playerID, date, type, poolid, 'pr');
    },

    DatePicker:
    {
        FromHidden: function (s, a)
        {
            if (typeof s == 'string')
            {
                s = $find($('[id$=_' + s + '_dateInput]')[0].id);
            }

            var id = $('#' + s.get_id() + '_shortid').val();

            var day = $('#' + id + 'day').val() * 1;
            var month = $('#' + id + 'month').val() - 1;
            var year = $('#' + id + 'year').val() * 1;

            if (day != 0)
            {
                var selDate = new Date();
                selDate.setFullYear(year, month, day);
                s.set_selectedDate(selDate);
            }
            else
            {
                s.set_selectedDate(null);
            }
        },
        ToHidden: function (s, a)
        {
            var selDate = s.get_selectedDate();

            if (selDate != null)
            {
                var id = $('#' + s.get_id() + '_shortid').val();
                $('#' + id + 'day').val(selDate.getDate());
                $('#' + id + 'month').val(selDate.getMonth() + 1);
                $('#' + id + 'year').val(selDate.getFullYear());
            }
        }
    },

    PlayerPicker:
    {
        HighlightClass: 'pex_pp_highlight',
        UpdateSalarayCallback: null,

        Init: function (defaultPlayerField, listBox, idFieldPrefix, ruleFieldPrefix, salaryFieldPrefix)
        {
            PE.PlayerPicker.ListBox = listBox;

            PE.PlayerPicker.IdFieldPrefix = idFieldPrefix;
            PE.PlayerPicker.RuleFieldPrefix = ruleFieldPrefix;
            PE.PlayerPicker.SalaryFieldPrefix = salaryFieldPrefix;

            defaultPlayerField.focus();
        },

        PlayerFocus: function (elem, idx)
        {
            // remove focus if previously set
            if (PE.PlayerPicker.FocusIdx != undefined)
            {
                $('.' + PE.PlayerPicker.HighlightClass).removeClass(PE.PlayerPicker.HighlightClass);
            }
            elem.parentNode.parentNode.className = PE.PlayerPicker.HighlightClass;
            PE.PlayerPicker.FocusIdx = idx;
            PE.PlayerPicker.FocusedInput = elem;
        },

        PlayerChange: function (txtLetters)
        {
            $('[name=' + PE.PlayerPicker.IdFieldPrefix + PE.PlayerPicker.FocusIdx + ']').val('');
            blnChange = true;

            var strLetters = new String(txtLetters.toLowerCase());
            var intLen = strLetters.length;
            if (intLen == 0)
                return;

            var i, j, o;
            j = 0;
            var str = new String();
            for (i = 0; i < (parent.aPl.length); i++)
            {
                str = parent.aPLN[i].substring(0, intLen).toLowerCase();
                str = str.toLowerCase();
                if (str == strLetters)
                {
                    o = new Option(parent.aPl[i], i, false, false);
                    PE.PlayerPicker.ListBox.options[j++] = o;
                }
            }

            for (i = PE.PlayerPicker.ListBox.length; i >= j; i--)
                PE.PlayerPicker.ListBox.options[i] = null;

            if (PE.PlayerPicker.ListBox.length > 0)
            {
                PE.PlayerPicker.ListBox.selectedIndex = 0;
                if (PE.PlayerPicker.ListBox.length == 1)
                {
                    PE.PlayerPicker.AddClick();
                }
                else
                {
                    PE.PlayerPicker.ListBox.focus();
                }
            }
        },

        LoadByLetter: function (txtLetter)
        {
            var strLetter = new String(txtLetter.toLowerCase());
            var i, j, o;
            j = 0;
            var str = new String();
            for (i = 0; i < (parent.aPl.length); i++)
            {
                str = parent.aPLN[i].charAt(0).toLowerCase();
                if (str == strLetter)
                {
                    o = new Option(parent.aPl[i], i, false, false);
                    document.aspnetForm.playList.options[j++] = o;
                }
            }
            for (i = document.aspnetForm.playList.length; i >= j; i--)
                document.aspnetForm.playList.options[i] = null;
        },

        LoadAll: function ()
        {
            var i, j, o;
            j = 0;
            var str = new String();
            for (i = 0; i < (parent.aPl.length); i++)
            {
                o = new Option(parent.aPl[i], i, false, false);
                document.aspnetForm.playList.options[j++] = o;
            }
            for (i = document.aspnetForm.playList.length; i >= j; i--)
                document.aspnetForm.playList.options[i] = null;
        },

        LoadByType: function (txtType)
        {
            var strType = new String(txtType);
            var i, j, o;
            j = 0;
            var str = new String();
            for (i = 0; i < (parent.aPl.length); i++)
            {
                str = parent.aPTP[i];
                if (str == strType)
                {
                    o = new Option(parent.aPl[i], i, false, false);
                    document.aspnetForm.playList.options[j++] = o;
                }
            }
            for (i = document.aspnetForm.playList.length; i >= j; i--)
                document.aspnetForm.playList.options[i] = null;
        },

        LoadByTeam: function (txtTeam)
        {
            var strTeam = new String(txtTeam.toLowerCase());
            var i, j, o;
            j = 0;
            var str = new String();
            for (i = 0; i < (parent.aPl.length); i++)
            {
                str = parent.aPT[i].toLowerCase();
                if (str == strTeam)
                {
                    o = new Option(parent.aPl[i], i, false, false);
                    document.aspnetForm.playList.options[j++] = o;
                }
            }
            for (i = document.aspnetForm.playList.length; i >= j; i--)
                document.aspnetForm.playList.options[i] = null;
        },

        AddClick: function ()
        {
            if (PE.PlayerPicker.ListBox.selectedIndex == -1)
            {
                alert(PE.Strings.Get("ChoosePlayer"));
                return;
            }

            var selval = $(PE.PlayerPicker.ListBox).val();

            // rule
            $('[name=' + PE.PlayerPicker.RuleFieldPrefix + PE.PlayerPicker.FocusIdx + ']')[0].selectedIndex = ETypeToPType(parent.aPTP[selval]) - 1;
            // playername
            $(PE.PlayerPicker.FocusedInput).val(PE.PlayerPicker.ListBox.options[PE.PlayerPicker.ListBox.selectedIndex].text);
            // player id
            $('[name=' + PE.PlayerPicker.IdFieldPrefix + PE.PlayerPicker.FocusIdx + ']').val(parent.aPID[selval]);
            // salary
            $('[name=' + PE.PlayerPicker.SalaryFieldPrefix + PE.PlayerPicker.FocusIdx + ']').val(parent.aPS[selval]);

            if (PE.PlayerPicker.UpdateSalarayCallback)
                PE.PlayerPicker.UpdateSalarayCallback();

            // set focus on next textbox
            var inputname = PE.PlayerPicker.FocusedInput.name;

            var nextelem;
            if ((nextelem = $('[name=' + inputname.replace(PE.PlayerPicker.FocusIdx, PE.PlayerPicker.FocusIdx + 1) + ']')[0]) == undefined)
            {
                nextelem = $('[name=' + inputname.replace(PE.PlayerPicker.FocusIdx, "1") + ']')[0];
            }
            nextelem.focus();

            blnChange = true;
        }

    }
};

