/*----------------------------------------------------------------------------------|  www.vdm.io  |----/
				Lmskaran 
/-------------------------------------------------------------------------------------------------------/

	@version		1.0.77
	@build			6th April, 2022
	@created		22nd July, 2020
	@package		Moojla
	@subpackage		course_search.js
	@author			Lmskaran <http://Lmskaran.com>	
	@copyright		Copyright (C) 2015. All Rights Reserved
	@license		GNU/GPL Version 2 or later - http://www.gnu.org/licenses/gpl-2.0.html
  ____  _____  _____  __  __  __      __       ___  _____  __  __  ____  _____  _  _  ____  _  _  ____ 
 (_  _)(  _  )(  _  )(  \/  )(  )    /__\     / __)(  _  )(  \/  )(  _ \(  _  )( \( )( ___)( \( )(_  _)
.-_)(   )(_)(  )(_)(  )    (  )(__  /(__)\   ( (__  )(_)(  )    (  )___/ )(_)(  )  (  )__)  )  (   )(  
\____) (_____)(_____)(_/\/\_)(____)(__)(__)   \___)(_____)(_/\/\_)(__)  (_____)(_)\_)(____)(_)\_) (__) 

/------------------------------------------------------------------------------------------------------*/

/* JS Document */

/***[JCBGUI.site_view.javascript_file.41.$$$$]***/
jQuery(document).ready(function($){

  var maxCost= Joomla.getOptions('maxCost');
  var menuid= Joomla.getOptions('menuid');
  var page= 1;
  var realPage= 1;
  var clickOnMore= false;


  $('.filter').on('click',function(){
    var name= $(this).attr('name')

    if(name == 'jform[category][]' || name== 'jform[tag][]' || name== 'jform[mid][]')
    {

      var data_value= $(this).val();
      var title= $(this).next('label').text();
      if (name == 'jform[category][]')
        var data_id= 'category-'+data_value
        else if(name== 'jform[mid][]')
          var data_id= 'mid-'+data_value
          else if(name== 'jform[tag][]')
            var data_id= 'tag-'+data_value


            if(!$(this).is(':checked'))
            {
              deleteFilterItem($('#filterItems .card-body').find('[data-id='+data_id+']'))
              return 0;
            }

    }
    else if(name == 'rangeBtn')
    {
      var minRange= $('#search form [name="jform[minRange]"]').val();
      var maxRange= $('#search form [name="jform[maxRange]"]').val();
      var title= 'قیمت از '+minRange+' تا '+maxRange+'';
      var data_id = 'rangeFilterItem';

      $('#filterItems .card-body').find('[data-id='+data_id+']').remove()
    }
    else if(name == 'text')
    {
      var data_value= $(this).next('input').val();

      if (!data_value)
      {
        $(this).next('input').focus()
        return;
      }
      var title= data_value;
      var data_id = 'textFilterItem';

      $('#filterItems .card-body').find('[data-id='+data_id+']').remove()
    }
    else if(name == 'jform[searchinmycourse]')
    {
      var data_value= $(this).val();
      var title= $(this).next('label').text();

      var data_id= 'searchinmycourse-'+data_value


      if(!$(this).is(':checked'))
      {
        deleteFilterItem($('#filterItems .card-body').find('[data-id='+data_id+']'))
        return 0;
      }
    }

    append(data_id,title)
    doFilter()
    $('#filterItems').show(0)

  })

  $(document).on('click','#filterItems .card-body .filterItem',function(){

    var data_id= $(this).attr('data-id')
    var type= data_id.split('-');
    if(type[0] == 'category' || type[0]== 'tag' || type[0]== 'mid')
    {
      $('#search form [data-id='+data_id+']').prop('checked',false);

    }
    else if(type[0] == 'rangeFilterItem')
    {
      $('#search form [name="jform[minRange]"]').val(0);
      $('#search form [name="jform[maxRange]"]').val(100);
      $('.rangeslider .range_min').text(0)
      $('.rangeslider .range_max').text(100)
    }
    else if(type[0] == 'textFilterItem')
    {
      $('#search form [data-id='+data_id+']').val('');
    }

    deleteFilterItem($(this))
  })

  $('.deleteFilterItems').on('click',function(){
    deleteFilterItem($('#filterItems .card-body .filterItem'))
  })

  function deleteFilterItem(filterItem)
  {
    filterItem.remove()
    var count=  $('#filterItems .card-body .filterItem').length
    if (count== 0)
    {
      $('#search form')[0].reset();
      $('#filterItems').hide(0)
      $('input[name="jform[minRange]"]').val()
      $('input[name="jform[maxRange]"]').val(maxCost)
      $('#courses .row').html('')
    }

    doFilter();



  }

  function doFilter()
  {

    page= realPage;
    if (!clickOnMore)
    {
      page= 1;
      $('#more').fadeIn();
    }
    else
      page++;

    var form= $('#search form');
    loading(true);
    $.ajax({
      url: 'index.php?option=com_moojla',
      data: form.serialize()+'&task=ajax.Filter&format=json&raw=true&menuid='+menuid+'&page='+page,
      type: 'POST',
      success: function(msg)
      {
        if (clickOnMore)
        {
          realPage++;
          clickOnMore= false;
          $('#courses > .row').append(msg.content)
        }
        else
        {
          realPage= 1;
          $('#courses > .row').html(msg.content)
        }

        loading(false);

        if (!msg.content)
        {
          $('#more').fadeOut();
        }
      },
      error: function(msg)
      {
        console.log(msg)
      }
    });
  }

  $('#more').click(function ()
                   {
    clickOnMore= true;
    doFilter();
  });


  function loading(flag)
  {
    if (flag)
      $('body').addClass('loading')
    else
      $('body').removeClass('loading')

  }

  $('#search form input').keydown(function (e) {
    if (e.keyCode == 13) {
      e.preventDefault()

      var data_value= $(this).val();

      if (!data_value)
      {
        $(this).focus()
        return;
      }

      var title= data_value;
      var data_id = 'textFilterItem';
      $('#filterItems .card-body').find('[data-id='+data_id+']').remove();
      doFilter();
      append(data_id,title);
      $('#filterItems').show(0);

    }
  });

  function append(data_id, title){
    $('#filterItems .card-body').append('' +
                                        '<span  data-id="'+data_id+'" class="filterItem">'+title+' ' +
                                        '<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-x" viewBox="0 0 16 16">' +
                                        '<path d="M4.646 4.646a.5.5 0 0 1 .708 0L8 7.293l2.646-2.647a.5.5 0 0 1 .708.708L8.707 8l2.647 2.646a.5.5 0 0 1-.708.708L8 8.707l-2.646 2.647a.5.5 0 0 1-.708-.708L7.293 8 4.646 5.354a.5.5 0 0 1 0-.708z"/>'+
                                        '</svg>' +
                                        ' </span>')
  }

  function addSeparator(nStr) {
    nStr += '';
    var x = nStr.split(',');
    var x1 = x[0];
    var x2 = x.length > 1 ? ',' + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
      x1 = x1.replace(rgx, '$1' + ',' + '$2');
    }
    return x1 + x2;
  }
  // <div class="rangeslider" style="direction:ltr; text-align: left;">
  //     <input class="min" name="range_1" type="range" min="0" max="100" value="0" />
  //     <input class="max" name="range_1" type="range" min="0" max="100" value="100" />
  //     <span class="range_min light left">0</span>
  //     <span class="range_max light right">100</span>
  // </div>
  function rangeInputChangeEventHandler(e){
    var rangeGroup = $(this).attr('name'),
        minBtn = $(this).parent().children('.min'),
        maxBtn = $(this).parent().children('.max'),
        range_min = $(this).parent().children('.range_min'),
        range_max = $(this).parent().children('.range_max'),
        minVal = parseInt($(minBtn).val()),
        maxVal = parseInt($(maxBtn).val()),
        origin = $(this).context.className;

    if(origin === 'min' && minVal > maxVal-5){
      $(minBtn).val(maxVal-5);
    }
    var minVal = parseInt($(minBtn).val());
    $(range_min).html(addSeparator(minVal));


    if(origin === 'max' && maxVal-5 < minVal){
      $(maxBtn).val(5+ minVal);
    }
    var maxVal = parseInt($(maxBtn).val());
    $(range_max).html(addSeparator(maxVal));
  }

  $('input[type="range"]').on( 'input', rangeInputChangeEventHandler);


  $('#sort').change(function (){

    doFilter()

  });



  function enable_checkboxes_relatedTo_QST()
  {
    const url = new URL(window.location);
    var tagid= url.searchParams.get('tag');
    var flag= false

    if (tagid)
    {
      var tag= $('[data-id=tag-'+tagid+']')
      if (tag.length)
      {
        tag.prop('checked', true);
        var title= tag.next('label').text();
        var data_id='tag-'+tagid;
        append(data_id,title);
        flag= true
      }

    }



    var categoryid= url.searchParams.get('category');
    $('[data-id=category-'+categoryid+']').prop('checked', true);

    if (categoryid)
    {
      var category= $('[data-id=category-'+categoryid+']')

      if (category.length)
      {
        category.prop('checked', true);
        var title= category.next('label').text();
        var data_id='category-'+categoryid;
        append(data_id,title);
        flag= true
      }

    }


    var muserid= url.searchParams.get('muser');
    $('[data-id=mid-'+muserid+']').prop('checked', true);

    if (muserid)
    {
      var muser= $('[data-id=mid-'+muserid+']')

      if (muser.length)
      {
        muser.prop('checked', true);
        var title= muser.next('label').text();
        var data_id='mid-'+muserid;
        append(data_id,title);
        flag= true
      }

    }

    if (flag)
      $('#filterItems').show(0);

  }
  enable_checkboxes_relatedTo_QST();



  $.each($('[data-collapse=true]'), function (){
    var target= $(this).data('target')
    $(target).slideDown(100)
  })

  $(document).on('click','[data-dropdown=true]',function (){
    var target= $(this).data('target')
    $(target).slideToggle(200)
  })







  $(".button-show-sliding").click(function() {
    $(this).toggleClass('active');
    var parent= $(this).parents('.lmskaran--course-search-card')
    parent.find('.sliding-card').toggleClass('show');
  });

  $(".button-show-item-rating").click(function() {
    $(this).toggleClass('active');
    $(".button-show-item-rating").html("امتیاز دهی");
    $(".button-show-item-rating.active").html("&#x2715");
    var parent= $(this).parents('.lmskaran--course-search-card')
    parent.find('.sliding-card-rating').toggleClass('show');
  });



  var search_course_functions = {
    'loading': loading,
    'doFilter': doFilter,
  }
  window.search_course_functions = search_course_functions;


});/***[/JCBGUI$$$$]***/
