var search_box;
var order_box;
var view_box;
var popupWin;
var search_request_active = false;
var ittour_order_id = '';

var jq = jQuery.noConflict();

function prepare_form() {
  jq('#tour_search_in_process').show();
  transparent_flash();
  var options = jq('body').data('options');
  /*
  //preload background - move to main_templates.php
  if(options.preload_bg)
    jQuery("<img>").attr("src", options.preload_bg);
  */
  document.getElementById('package_search_form').reset();
  document.getElementById('hike_search_form').reset();

  if(jq.browser.opera) { // for opera only
    jq(window).resize(function() {
      jq('.ellipsis').css('white-space', 'normal');
      jq('.tour_search_result div:eq(0)').css('width', 'auto');
      jq('.tour_search_result div:eq(0)').css('width', jq('.tour_search_result div:eq(0)').width());
      jq('.ellipsis').css('white-space', 'nowrap');
    });
  }


  jq(function()  {
    jq("#date_from").datepicker({  dateFormat: 'dd.mm.y', minDate: '+1', showAnim: ''});
    jq("#date_till").datepicker({  dateFormat: 'dd.mm.y', minDate: '+1', showAnim: ''});
    jq("#hike_date_from").datepicker({  dateFormat: 'dd.mm.y', minDate: '+1', showAnim: ''});
    jq("#hike_date_till").datepicker({  dateFormat: 'dd.mm.y', minDate: '+1', showAnim: ''});
  });

  if(jq('#hotel_list').length) {
    jq('#itt_hotel_rating_block input').click(function(){
      hotel_refresh();
    });
    jq('#region_list').change(function(){
      hotel_refresh();
    });
  }

  region_name = (jq('#region_list').length)?'#region_list':'#region';

  jq('div.ittour_order_grey_box_list_center a').live('click', show_hotel_more_info);
  
  jq('#country').change(function(){
    var hotel_rating_list  = '';
    jq('#itt_hotel_rating_block :checkbox:checked').each(function(index){
      hotel_rating_list  += jq(this).val()+' ';
    });
    jq.getJSON(options.modules_action, { 'action':'get_package_search_filtered_field'
                             , 'event_owner_level' : 1
                             , 'country_id': jq('#country').val()
                             , 'hotel_rating_id': hotel_rating_list
                             , 'tour_kind': jq('#tour_kind').val()
                             , 'tour_type' : jq('#package_search_form :radio:checked').val()
                             }
                             , function(data) {
      jq('#region_list').html(data.region);
      jq('#hotel_list').html(data.hotel);
      jq('#departure_city').html(data.departure_city);
      package_search_form_submit(true);
    });
    return false;
  });
  
  jq('#hotel_list').change(function(){
    package_search_form_submit(true);
    return false;
  });

  jq('.food_list_input').click(function(){
    package_search_form_submit(true);
  });

  jq('#adult').change(function(){
    package_search_form_submit(true);
  });

  jq('#child1_age, #child2_age, #child3_age').change(function(){
    package_search_form_submit(true);
  });

  jq('#night_from').change(function(){
    package_search_form_submit(true);
  });

  jq('#night_till').change(function(){
    package_search_form_submit(true);
  });

  jq('#price_from').change(function(){
    package_search_form_submit(true);
  });

  jq('#price_till').change(function(){
    package_search_form_submit(true);
  });

  jq('#date_from').change(function(){
    package_search_form_submit(true);
  });

  jq('#date_till').change(function(){
    package_search_form_submit(true);
  });

  jq('#departure_city').change(function(){
    package_search_form_submit(true);
  });
  
  jq('#children').change(function(e, without_instantsearch){
    jq(':input.age_small[id^="child"]').attr('disabled', 'disabled').hide();
    var child_count = jq('#children').val();
    switch(child_count) {
      case '0':
        jq('div.child_age-select').hide();
        break;
      case '3':
        jq('#child3_age').attr('disabled', '').show();
      case '2':
        jq('#child2_age').attr('disabled', '').show();
      case '1':
        jq('#child1_age').attr('disabled', '').show();
        jq('div.child_age-select').show();
        break;
    }
    if(without_instantsearch == undefined)
      package_search_form_submit(true);
  });

  jq('#tour_not_found_price_link').live('click', function(){
    jq('#package_tour_type_0').attr('checked', 'checked');
    jq('#price_from').val(1);
    jq('#price_till').val(10000);
    jq('#package_search_form .btn-search :button').click();
  });

  jq('#tour_not_found_night_link').live('click', function(){
    jq('#package_tour_type_0').attr('checked', 'checked');
    jq('#night_from').val(6);
    jq('#night_till').val(14);
    jq('#package_search_form .btn-search :button').click();
  });

  jq('#tour_not_found_hotel_rating_link').live('click', function(){
    jq('#package_tour_type_0').attr('checked', 'checked');
    jq('.hotel_rating[value="7"]').attr('checked', 'checked');
    jq('.hotel_rating[value="3"]').attr('checked', 'checked');
    jq('.hotel_rating[value="4"]').attr('checked', 'checked');
    jq('.hotel_rating[value="78"]').attr('checked', '');
    jq('.hotel_rating[value="78"]').click();
    jq('#package_search_form .btn-search :button').click();
  });

  jq('#tour_not_found_meal_link').live('click', function(){
    jq('#package_tour_type_0').attr('checked', 'checked');
    jq('.food_list_input[value="394"]').attr('checked', 'checked');
    jq('.food_list_input[value="498"]').attr('checked', 'checked');
    jq('.food_list_input[value="388"]').attr('checked', 'checked');
    jq('.food_list_input[value="512"]').attr('checked', 'checked');
    jq('.food_list_input[value="496"]').attr('checked', 'checked');
    jq('.food_list_input[value="560"]').attr('checked', '');
    jq('.food_list_input[value="560"]').click();
    jq('#package_search_form .btn-search :button').click();
  });

  jq('#tour_not_found_date_link').live('click', function(){
    jq('#package_tour_type_0').attr('checked', 'checked');
    var newDate = new Date();
    newDate.setDate(newDate.getDate() + 90);
    jq('#date_till').datepicker( "setDate" , newDate );
    jq('#package_search_form .btn-search :button').click();
  });

  jq('#hike_tour_not_found_price_link').live('click', function(){
    jq('#hike_tour_type_0').attr('checked', 'checked');
    jq('#hike_price_till').val(2000);
    jq('#hike_search_form .btn-search :button').click();
  });

  jq('#hike_tour_not_found_date_link').live('click', function(){
    jq('#hike_tour_type_0').attr('checked', 'checked');
    var newDate = new Date();
    newDate.setDate(newDate.getDate() + 90);
    jq('#hike_date_till').datepicker( "setDate" , newDate );
    jq('#hike_search_form .btn-search :button').click();
  });

  //автопоиск
  search_params = window.location.hash.toString();
  if(search_params == '') {
    search_params = '#' + jq('#module_search_query').val();
  }
  var reg = /action=([a-z_]+)/;
  var arr = reg.exec(search_params);
  if(arr)
    var action = arr[1];
  else
    var action = null;

  if(action) {

    if(action == 'hike_tour_search')
      display_hike_form();
    else
      display_package_form();

    search_params = search_params.substr(1);
    search_params = search_params.split('&');
    search_params_array = new Array();
    jq.each(search_params, function(index, value){
      param_one = value.split('=');
      var field = param_one[0];
      var value = jq.trim(param_one[1]);
      search_params_array[field] = value;
    });

    if(action == 'package_tour_search') {
      if(search_params_array['country'] != undefined){
        jq('#country').val(search_params_array['country'].split('+'));
        if(jq('#country').val() != search_params_array['country']) {
          jq('#tour_search_module').show();
          return false;
        }
      } else {
        jq('#tour_search_module').show();
        return false;
      }
      jq('.hotel_rating').attr('checked', '');
      jq('.food_list_input').attr('checked', '');
      if(search_params_array['hotel_rating'] != undefined && search_params_array['hotel_rating'])
        jq.each(search_params_array['hotel_rating'].split('+'), function(i, v) {
          jq('.hotel_rating[value="'+v+'"]').attr('checked', 'checked');
        });
      if(search_params_array['food'] != undefined && search_params_array['food'])
        jq.each(search_params_array['food'].split('+'), function(i, v) {
          jq('.food_list_input[value="'+v+'"]').attr('checked', 'checked');
        });
      if(search_params_array['adults'] != undefined && search_params_array['adults'])
        jq('#adult').val(search_params_array['adults']);
      if(search_params_array['children'] != undefined && search_params_array['children'])
        jq('#children').val(search_params_array['children']).trigger('change', true);//.change();
      if(search_params_array['child1_age'] != undefined && search_params_array['child1_age'])
        jq('#child1_age').val(search_params_array['child1_age']);
      if(search_params_array['child2_age'] != undefined && search_params_array['child2_age'])
        jq('#child2_age').val(search_params_array['child2_age']);
      if(search_params_array['child3_age'] != undefined && search_params_array['child3_age'])
        jq('#child3_age').val(search_params_array['child3_age']);
      if(search_params_array['date_from'] != undefined && search_params_array['date_from'])
        jq('#date_from').val(search_params_array['date_from']);
      if(search_params_array['date_till'] != undefined && search_params_array['date_till'])
        jq('#date_till').val(search_params_array['date_till']);
      if(search_params_array['night_from'] != undefined && search_params_array['night_from'])
        jq('#night_from').val(search_params_array['night_from']);
      if(search_params_array['night_till'] != undefined && search_params_array['night_till'])
        jq('#night_till').val(search_params_array['night_till']);
      if(search_params_array['price_from'] != undefined && search_params_array['price_from'])
        jq('#price_from').val(search_params_array['price_from'].replace(/[^\d]/g, ''));
      if(search_params_array['price_till'] != undefined && search_params_array['price_till'])
        jq('#price_till').val(search_params_array['price_till'].replace(/[^\d]/g, ''));
      if(search_params_array['items_per_page'] != undefined && search_params_array['items_per_page'])
        jq('#items_per_page' + search_params_array['items_per_page']).attr('checked', 'checked');
      if(search_params_array['package_tour_type'] != undefined && search_params_array['package_tour_type'])
        jq('#package_tour_type_'+search_params_array['package_tour_type']).attr('checked', 'checked');
      if(search_params_array['tour_kind'] != undefined && search_params_array['tour_kind'])
        jq('#tour_kind').val(search_params_array['tour_kind']);

      jq.getJSON(options.modules_action, { 'action':'get_package_search_filtered_field'
                                 , 'event_owner_level' : 0
                                 , 'country_id': jq('#country').val()
                                 , 'region_id': search_params_array['tour_kind'] != undefined?search_params_array['region'].replace(/\+/g, ' '):0
                                 , 'hotel_rating_id': search_params_array['hotel_rating'] != undefined?search_params_array['hotel_rating'].replace(/\+/g, ' '):''
                                 , 'tour_kind': jq('#tour_kind').val()
                                 , 'tour_type' : jq('#package_search_form :radio:checked').val()
                                 }
                                 , function(data) {
          jq('#country').html(data.country);
          jq('#region_list').html(data.region);
          jq('#hotel_list').html(data.hotel);
          jq('#departure_city').html(data.departure_city);

          if(search_params_array['country'])
            jq('#country').val(search_params_array['country'].split('+'));
          var no_country = false;
          if(jq('#country').val() != search_params_array['country']) {
            jq('#country').append('<option val="'+search_params_array['country']+'" id="itt_seched_country">'+search_params_array['country']+'</option>');
            jq('#country').val(search_params_array['country'].split('+'));
            no_country = true;
          }
          
          if(search_params_array['region'] != undefined && search_params_array['region'])
            jq('#region_list').val(search_params_array['region'].split('+'));
          if(search_params_array['hotel'] != undefined && search_params_array['hotel'])
            jq('#hotel_list').val(search_params_array['hotel'].split('+'));
          if(search_params_array['departure_city'] != undefined && search_params_array['departure_city'])
            jq('#departure_city').val(search_params_array['departure_city'].split('+'));
          jq('#package_search_form .btn-search :button').click();
          if(no_country) {
            jq('#itt_seched_country').remove();
          }
          jq('#tour_search_module').show();
        });
      }

      if(action == 'hike_tour_search' && search_params_array['country'] != undefined) {
        if(search_params_array['hike_date_from'] != undefined && search_params_array['hike_date_from'])
          jq('#hike_date_from').val(search_params_array['hike_date_from']);
        if(search_params_array['hike_date_till'] != undefined && search_params_array['hike_date_till'])
          jq('#hike_date_till').val(search_params_array['hike_date_till']);
        if(search_params_array['hike_price_till'] != undefined && search_params_array['hike_price_till'])
          jq('#hike_price_till').val(search_params_array['hike_price_till']);
        if(search_params_array['items_per_page'] != undefined && search_params_array['items_per_page'])
          jq('#hike_items_per_page' + search_params_array['items_per_page']).attr('checked', 'checked');
        jq.getJSON(options.modules_action, { 'action':'get_hike_search_filtered_field'
                                 , 'event_owner_level' : 0
                                 , 'country_id': search_params_array['country'].replace(/\+/g, ' ')
                                 , 'transport_id': search_params_array['transport'].replace(/\+/g, ' ')
                                 , 'city_id': search_params_array['city'].replace(/\+/g, ' ')
                                 }
                                 , function(data) {
          jq('#transport_list').html(data.transport);
          jq('#city_list').html(data.city);
          jq('#tour_city_list').html(data.tour_city);
          if(search_params_array['country'])
            jq('#country_list').val(search_params_array['country'].split('+'));
          if(search_params_array['transport'] != undefined && search_params_array['transport'])
            jq('#transport_list').val(search_params_array['transport'].split('+'));
          if(search_params_array['city'] != undefined && search_params_array['city'])
            jq('#city_list').val(search_params_array['city'].split('+'));
          if(search_params_array['tour_city'] != undefined && search_params_array['tour_city'])
            jq('#tour_city_list').val(search_params_array['tour_city'].split('+'));
          jq('#hike_search_form .btn-search :button').click();
          jq('#tour_search_module').show();
        });
      }





  } else {
    jq('#tour_search_module').show();
    package_search_form_submit(true);
  }
  jq('.module_preview_load').hide();
  jq('#tour_search_in_process_main').hide();
  //---------


}

function change_package_tour_type(tour_type) {

  var options = jq('body').data('options');

  var hotel_rating_list  = '';
  jq('#itt_hotel_rating_block :checkbox:checked').each(function(index){
    hotel_rating_list  += jq(this).val()+' ';
  });
  jq.getJSON(options.modules_action, { 'action':'get_package_search_filtered_field'
                            , 'event_owner_level' : 0
                            , 'hotel_rating_id': hotel_rating_list
                            , 'tour_type': tour_type
                            , 'tour_kind': jq('#tour_kind').val()
                            }
                            , function(data) {
    jq('#country').html(data.country);
    jq('#region_list').html(data.region);
    jq('#hotel_list').html(data.hotel);
    package_search_form_submit(true);
  });
}

function change_package_tour_kind(tour_kind) {

  var options = jq('body').data('options');

  var hotel_rating_list  = '';
  jq('#itt_hotel_rating_block :checkbox:checked').each(function(index){
    hotel_rating_list  += jq(this).val()+' ';
  });
  jq.getJSON(options.modules_action, { 'action':'get_package_search_filtered_field'
                            , 'event_owner_level' : 0
                            , 'hotel_rating_id': hotel_rating_list
                            , 'tour_type' : jq('#package_search_form :radio:checked').val()
                            , 'tour_kind': tour_kind
                            }
                            , function(data) {
    jq('#country').html(data.country);
    jq('#region_list').html(data.region);
    jq('#hotel_list').html(data.hotel);
    package_search_form_submit(true);
  });
}

function hotel_refresh(){

  var options = jq('body').data('options');

  var region_list = '';
  jq('#region_list option:selected').each(function(index){
    region_list  += jq(this).val()+' ';
  });
  var hotel_rating_list  = '';
  jq('#itt_hotel_rating_block :checkbox:checked').each(function(index){
    hotel_rating_list  += jq(this).val()+' ';
  });

  jq.getJSON(options.modules_action, { 'action':'get_package_search_filtered_field'
                           , 'event_owner_level' : 2
                           , 'country_id': jq('#country').val()
                           , 'region_id': region_list
                           , 'hotel_rating_id': hotel_rating_list
                           , 'tour_kind': jq('#tour_kind').val()
                           , 'tour_type' : jq('#package_search_form :radio:checked').val()
                           }
                           , function(data) {
    jq('#hotel_list').html(data.hotel).val(0);
    jq('#departure_city').html(data.departure_city);
    package_search_form_submit(true);
  });
}

function package_search_form_submit(presearch) {
  if(!presearch) {
    if(search_request_active)
      return false;
    search_request_active = true;
  }
  var options = jq('body').data('options');

  var hotel_rating_str  = '';
  jq('#itt_hotel_rating_block :checkbox:checked').each(function(index){
    hotel_rating_str  += jq(this).val()+' ';
  });
  jq('#hotel_rating').val(jq.trim(hotel_rating_str));
  jq('#itt_hotel_rating_block input').attr('disabled', 'disabled');

  var food_str = '';
  jq('ul.food :checkbox:checked').each(function(index){
    food_str += jq(this).val()+' ';
  });
  jq('#food').val(jq.trim(food_str));
  jq('ul.food input').attr('disabled', 'disabled');

  //if(form_type == 'extended') {
    var hotel_list_temp = jq('#hotel_list').val();
    var region_list_temp = jq('#region_list').val();
    var region_list = '';
    jq('#region_list  option:selected').each(function(index){
      if(jq(this).val() != 0) // исключаем все регионы
        region_list  += jq(this).val()+' ';
    });
    jq('#region').val(jq.trim(region_list));
    var hotel_list = '';
    jq('#hotel_list option:selected').each(function(index){
      if(jq(this).val() != 0) // исключаем все отели
        hotel_list  += jq(this).val()+' ';
    });
    jq('#hotel').val(jq.trim(hotel_list));
    jq('#hotel_list').val('');
    jq('#region_list').val('');
  //}
  if(!jq('#package_tour_type_0').length) {
    if(jq('#only_tour_with_transport:checked').length) {
      jq('#package_search_form').append('<input id="add_package_tour_type" type="hidden" name="package_tour_type" value="1" />');
    } else {
      jq('#package_search_form').append('<input id="add_package_tour_type" type="hidden" name="package_tour_type" value="0" />');
    }
  }

  var params = (jq('#package_search_form').serialize());
  
  if(jq('#add_package_tour_type').length) {
    jq('#add_package_tour_type').remove();
  }

  //var params = (jq('#package_search_form').serialize());
  //if(form_type == 'extended') {
    jq('#hotel_list').val(hotel_list_temp);
    jq('#region_list').val(region_list_temp);
  //}
  jq('#itt_hotel_rating_block input').attr('disabled', '');
  jq('ul.food input').attr('disabled', '');

  if(!presearch) {
    if(options.modules_popup_result && options.extended_search_url != ''){
      window.location = options.extended_search_url + '#' + params;
      return false;
    }

    if(options.modules_popup_result) {
      if(options.modules_popup_type == 'div') {
        if(search_box)
          jq('div.tour_search_result').parents('table.boxy-wrapper').remove();
        search_box = new Boxy('<div class="itt_main_block tour_search_result" style="text-align: center;">'+jq('#go_tour_search_caption').html()+'<br />'+jq('#please_wait_caption').html()+'<br /><img class="load_center" src="'+options.modules_url+'images/ajax_loader_circle.gif" /></div>',
                    { modal: true
                    , title: jq('#tour_search_result_caption').html()
                    //, afterHide: function(event, ui) { jq('body').css('overflow', ''); }
                    //, afterShow: function(event, ui) { jq('body').css('overflow', 'hidden'); }
                    });
      } else {
        popupWin = window.open('', '', 'status=no,width=750,height=240,scrollbars=yes,resizable=no,top=10,left='+(screen.width-800)/2);
        popupWin.document.write('<div class="window_popup" style="width: 100%; text-align: center;"><img  style="margin: 50px 0;" src="'+options.modules_url+'images/ajax_loader_circle.gif" /></div>');
        popupWin.document.close();
      }
    } else {
      jq('div.tour_search_result').html('');
      jq('.tour_load').show();
    }

    if(!options.modules_popup_result && jq('#module_search_query').val() == '') {
      // change url
      var loc = window.location.toString();
      if(loc.indexOf('#') == -1)
        window.location = loc + '#' + params;
      else
        window.location = loc.substr(0, loc.indexOf('#')) + '#' + params;
    }
  } else {
    params = params + '&instantsearch=1';
  }

  jq.getJSON(options.modules_action, params, function(data) {
    if(presearch)
      return false;
    search_request_active = false;
    if(options.modules_popup_result) {
      if(options.modules_popup_type == 'div') {
        search_box.setContent('<div class="itt_main_block tour_search_result" style="overflow: auto;">'+data.text+'</div>');
        set_poput_actual_size(search_box);
      } else {
        popupWin.document.write(data.text);
        popupWin.document.close();
      }
    } else {
      jq('div.tour_search_result').html(data.text);
      jq('.tour_load').hide();
      if(jq.browser.opera) { // for opera only
        jq('.ellipsis').css('white-space', 'normal');
        jq('.tour_search_result div:eq(0)').css('width', jq('.tour_search_result div:eq(0)').width());
        jq('.ellipsis').css('white-space', 'nowrap');
      }
      var targetOffset = jq('div.itt_title').offset().top;
      jq('html,body').animate({scrollTop: targetOffset}, 700);
    }
    return false;
  });
  return false;
}

function ajax_load(url, div_name, show_result_in_popup) {
  var options = jq('body').data('options');

  var params = url.substr( (url.indexOf( '?', 0) + 1) );
  params = params.replace(/callback=jsonp[0-9]+&/, '');
  if(show_result_in_popup) {
    if(options.modules_popup_type == 'div')
      search_box.setContent('<div class="itt_main_block tour_search_result" style="text-align: center;">'+jq('#go_tour_search_caption').html()+'<br />'+jq('#please_wait_caption').html()+'<br /><img class="load_center" src="'+options.modules_url+'images/ajax_loader_circle.gif" /></div>').center();
    else {
      window.document.write('<div class="window_popup" style="width: 100%; text-align: center;"><img  style="margin: 50px 0;" src="'+options.modules_url+'images/ajax_loader_circle.gif" /></div>');
      window.document.close();
    }
  } else {
    jq('.'+div_name).html('');
    jq('.tour_load').show();
  }

  jq.getJSON(options.modules_action, params, function(data) {
    if(show_result_in_popup) {
      if(options.modules_popup_type == 'div') {
        search_box.setContent('<div class="itt_main_block tour_search_result" style="overflow: auto;">'+data.text+'</div>');
        set_poput_actual_size(search_box);
      } else {
        window.document.write(data.text);
        window.document.close();
      }
    } else {
      jq('.'+div_name).html(data.text);
      jq('.tour_load').hide();
      if(jq.browser.opera) { // for opera only
        jq('.ellipsis').css('white-space', 'normal');
        jq('.tour_search_result div:eq(0)').css('width', jq('.tour_search_result div:eq(0)').width());
        jq('.ellipsis').css('white-space', 'nowrap');
      }
    }
    return false;
  });
  return false;
}

function display_hike_form() {
  jq('div.tour_search_result').html('');
  jq('div.extended_package_search_form').hide();
  jq('div.extended_hike_search_form').show();
  jq('#form_type_hike').val(2);
  return false;
}

function display_package_form() {
  jq('div.tour_search_result').html('');
  jq('div.extended_hike_search_form').hide();
  jq('div.extended_package_search_form').show();
  jq('#form_type_package').val(1);
  return false;
}

function hike_search_form_submit(form_type, show_result_in_popup) {
  if(search_request_active)
    return false;
  search_request_active = true;
  var options = jq('body').data('options');

  var country_list_temp = jq('#country_list').val();
  var transport_list_temp = jq('#transport_list').val();
  var city_list_temp = jq('#city_list').val();
  var tour_city_list_temp = jq('#tour_city_list').val();

  var country_list = '';
  jq('#country_list option:selected').each(function(index){
    country_list  += jq(this).val()+' ';
  });
  jq('#hike_country').val(jq.trim(country_list));
  var transport_list = '';
  jq('#transport_list option'+((jq('#transport_list').val() && jq('#transport_list').val() != 900)?':selected':'') ).each(function(index){
    if(jq(this).val() != 0)
      transport_list  += jq(this).val()+' ';
  });
  jq('#transport').val(jq.trim(transport_list));
  var city_list = '';
  jq('#city_list option'+((jq('#city_list').val() && jq('#city_list').val() != 900)?':selected':'') ).each(function(index){
    if(jq(this).val() != 0)
      city_list  += jq(this).val()+' ';
  });
  jq('#city').val(jq.trim(city_list));
  var tour_city_list = '';
  jq('#tour_city_list option'+((jq('#tour_city_list').val() && jq('#tour_city_list').val() != 900)?':selected':'') ).each(function(index){
    if(jq(this).val() != 0)
      tour_city_list  += jq(this).val()+' ';
  });
  jq('#tour_city').val(jq.trim(tour_city_list));

  jq('#country_list').val('');
  jq('#transport_list').val('');
  jq('#city_list').val('');
  jq('#tour_city_list').val('');

  var params = (jq('#hike_search_form').serializeArray());
  var params_str = (jq('#hike_search_form').serialize());
  jq('#country_list').val(country_list_temp);
  jq('#transport_list').val(transport_list_temp);
  jq('#city_list').val(city_list_temp);
  jq('#tour_city_list').val(tour_city_list_temp);

  if(show_result_in_popup && options.extended_search_url != ''){
    window.location = options.extended_search_url + '#' + params_str;
    return false;
  }

  if(show_result_in_popup) {
    if(options.modules_popup_type == 'div') {
      if(search_box)
        jq('div.tour_search_result').parents('table.boxy-wrapper').remove();
      search_box = new Boxy('<div class="itt_main_block tour_search_result" style="text-align: center;">'+jq('#go_tour_search_caption').html()+'<br />'+jq('#please_wait_caption').html()+'<br /><img class="load_center" src="'+options.modules_url+'images/ajax_loader_circle.gif" /></div>',
                  { modal: true
                  , title: jq('#tour_search_result_caption').html()
                  //, afterHide: function(event, ui) { jq('body').css('overflow', ''); }
                  //, afterShow: function(event, ui) { jq('body').css('overflow', 'hidden'); }
                  });
    } else {
      popupWin = window.open('', '', 'status=no,width=750,height=240,scrollbars=yes,resizable=no,top=10,left='+(screen.width-800)/2);
      popupWin.document.write('<div class="window_popup" style="width: 100%; text-align: center;"><img  style="margin: 50px 0;" src="'+options.modules_url+'images/ajax_loader_circle.gif" /></div>');
      popupWin.document.close();
    }
  } else {
    jq('div.tour_search_result').html('');
    jq('.tour_load').show();
  }

  if(!show_result_in_popup && jq('#module_search_query').val() == '') {
    var loc = window.location.toString();
    if(loc.indexOf('#') == -1)
      window.location = loc + '#' + params_str;
    else
      window.location = loc.substr(0, loc.indexOf('#')) + '#' + params_str;
  }

  jq.getJSON(options.modules_action, params, function(data) {
    search_request_active = false;
    if(show_result_in_popup) {
      if(options.modules_popup_type == 'div') {
        search_box.setContent('<div class="itt_main_block tour_search_result" style="overflow: auto;">'+data.text+'</div>');
        set_poput_actual_size(search_box);
      } else {
        popupWin.document.write(data.text);
        popupWin.document.close();
      }
    } else {
      jq('div.tour_search_result').html(data.text);
      jq('.tour_load').hide();
      if(jq.browser.opera) { // for opera only
        jq('.ellipsis').css('white-space', 'normal');
        jq('.tour_search_result div:eq(0)').css('width', jq('.tour_search_result div:eq(0)').width());
        jq('.ellipsis').css('white-space', 'nowrap');
      }
      var targetOffset = jq('div.itt_title').offset().top;
      jq('html,body').animate({scrollTop: targetOffset}, 700);
    }
    return false;
  });
  return false;
}

function country_list_click(){

  var options = jq('body').data('options');

  var country_list = '';
  jq('#country_list option:selected').each(function(index){
    if(jq(this).val() != 0)
      country_list  += jq(this).val()+' ';
  });
  jq.getJSON(options.modules_action, { 'action':'get_hike_search_filtered_field', 'event_owner_level' : 1, 'country_id':  jq.trim(country_list) }, function(data) {
    jq('#transport_list').html(data.transport);
    jq('#city_list').html(data.city);
    jq('#tour_city_list').html(data.tour_city);
  });
}

function transport_list_click(){

  var options = jq('body').data('options');

  var country_list = '';
  jq('#country_list option:selected').each(function(index){
    if(jq(this).val() != 0)
      country_list  += jq(this).val()+' ';
  });
  var transport_list = '';
  jq('#transport_list option:selected').each(function(index){
    if(jq(this).val() != 0)
      transport_list  += jq(this).val()+' ';
  });
  jq.getJSON(options.modules_action, { 'action':'get_hike_search_filtered_field', 'event_owner_level' : 2, 'country_id':  jq.trim(country_list), 'transport_id':  jq.trim(transport_list) }, function(data) {
    jq('#city_list').html(data.city);
    jq('#tour_city_list').html(data.tour_city);
  });
}

function city_list_click(){

  var options = jq('body').data('options');

  var country_list = '';
  jq('#country_list option:selected').each(function(index){
    if(jq(this).val() != 0)
      country_list  += jq(this).val()+' ';
  });
  var transport_list = '';
  jq('#transport_list option:selected').each(function(index){
    if(jq(this).val() != 0)
      transport_list  += jq(this).val()+' ';
  });
  var city_list = '';
  jq('#city_list option:selected').each(function(index){
    if(jq(this).val() != 0)
      city_list  += jq(this).val()+' ';
  });
  jq.getJSON(options.modules_action, { 'action':'get_hike_search_filtered_field', 'event_owner_level' : 3, 'country_id':  jq.trim(country_list), 'transport_id':  jq.trim(transport_list), 'city_id':  jq.trim(city_list) }, function(data) {
    jq('#tour_city_list').html(data.tour_city);
  });
}

function package_tour_order(tour_id) {
  var options = jq('body').data('options');
  if(options.modules_popup_type == 'div') {
    if(order_box)
      jq('div.tour_order').parents('table.boxy-wrapper').remove();
    order_box = new Boxy('<div class="itt_main_block tour_order"><img class="load_center" src="'+options.modules_url+'images/ajax_loader_circle.gif" /></div>',
                  { modal: true
                  , title: jq('#tour_order_caption').html()
                  //, afterHide: function(event, ui) { jq('body').css('overflow', ''); }
                  //, afterShow: function(event, ui) { jq('body').css('overflow', 'hidden'); }
                  });
  } else {
    orderWin = window.open('', '', 'status=no,width=750,height=240,scrollbars=yes,resizable=no,top=10,left='+(screen.width-800)/2);
    orderWin.document.write('<div class="window_popup" style="width: 100%; text-align: center;"><img  style="margin: 50px 0;" src="'+options.modules_url+'images/ajax_loader_circle.gif" /></div>');
    orderWin.document.close();
  }
  jq.getJSON(options.modules_action, { 'action':'get_package_tour_order_form', 'tour_id' : tour_id}, function(data) {
    if(options.modules_popup_type == 'div') {
      order_box.setContent('<div class="itt_main_block tour_order" style="overflow: auto;">'+data.text+'</div>');
      set_poput_actual_size(order_box, 1000);
    } else {
      orderWin.document.write(data.text);
      orderWin.document.close();
    }
    //jq('#second_name').focus();
    return false;
  });
}

function package_tour_order_submit(){
  var options = jq('body').data('options');
  var params = (jq('#package_order_form').serialize());
  var new_ittour_order_id = jq("#package_order_form input[name='tour_id']").val();
  if(ittour_order_id != new_ittour_order_id) {
    ittour_order_id = new_ittour_order_id;
    jq('.package_order_load').html('<img src="'+options.modules_url+'images/ajax_loader.gif" />');
    jq('#package_order_form :submit').hide();
    jq.getJSON(options.modules_action, params, function(data) {
      if(data.success == false) {
        alert(data.error);
      } else {
        if(options.modules_popup_type == 'div') {
          order_box.setContent(jq('#tour_order_success_message').html());
          set_poput_actual_size(order_box);
        } else {
          jq('.ittour_order_block').html(jq('#tour_order_success_message').html());
        }
      }
      ittour_order_id = '';
      return false;
    });
  }
  return false;
}

function hike_tour_order(tour_id) {
  var options = jq('body').data('options');
  if(options.modules_popup_type == 'div') {
    if(order_box)
      jq('div.tour_order').parents('table.boxy-wrapper').remove();
    order_box = new Boxy('<div class="itt_main_block tour_order"><img class="load_center" src="'+options.modules_url+'images/ajax_loader_circle.gif" /></div>',
                  { modal: true
                  , title: jq('#tour_order_caption').html()
                  //, afterHide: function(event, ui) { jq('body').css('overflow', ''); }
                  //, afterShow: function(event, ui) { jq('body').css('overflow', 'hidden'); }
                  });
  } else {
    orderWin = window.open('', '', 'status=no,width=750,height=240,scrollbars=yes,resizable=no,top=10,left='+(screen.width-800)/2);
    orderWin.document.write('<div class="window_popup" style="width: 100%; text-align: center;"><img  style="margin: 50px 0;" src="'+options.modules_url+'images/ajax_loader_circle.gif" /></div>');
    orderWin.document.close();
  }
  jq.getJSON(options.modules_action, { 'action':'get_hike_tour_order_form', 'tour_id' : tour_id }, function(data) {
    if(options.modules_popup_type == 'div') {
      order_box.setContent('<div class="itt_main_block tour_order" style="overflow: auto;">'+data.text+'</div>');
      reload_price();
    } else {
      orderWin.document.write(data.text.replace('/*%onload_custom_func%*/', 'reload_price();'));
      orderWin.document.close();
    }
    //jq('#second_name').focus();
    return false;
  });
}

function hike_tour_view(tour_id) {

  var options = jq('body').data('options');

  if(view_box)
    jq('div.tour_view').parents('table.boxy-wrapper').remove();
  view_box = new Boxy('<div class="itt_main_block tour_order"><img class="load_center" src="'+options.modules_url+'images/ajax_loader_circle.gif" /></div>',
                { modal: true
                , title: '&nbsp;'
                //, afterHide: function(event, ui) { jq('body').css('overflow', ''); }
                //, afterShow: function(event, ui) { jq('body').css('overflow', 'hidden'); }
                });
  jq.getJSON(options.modules_action, { 'action':'get_hike_tour_view', 'tour_id' : tour_id }, function(data) {
    view_box.setContent('<div class="itt_main_block tour_order" style="overflow: auto;">'+data.text+'</div>');
    set_poput_actual_size(view_box);
  });
}

function hike_tour_order_submit(){

  var options = jq('body').data('options');

  var params = (jq('#hike_order_form').serialize());
  jq('.hike_order_load').html('<img src="'+options.modules_url+'images/ajax_loader.gif" />');
  jq('#hike_order_form :submit').hide();
  jq.getJSON(options.modules_action, params, function(data) {
    jq('.hike_order_load').html('');
    jq('#hike_order_form :submit').show();
    if(data.success == false) {
      jq('.error_form').html(data.error).show();
      if(options.modules_popup_type == 'div')
        set_poput_actual_size(order_box);
    } else {
      if(options.modules_popup_type == 'div') {
        order_box.setContent(jq('#tour_order_success_message').html());
        set_poput_actual_size(order_box);
      } else {
        jq('.tour_order').html(jq('#tour_order_success_message').html());
      }
    }
    return false;
  });
  return false;
}


//hike order

function reload_price() {
  var departure_date = jq('#departure_date').val();
  if(!departure_date)
    return false;
  var departure_timestamp = Date.UTC(departure_date.substr(0, 4), departure_date.substr(5, 2)-1, departure_date.substr(8, 2), 0, 0, 0) / 1000;
  var now_timestamp = Number(new Date())/1000;
  var accomodation = jq('#accomodation').val();

  var price = offer_prices[departure_date][accomodation]['price'];
  var price_id = offer_prices[departure_date][accomodation]['price_id'];

  var offer_early_prices_str = '';
  if(offer_early_prices[departure_date]) {
    var early_price = offer_early_prices[departure_date][accomodation];
    jq.each(early_price, function(key, value) {
      if(now_timestamp < value['early_timestamp']) {
        var price_selected = '';
        offer_early_prices_str += '<input type="radio" name="price" ' + price_selected + ' value="' + value['price'] + ':' + value['price_id'] + '" />' + jq('#for_count_weeks').html().replace('$count', value['week_num']) + ': <strong class="hike_price">' + value['price'] + ' ' + currency_symbol + '</strong><br />';
      }
    });
  }
  var price_selected = 'checked="checked"';
  offer_early_prices_str += '<input ' + (offer_early_prices_str?'':'style="display: none;"') + ' type="radio" name="price" ' + price_selected + ' value="' + price + ':' + price_id + '" />' + (offer_early_prices_str?(jq('#without_prepay_message').html() + ': '):'') + '<strong class="hike_price">' + price + ' ' + currency_symbol + '</strong>';
  jq('#price').html(offer_early_prices_str);
  set_poput_actual_size(order_box);
}

function show_hide_tour_info(){
  if(jq('#hike_tour_info').css('display') == 'none') {
    jq('.hike_tour_add_info_link').html( jq('#hide_add_info_message').html() );
    jq('#hike_tour_info').show();
  } else {
    jq('.hike_tour_add_info_link').html( jq('#show_add_info_message').html() );
    jq('#hike_tour_info').hide();
  }
  return false;
}

function show_hike_description(hike_id){
  jq('div[id^="hike_description_"]').hide();
  jq('#hike_description_'+hike_id).show();
  return false;
}

function set_poput_actual_size(box, div_width) {

  if(div_width == undefined)
    div_width = 730;  

  box.resize(div_width, ''); // or 'auto'
  var size = box.getContentSize();
  h = ((jq(window).height()-80) < (size[1]))?(jq(window).height()-80):(size[1]);
  box.resize(div_width, h).center();
}

function set_window_popup_actual_size(box){
  var height = jq(box.document).find('.window_popup').height();
  height = ((screen.height-170) < height)?(screen.height-170):(height);
  box.resizeTo(760, height+80);
}

function toggle_hike_tour_add_info(el, element_id) {
  var visible = jq('#'+element_id).css('display');
  if(visible == 'none') {
    jq('#'+element_id).show();
    jq(el).parent().removeClass().addClass('itt_open_header');
    jq(el).html(jq('#hide_info_caption').html());
  } else {
    jq('#'+element_id).hide();
    jq(el).parent().removeClass().addClass('itt_close_header');
    jq(el).html(jq('#show_info_caption').html());
  }
  set_poput_actual_size(order_box);
  return false;
}

function show_hotel_more_info() {
  jq('div.ittour_order_hotel_description2').css({'height': 'auto', 'overflow': 'auto'});
  jq('p.ittour_order_more_block').hide();
  jq('div.ittour_order_hotel_description_shadow').hide();
}

function show_hotel_more_photos(btn,img) {
  show_hotel_more_info();
  jq('div#ittour_slider_panel').show();
  jq('#ittour_order_show_more_photos').hide();
  jq(btn).hide();
  jq(img).hide();
}

function input_focus(el, text) {
  if(jq.trim(jq(el).val()) == text)
    jq(el).val('');
}

function input_blur(el, text) {
if(jq.trim(jq(el).val()) == '')
    jq(el).val(text);
}

function ittour_show_down(list,btn_up, btn_duwn) {
  var next = jq(list+':visible:last').next();
  if(jq(next).html()) {
    //jq(btn_up).show();
    jq(btn_up).removeClass("ittour_hidden");
    jq(next).show();
    jq(list+':visible:first').hide();
   // alert(jq(next).next().html());
    if(!jq(next).next().html()) {
      //jq(btn_duwn).hide();
      jq(btn_duwn).addClass("ittour_hidden");
    }
  }
}

/*
 $("#target").addClass("ittour_hidden ");
$("#target").removeClass("ittour_hidden ");

*/
function ittour_show_up(list,btn_up, btn_duwn) {
  var prev = jq(list+':visible:first').prev();
  if(jq(prev).html()) {
    //jq(btn_duwn).show();
    jq(btn_duwn).removeClass("ittour_hidden");
    jq(prev).show();
    jq(list+':visible:last').hide();
    if(!jq(prev).prev().html()) {
      //jq(btn_up).hide();
      jq(btn_up).addClass("ittour_hidden");
    }
  }
}

function transparent_flash() {
  jq('embed').each(function() {
          var clone = this.cloneNode(true);
          clone.setAttribute('wmode', 'transparent');
          jq(this).before(clone);
          jq(this).remove();
  });

  jq("object").each(function (i, v) {
	var embed = jq(this).children("embed");
	if(typeof (embed.get(0)) != "undefined") {
		if(typeof (embed.get(0).outerHTML) != "undefined") {
			embed.attr("wmode", "transparent");
			jq(this.outerHTML).insertAfter(this);
			jq(this).remove();
		}
		return true;
	}

  });
}
function addToCart(id, date) {
	var exp_date = date;
	cookie = get_cookie('cart');
	var count = 0;
	
	if(cookie) {
		var arr = cookie.split(";");
		var value = '';
		var flag = true;
		var exp_date = 0;
		for(i = 0; i < arr.length; i++){
			if(arr[i]) {
				// сравниваем ИД из куки с тем который пришел
				data = arr[i].split('_');
				// если разные записываем в значение данные из куки
				if(data[0] != id) {
//					console.log('то что записываем' +data[0] + '_' + data[1] + ';');
					count++; 
					value += data[0] + '_' + data[1] + ';';
					if(data[1]*1 > exp_date*1) {
						exp_date = data[1];
//						console.log('максимальная дата' +exp_date);
					}
				} else {
					// если одинаковые то пропускаем и ставим флаг false
					flag = false;
				}
			}
		}
		//если флаг тру то дописываем ид который пришел
		if(flag) {
			count++; 
			value += id+'_'+date+';';
			if(date*1 > exp_date*1) {
				exp_date = date;
			}
//			console.log('заничение после последнее записи' +value);
		}
	} else {
		count++; 
		value = id+'_'+date+';';
	}
	console.log(jq('#'+id) + ' ' +jq('#'+id).attr('checked'));
	if(jq('#'+id).attr('checked'))
		jq('#'+id).attr('checked', true);
	else
		jq('#'+id).attr('checked', false);
	
	if(jq('#cart_count')) {
		jq('#cart_count').html(count)
	}
	set_cookie('cart', value, exp_date);
}

function set_cookie(cookie_name, value, expire) {
    var expire_date = new Date();
    
    expire_date.setDate(expire_date.getDate() + expire*1);
    document.cookie = (cookie_name + "=" + escape(value) + ((expire == null) ? "" : ";expires=" + expire_date.toGMTString()));

    return true;
}

function get_cookie(cookie_name) {
    if (document.cookie.length > 0) {
        cookie_start = document.cookie.indexOf(cookie_name + "=");
        
        if (cookie_start != -1) { 
            cookie_start = ((cookie_start + cookie_name.length) + 1); 
            cookie_end   = document.cookie.indexOf(";", cookie_start);
            
            if ( cookie_end == -1) {
                cookie_end = document.cookie.length;
            }
            
            return unescape(document.cookie.substring(cookie_start, cookie_end));
        } 
    }
    
    return false;
}

function setChecked() {
	cookie = get_cookie('cart');
	if(cookie) {
		var arr = cookie.split(";");
		var ids = Array();
		for(i = 0; i < arr.length; i++){
			if(arr[i]) {
				data = arr[i].split('_');
				ids.push(data[0]);
			}
		}
//		console.log(jq('a[class^="list_stars"]'));
		jq('input[class^="list_stars"]').each(function() {
//			console.log(this.id + '  ' +jq.inArray(this.id, ids));
			if(jq.inArray(this.id, ids) != '-1') {
				jq(this).attr('checked', true);
			}
		});
	}
	
}

function showCart() {
	 var loc = window.location.toString();
	 var ids = getCartIds();
	 if(ids != '') {
		 var url = ids.join('+');
	 } else {
		 var url = '';
	 }
	 
	 if(url != '') {
	     if(loc.indexOf('#') == -1)
	       window.location = loc + '#action=package_tour_cart&ids='+url;
	     else
	       window.location = loc.substr(0, loc.indexOf('#')) + '#action=package_tour_cart&ids='+url;
	}	
}

function getCartIds() {
	cookie = get_cookie('cart');
	if(cookie) {
		var ids = Array();
		var arr = cookie.split(";");
		for(i = 0; i < arr.length; i++){
			if(arr[i]) {
				data = arr[i].split('_');
				ids.push(data[0]);
			}
		}
		return ids;
	}
	return '';
}

function showCart() {
	var options = jq('body').data('options');

	var params = (jq('#package_search_form').serialize());
	  
	  if(jq('#add_package_tour_type').length) {
	    jq('#add_package_tour_type').remove();
	  }
	
	  
	    if(options.modules_popup_result && options.extended_search_url != ''){
	      window.location = options.extended_search_url + '#' + params;
	      return false;
	    }
	
	    if(options.modules_popup_result) {
	      if(options.modules_popup_type == 'div') {
	        if(search_box)
	          jq('div.tour_search_result').parents('table.boxy-wrapper').remove();
	        search_box = new Boxy('<div class="itt_main_block tour_search_result" style="text-align: center;">'+jq('#go_tour_search_caption').html()+'<br />'+jq('#please_wait_caption').html()+'<br /><img class="load_center" src="'+options.modules_url+'images/ajax_loader_circle.gif" /></div>',
	                    { modal: true
	                    , title: jq('#tour_search_result_caption').html()
	                    //, afterHide: function(event, ui) { jq('body').css('overflow', ''); }
	                    //, afterShow: function(event, ui) { jq('body').css('overflow', 'hidden'); }
	                    });
	      } else {
	        popupWin = window.open('', '', 'status=no,width=750,height=240,scrollbars=yes,resizable=no,top=10,left='+(screen.width-800)/2);
	        popupWin.document.write('<div class="window_popup" style="width: 100%; text-align: center;"><img  style="margin: 50px 0;" src="'+options.modules_url+'images/ajax_loader_circle.gif" /></div>');
	        popupWin.document.close();
	      }
	    } else {
	      jq('div.tour_search_result').html('');
	      jq('.tour_load').show();
	    }

	if(!options.modules_popup_result && jq('#module_search_query').val() == '') {
		 var loc = window.location.toString();
		 var ids = getCartIds();
		 if(ids != '') {
			 var url = ids.join('+');
		 } else {
			 var url = '';
		 }
		 
		 if(url != '') {
		     if(loc.indexOf('#') == -1)
		       window.location = loc + '#action=package_tour_cart&ids='+url;
		     else
		       window.location = loc.substr(0, loc.indexOf('#')) + '#action=package_tour_cart&ids='+url;
		 }	
	}

	  jq.getJSON(options.modules_action, 'action=package_tour_cart&ids='+url, function(data) {
	    search_request_active = false;
	    if(options.modules_popup_result) {
	      if(options.modules_popup_type == 'div') {
	        search_box.setContent('<div class="itt_main_block tour_search_result" style="overflow: auto;">'+data.text+'</div>');
	        set_poput_actual_size(search_box);
	      } else {
	        popupWin.document.write(data.text);
	        popupWin.document.close();
	      }
	    } else {
	      jq('div.tour_search_result').html(data.text);
	      jq('.tour_load').hide();
	      if(jq.browser.opera) { // for opera only
	        jq('.ellipsis').css('white-space', 'normal');
	        jq('.tour_search_result div:eq(0)').css('width', jq('.tour_search_result div:eq(0)').width());
	        jq('.ellipsis').css('white-space', 'nowrap');
	      }
	      var targetOffset = jq('div.itt_title').offset().top;
	      jq('html,body').animate({scrollTop: targetOffset}, 700);
	    }
	    return false;
	  });
	  return false;
}
