/**
 * Le controller des categories
 */
$(function ()
{


    function init(){
        if($('#team').length){

            // Click sur un élément select pour l'ouvrir
            $('.select').click(function(){
                openSelect($(this));
            });

            // Click sur un des choix du du select
            $('.select .selectChoices span').click(function(){
                var value = $(this).html();
                var valueId = $(this).attr('data-id');
                var valueURL = $(this).attr('data-url');
                $(this).parent().parent().find('input').val(valueId);
                $(this).parent().parent().find('input').attr('data-url',valueURL);
                $(this).parent().parent().find('.currentChoice').html(value);
                const a = new URL(window.location);
                a.searchParams.set('Country', $('#pays').attr('data-url'));
                a.searchParams.set('Activity', $('#activity').attr('data-url'));
                window.history.replaceState(null, null, a);
                LoadTeamView();
            });

            $('.select .currentChoice').change(function(){  
				LoadTeamView();	
			});	
            UTILS.compileDustTemplates();

            setTimeout(() => {
                const /**string*/ countryParam = new URL(window.location).searchParams.get('Country') || 'allCountries';
                const /**string*/ activityParam = new URL(window.location).searchParams.get('Activity') || 'allActivities';
                document
                    .querySelector('span[data-url="' + countryParam + '"]')
                    .click();
                document
                    .querySelector('span[data-url="' + activityParam + '"]')
                    .click();
                    
                $('.select .selectChoices').css('display', 'none');
                $('.select').removeClass('opened');
            }, 10);
        }
    }

    // Ouverture du select
    function openSelect(elem) {
        var visibility = (elem.find('.selectChoices').css('display') == 'block') ? 'none' : 'block';
        elem.find('.selectChoices').css('display', visibility).addClass('opened');
    }

	function LoadTeamView() {		
		var activityId = $('#activity').val();
		var national = $('#pays').val();
		Web_TeamOverview.getTeams(UTILS.universId, UTILS.language, UTILS.country,UTILS.universName,activityId, national,function(result, event){     //PARAMS: universId, languagecode, country,isGlobal,activityId,nationality		
			if(event.status){
				$('#teamContainer').html(''); 
				$.map( result, function( val, i ) {
					val.activityName = $('.select .selectChoices span[data-id="' + val.Id + '"]').html();
				});
                result.sort(function(){return 0.5 - Math.random()});
				UTILS.dustRender('tmpl_teamItem',result, $('#teamContainer'));
				
			}
		},{escape:false});	
	}

    /**
     * Initialisation
     */
    init();
});
