function saveUrl(name) {
  document.cookie = name + "=" + escape(document.location.href);
}

function getCookie(c_name) {
  if (document.cookie.length>0) {
    c_start=document.cookie.indexOf(c_name + "=");
    if (c_start!=-1) {
      c_start=c_start + c_name.length+1;
      c_end=document.cookie.indexOf(";",c_start);
      if (c_end==-1) c_end=document.cookie.length;
      return unescape(document.cookie.substring(c_start,c_end));
      }
    }
  return "";
}

$(function() {
  $.datepicker.setDefaults($.extend({
		numberOfMonths: 1,
		showButtonPanel: true,
		gotoCurrent: true,
    // dateFormat: 'dd.mm.yy',
		showAnim: 'show',
		showOn: 'both', 
		buttonImage: '/site_media/images/calendar.gif', 
		buttonImageOnly: true,
		minDate: +1,
		changeMonth: true,
		duration: '',
		firstDay: 1
	}, $.datepicker.regional[lang == 'en' ? '' : lang]));
  // $('.datepicker').datepicker();

	$('input[type=text]#id_basic-from_date').datepicker({
    dateFormat: 'dd.mm.yy',
    onSelect: function(dateText, inst) {
      var min_date = new Date(inst.selectedYear, inst.selectedMonth, inst.selectedDay);
      min_date.setDate(min_date.getDate() + 1);
      $('#id_basic-to_date').datepicker('option', 'minDate', min_date);
      var to_date = new Date(inst.selectedYear, inst.selectedMonth, inst.selectedDay);
      to_date.setDate(to_date.getDate() + 7);
      $('#id_basic-to_date').datepicker('setDate', to_date);
    }
  });
	$('input[type=text]#id_basic-to_date').datepicker({
    dateFormat: 'dd.mm.yy'
  });
	$('input[type=text]#id_from_date').datepicker({
    dateFormat: 'dd.mm.yy'
  });
	
	function toggle_children_inputs(num) {
    $('.child_container').hide();
    $('.child_container select').attr('disabled', 'disabled');
    for (var i=0; i < num; i++) {
      $('#child_'+i+'_container').show();
      $('#child_'+i+'_container select').attr('disabled', '');
    };
	}
	$('#id_basic-num_children').each(function() {
    toggle_children_inputs($(this).val());
  });
	$('#id_basic-num_children').change(function() {
    toggle_children_inputs($(this).val());
  });
  
  function booking_prices_update(amount, tax) {
    $('#booking_prices_total').html(format_currency(to_num($('#booking_prices_total').html()) + amount)).effect('highlight');
    $('#booking_prices_tax').html(format_currency(to_num($('#booking_prices_tax').html()) + tax)).effect('highlight');
    $('#booking_prices_subtotal').html(format_currency(to_num($('#booking_prices_subtotal').html()) + amount-tax)).effect('highlight');
  }
  
  function add_price_row(service_id, dict) {
    el = $(tmpl('row_template', dict));
    $('#booking_prices').append(el);
    booking_prices_update(to_num(dict.amount)*dict.quantity, to_num(dict.tax_amount)*dict.quantity);
    el.effect('highlight');
  }
  
  function remove_price_rows(service_id) {
    $('#'+service_id+"_row").each(function() {
      var amount = to_num($('.amount', this).html());
      var tax_amount = to_num($('.tax_amount', this).html());
      var quantity = $('.services_qty', this).html()*1 * $('.services_num', this).html()*1;
      booking_prices_update(-amount, -quantity*tax_amount);
      $(this).remove();
    });
  }
  
  $('.optional_service').change(function() {
    var el = $(this);
    var v;
    if (el.attr('type') == 'checkbox') {
      v = el.attr('checked') ? 1 : 0;
    } else {
      v = el.val();
    }
    var el_id = el.attr('id');
    remove_price_rows(el_id);
    if (v > 0) {
      add_price_row(el_id, {
         id: el_id,
         service: $('#'+el_id+'_service').html(), 
         amount: $('#'+el_id+'_total').html(), 
         services_qty: 1, 
         services_num: v, 
         quantity: v,
         tax_name: $('#'+el_id+'_tax_name').html(), 
         tax_amount: $('#'+el_id+'_tax_amount').html() 
      });
    }
  });
  
  $('.service_group_tables').each(function() {
    // size tables equally
    var max_width = 0;
    $('table', $(this)).each(function() {
      max_width = Math.max(max_width, $(this).width());
    });
    $('table', $(this)).css('width', max_width);
  });
  
  // order by
  $('#order-by-condition').change(function() {
    var form = $(this).parents('form')[0]
    form.action += "&order_by=" + $(this).val();
    window.location = form.action;
    // form.submit();
  });
  
  // tabs
  $("#tabs").tabs();
  
  function replace_options(el, options_arr) {
    el.children('option:gt(0)').remove();
    $.each(options_arr, function() {
      el.append('<option value="' + this[0] + '">' + this[1] + '</option>');
    });
    el.attr('disabled', '');
  }
  
  function disable_select(el) {
  }
  
  // ajax update select boxes in search
  $('#id_country_id').change(function() {
    $.getJSON("/" + lang + "/locations/regions_and_places/" + $(this).val() + "/", function(data) {
      replace_options($('#id_region_id').attr('disabled', 'disabled'), data['regions']);
      replace_options($('#id_city_id').attr('disabled', 'disabled'), data['places']);
    });
  });
  $('#id_region_id').change(function() {
    var v = $(this).val() || $('#id_country_id').val();
    $.getJSON("/" + lang + "/locations/regions_and_places/" + v + "/", function(data) {
      replace_options($('#id_city_id').attr('disabled', 'disabled'), data['places']);
    });
  });
  $('#id_accomodation_type_id').change(function() {
    $.getJSON("/" + lang + "/accomodation_unit_list_types/" + $(this).val(), function(data) {
      replace_options($('#id_accomodation_unit_type_id').attr('disabled', 'disabled'), data['result']);
    });
  });

  $('#language-selection-select').change(function() {
    window.location=$(this).val();
  });
  
  var result_backlink = $('#results_backlink');
  if (result_backlink.size() > 0) {
    url = getCookie('search');
    if (url != "") {
      $('a', result_backlink).attr('href', url);
      result_backlink.show();
    }
  }

});

