if(typeof(vrossii.kvartira)=="undefined"){
  vrossii.kvartira=function(){};
}

vrossii.kvartira.city = 0;
(function($){
  // очищаем select
  $.fn.clearSelect = function() {
      return this.each(function(){
          if(this.tagName=='SELECT') {
              this.options.length = 0;
              $(this).attr('disabled','disabled');
          }
      });
  }
  // заполняем select
  $.fn.fillSelect = function(dataArray) {
      return this.clearSelect().each(function(){
          if(this.tagName=='SELECT') {
              var currentSelect = this;
              $.each(dataArray,function(index,data){
                  var option = new Option(data.text,data.value);
                  if($.support.cssFloat) {
                      currentSelect.add(option,null);
                  } else {
                      currentSelect.add(option);
                  }
              });
          }
      });
  }
})(jQuery);


$(document).ready(function(){

// --- Автозаполнение2 ---

function streetAutocomplete(){
$("#street_name").autocomplete("/loader.php",  {
    delay:10,
    minChars:2,
    matchSubset:1,
    autoFill:true,
    matchContains:1,
    cacheLength:10,
    selectFirst:true,
    formatItem:liFormat,
    maxItemsToShow:10,
    onItemSelect:selectItem,
    extraParams:{'cmd':'streetautocomp', 'id':$('#city').val()}
}); 
}


$("#login").autocomplete("/loader.php",  {
    delay:10,
    minChars:2,
    matchSubset:1,
    autoFill:true,
    matchContains:1,
    cacheLength:10,
    selectFirst:true,
    formatItem:liFormat,
    maxItemsToShow:10,
    onItemSelect:selectItem,
    extraParams:{'cmd':'loginautocomp'}
});



streetAutocomplete();
// --- Автозаполнение2 ---


function liFormat (row, i, num) {
    var result = row[0];  // + '<p class=qnt>' + row[1] + ' тыс.чел.</p>';
    return result;
}

function selectItem(li) {
    if( li == null ) var sValue = 'А ничего не выбрано!';
    if( !!li.extra ) var sValue = li.extra[2];
    else var sValue = li.selectValue;

}

// выбор Районов
  function adjustRegion(){
    var provinceValue = $('#province').val();
    var tmpSelect = $('#region');
    if(provinceValue.length == 0 || provinceValue<1) {
        tmpSelect.attr('disabled','disabled');
        tmpSelect.clearSelect();
    } else {
        
        $.getJSON('/loader.php',{id:provinceValue,cmd:'listregion'},function(data) { tmpSelect.fillSelect(data).attr('disabled',''); });
        adjustCity()
        adjustCRegion();
        $('#region option').each(function (){
                if($(this).val()==vrossii.kvartira.region){
                    $(this).attr('selected','yes');
                }
        });

    }
        $('#street_name').val('').attr('disabled','disabled');
  };


  // выбор Города
  function adjustCity(){
      var regionValue = $('#region').val();
      var tmpSelect = $('#city');
      $('#city').val(0);
      if(regionValue.length == 0 || regionValue<1) {
        tmpSelect.attr('disabled','disabled');
        tmpSelect.clearSelect();
    } else {
        $.getJSON('/loader.php',{id:regionValue,cmd:'listcity'},function(data) { tmpSelect.fillSelect(data).attr('disabled',''); });
        adjustCRegion();
        
    }
        $('#street_name').val('');
        

  };
// выбор улици 
  function adjustStreet(){
      var regionValue = $('#region').val();
      var cityValue = $('#city').val();
      var tmpSelect = $('#street_name');
      if(regionValue.length == 0 || cityValue.length == 0 || regionValue<1 || cityValue<1){
//          tmpSelect.attr('disabled','disabled');
      } else {
           tmpSelect.val('');
           tmpSelect.attr('disabled','');
      }
  };

//  список районов города    
   function adjustCRegion(){
      var regionValue = $('#region').val();
      var cityValue = $('#city').val();
      var tmpSelect = $('#cregion');
      if(regionValue.length == 0 || cityValue.length == 0 || regionValue<1 || cityValue<1){
          tmpSelect.attr('disabled','disabled');
          tmpSelect.clearSelect();
      } else {
              $.getJSON('/loader.php',{id:cityValue,cmd:'listcregion'},function(data) { tmpSelect.fillSelect(data).attr('disabled',''); });
              tmpSelect.attr('disabled','');
      }
   };


  $('#province').change(function(){
       adjustRegion();
  });


  $('#region').change(function(){
     adjustCity();
     adjustCRegion();


  $('#city option').each(function () {
                if($(this).val()==vrossii.kvartira.city){
                    $(this).attr('selected','yes');
                }
              });

  //$('#myLoader').css("display","block");

  });

  $('#city').change(function(){ 
            adjustStreet();
            adjustCRegion(); 
            }
        ).change(function(){
          streetAutocomplete();
         vrossii.kvartira.checkCityOther();
        });

vrossii.kvartira.checkCityOther= function(){
if($('#city').val()==-1){
    $('#ncity').attr('disabled','');
}else{
    $('#ncity').attr('disabled','disabled');
}
}

vrossii.kvartira.checkCityOther();


vrossii.kvartira.viewHouse = function(id){
    window.location.href = '/house'+id+'/';
    return false;
}




// мульти файл форма
$('#photo').MultiFile({ 
	accept:'jpg', max:3, STRING: { 
		remove:'удалить',
		file:'$file', 
		selected:'Выбраны: $file', 
		denied:'Неверный тип файла: $ext!', 
		duplicate:'Этот файл уже выбран:\n$file!' 
	} 
});		  



});


var map, geoResult;
vrossii.kvartira.showAddress = function(value) {
            document.getElementById("YMapsID").style.display='block';
            map = new YMaps.Map(document.getElementById("YMapsID"));
            map.removeOverlay(geoResult);
            var geocoder = new YMaps.Geocoder(value, {results: 1, boundedBy: map.getBounds()});

            YMaps.Events.observe(geocoder, geocoder.Events.Load, function () {
                if (this.length()) {
                    geoResult = this.get(0);
                    map.addOverlay(geoResult);
                    map.setBounds(geoResult.getBounds());

                    map.addControl(new YMaps.TypeControl());
                    map.addControl(new YMaps.ToolBar());
                    map.addControl(new YMaps.Zoom());
                    map.addControl(new YMaps.MiniMap());
                    map.addControl(new YMaps.ScaleLine())
                }else {
                    alert("Ничего не найдено")
                }
            });

}

vrossii.kvartira.city =0;
vrossii.kvartira.region = 0;
vrossii.kvartira.cregion =0;

vrossii.kvartira.viewBigPhoto=function(id, hid){
    var bp = $('#bigphoto')
    bp.load('/loader.php?cmd=viewphoto&id='+id+'&house_id='+hid);
    
}
