$( function() {

  var fields_array =  function(){
    fields = [];
    $('input[id^=mortgages_]:radio:checked, input[id^=mortgages_]:text').each(function(ix, el){
      fields.push($(el).attr('id').replace(/^mortgages_/,'').replace(/_\d+$/,'') + '=' + $(el).val());
    });
    return fields;
  };

  // mortgages table - restriction to comparison only 3
  $('#creditsBoxResultsTable :checkbox').click( function() {
    if ($('#creditsBoxResultsTable :checkbox:checked').length > 3) {
      $(this).attr('checked', false);
      $('#max-checked-to-compare').slideDown('normal');
      setTimeout( function() {
        $('#max-checked-to-compare').slideUp('normal');
      }, 3000);
    }
  });

  //sendding values to request
  
  
  $('.jqCreditRequest').click( function(event) {
    event.preventDefault();
    location.href = $(this).attr('href') + '?' + 'credit_amount=' + $('input[id$=credit_amount]').val();
    return false;
  });
   
  
  
  //sending values to details
  // fixme: to już jest niepotrzebne, teraz szczegóły oferty podajemy jako normalne linki
/*
  $('.jqCreditDetails').click( function(event) {
    event.preventDefault();
    fields = [];
    //   v to this array add more filds
    $(['#mortgages_estate_value','#mortgages_credit_amount', '#mortgages_installment_number', 'input:radio:not([id^=mortgages_market_types_id]):checked'].join(', ')).each( function(key, value) {
      fields.push($(value).attr('id').replace(/^mortgages_/, '').replace(/_\d+$/, '') + '=' + $(value).val());
    });
    location.href = $(this).attr('href') + "?" +  fields.join('&');
    return false;
  });
*/

  $('img.jqAsc, img.jqDesc').click(function(){
    fields = fields_array();
    fields.push('page='+$('#jqPage').val());
    fields.push('order=' + ($(this).hasClass('jqAsc')?1:2));
    fields.push('sort='+$(this).attr('rel'));

    location.href = '?' + fields.join('&');
    return false;
  });

  $('#max-compare-button').click(function(event)
  {
    event.preventDefault();

    // replace placeholders with form values
    var url = $(this).attr('href');
    var action = '/porownanie-kredytow/';
    var format = url.slice(url.search(action) + action.length).split('/');
    for (key in format)
    {
      var element = $('select[id*=' + format[key] + '], input[type=hidden][id*=' + format[key] + ']');
      if (element.val())
      {
        url = url.replace(format[key], element.val());
      }
    }

    // get selected offers IDs
    var offers = [];
    $('#creditsBoxResultsTable :checkbox:checked').each(function(key, value)
    {
      if (offers.length < 3)
      {
        offers.push($(value).val());
      }
      else
      {
        return;
      }
    });
    url = url.replace('offers', offers.join(','));
    document.location = url;
    return false;
  });

  // expanding and collapsing advanced filtering
//  $("#example1").jcollapser({target: '#jcollapse1', state: 'collapsed'});

  // pokazywanie/ukrywanie wyboru waluty, rodzaju rat, itd.
/*
  $('.creditBoxContent > span, .creditSearchParameter').click(function()
  {
    $('.creditSearchParameter').toggle();
    $('#searchParameters').slideToggle('normal');
  });
*/

  // wpisywanie aktywnej nazwy opcji po załadowaniu strony
  $('input[id*=currencies_id]:radio:checked, input[id*=installment_types]:radio:checked, input[id*=loan_goals]:radio:checked, input[id*=purchase_subjects]:radio:checked, input[id*=market_types]:radio:checked').each(function()
  {
    updateParameterName(this);
  });

  // wpisanie nazwy wybranej opcji pod etykietkę po zmianie opcji
  $('input[id*=currencies_id]:radio, input[id*=installment_types]:radio, input[id*=loan_goals]:radio, input[id*=purchase_subjects]:radio, input[id*=market_types]:radio').change(function()
  {
    updateParameterName(this);
    $('.creditSearchParameter').toggle();
    $('#searchParameters').slideToggle('normal');
  });
});

function updateSliderRanges(url, module)
{
  $.getJSON(url, $('input[id^=' + module + '_]:radio:checked').serialize(), function(data)
  {
    if (data.success == false)
    {
      $('#error-box p strong').html('Nie znaleziono kredytów spełniających wybrane kryteria.');
      $('#error-box').slideDown('normal');
      setTimeout(function() {$('#error-box').slideUp('normal');}, 3000);
      return false;
    }
    $.each(data.ranges, function(i, item)
    {
      slider = '#slider-' + i.replace('_', '-');
      if (typeof(item.min) != 'undefined')
      {
        $(slider).rangeslider('option', 'rangemin', item.min);
      }
      if (typeof(item.max) != 'undefined')
      {
        $(slider).rangeslider('option', 'rangemax', item.max);
      }
    });
  });
  return false;
}

function updateParameterName(element)
{
  var id = $(element).attr('id');
  var text = $('label[for=' + id  +']').text();
  var target_id = id.substr(0, id.lastIndexOf('_')) + '_selected';
  $('#' + target_id).text(text);
}
