function initKorzina(){
  function korzinaShow(){
  $('.mKorzina .bd').show();
  $('.mKorzina .bd').animate({marginRight:'0'},1000, function(){ $('.mKorzina .krest').show() });
  }
  function korzinaHide(){
  $('.mKorzina .krest').hide();
  $('.mKorzina .bd').animate({marginRight:'-252px'},1000, function(){ $('.mKorzina .bd').hide() });
  }
  $('.mKorzina .tgl').click(function(){
  if ($('.mKorzina .krest').css('display') == 'none') korzinaShow();
  else korzinaHide();
  });
  $('.mKorzina .krest').click(korzinaHide);
}

function initSite(){
  $('.cSendForm input')
    .focus(function(){
      $(this).parent().css('background-position','0 -40px');
      if ($(this).val() == $(this).attr('rel')) $(this).val('');
      $(this).removeClass('void');
    })
    .blur(function(){
      $(this).parent().css('background-position','0 0');
      if (($(this).val() == '') && $(this).attr('rel')) $(this).val( $(this).attr('rel') ).addClass('void');
    });
  $('.cSendForm textarea')
    .focus(function(){
      $(this).parent().css('background-position','0 -280px');
      if ($(this).val() == $(this).attr('rel')) $(this).val('');
      $(this).removeClass('void');
    })
    .blur(function(){
      $(this).parent().css('background-position','0 -80px');
      if (($(this).val() == '') && $(this).attr('rel')) $(this).val( $(this).attr('rel') ).addClass('void');
    });
  
  $('.cSendForm .row').click(function(){
    $(this).find('textarea, input').focus();
  });
  
  $('.cSendForm input, .cSendForm textarea').each(function(){
    if (($(this).val() == '') && $(this).attr('rel')) $(this).val( $(this).attr('rel') ).addClass('void');
  });
  
  $('.mSearch .txt input')
    .focus(function(){
      if ($(this).val() == $(this).attr('rel')) $(this).val('');
      $(this).removeClass('void');
    })
    .blur(function(){
      if (($(this).val() == '') && $(this).attr('rel')) $(this).val( $(this).attr('rel') ).addClass('void');
    })
	.blur();
  $('.postloadedB').show();
}

function formaNewStart(param){
  $('.cSendForm .toggleDiv').hide();
  rel = $('.cSendForm h2').attr('rel');
  $('.cSendForm h2').attr('rel',  $('.cSendForm h2').text() );
  $('.cSendForm h2').text(rel).wrapInner('<a href="#"></a>');
  $('.cSendForm h2 a').click(function(){
    rel = $('.cSendForm h2').attr('rel');
    txt = $('.cSendForm h2 a').text();
    if ($('.cSendForm .toggleDiv').css('display') == 'none'){
      $('.cSendForm .toggleDiv').slideDown();
    } else {
      $('.cSendForm .toggleDiv').slideUp();
    }
    $('.cSendForm h2').attr('rel',txt);
    $('.cSendForm h2 a').text(rel);
    return false;
  });
  if (param) {
    $('.cSendForm h2 a').click();
  }
}


function setAgreement(idComplaint, agree, notAgree, delLink, agreeText, disagreeText) {
  var sum = agree*1 - notAgree*1;
  var naTxt = "Нажмите сюда, если ответ показался вам неисчерпывающим, чтобы указать врачам и прочим комментирующим пользователям на необходимость дополнения. Также думают: ";
  var aTxt = "Нажмите сюда, если хотите выразить благодарность врачу за ответ. Также думают: ";
  if (sum == 0){
    $('#'+idComplaint).removeClass('green').removeClass('red').find('th').text(sum);
  } else if (sum > 0){
    $('#'+idComplaint).removeClass('red').addClass('green').find('th').text('+'+sum);
  } else {
    $('#'+idComplaint).removeClass('green').addClass('red').find('th').text(sum);
  }
  $('#'+idComplaint+' td:eq(0) a').attr('title',naTxt+notAgree);
  $('#'+idComplaint+' td:eq(1)').attr('title',aTxt+agree);
  if (delLink){
    if (agreeText == '') $('#'+idComplaint+' td:eq(0)').attr('title','Также думают: '+notAgree).find('a').after( $('#'+idComplaint+' td:eq(0) a').text()).remove();
  else $('#'+idComplaint+' td:eq(0)').attr('title','Также думают: '+notAgree).find('a').after( $('#'+idComplaint+' td:eq(0) a').text()).remove();
    if (disagreeText == '') $('#'+idComplaint+' td:eq(1)').attr('title','Также думают: '+agree).find('a').after( $('#'+idComplaint+' td:eq(1) a').text()).remove();
  else $('#'+idComplaint+' td:eq(1)').attr('title','Также думают: '+agree).find('a').after( $('#'+idComplaint+' td:eq(1) a').text()).remove();
  }
}




function catalogStart(){
  //$('#cCatalog h3 a').click(function(){catalogActive($(this)); return false;});
  //$('#cCatalog h3 a.cur').click();
  $('.cCatalog').append('<table class="separator"><tr><td class="lft"></td><td class="rgt"></td></tr></table>');
  var i = 0;
  $('.cCatalog h3').each(function(){
    $(this).appendTo('.cCatalog .separator .lft').attr('rel', 'category'+i);
	i++;
  });
  i = 0;
  $('.cCatalog ul').each(function(){
    $(this).appendTo('.cCatalog .separator .rgt').attr('id', 'category'+i).hide();
	i++;
  });
  $('.cCatalog .item').remove();
  
  $('.cCatalog h3').click(function(){
    $('.cCatalog h3.act').html( '<a href="#">'+$('.cCatalog h3.act').html()+'</a>' ).removeClass('act');
	catalogActive($(this));
	return false;
  });
  
  catalogActive( $('.cCatalog h3.cur') );
}
function catalogActive(el){
  el.addClass('act').html( el.find('a').html() );
  var v = $('.cCatalog .separator .rgt ul:visible');
  if (v.length > 0){
    $('.cCatalog .separator .rgt ul:visible').fadeOut('fast', function(){
      $('#'+el.attr('rel')).fadeIn();
    });
  } else $('#'+el.attr('rel')).fadeIn();
}

/*function mapLinkBind(){
  $('.cFirmAddr').each(function(){
	var firm = $(this);
	firm.find('.mapLink').click(function(){
      firm.find('.yandexMap').slideToggle();
      var altTxt = $(this).attr('rel');
      $(this).attr('rel',$(this).text());
      $(this).text(altTxt);
      return false;
    })
  })
}*/

//Работа с Yandex-картами
var map;
map = new Array();

function showAddress(latitude, longitude, strAddress, i) {
    if (typeof(map[i]) == "undefined") {
        map[i] = new YMaps.Map(document.getElementById("YMapsContainer"+i));
        map[i].addControl(new YMaps.ToolBar()); //панель инструментов с кнопками, позволяющими перемещать карту, увеличивать ее, а также измерять расстояние на карте с помощью специальной линейки
        map[i].addControl(new YMaps.Zoom()); //элемент масштабирования, который позволяет менять разрешение карты с определенным шагом
        map[i].addControl(new YMaps.ScaleLine()); //элемент карты "Масштабная линейка" (scale line), позволяющий измерять расстояние между объектами, не прибегая к вычислениям

	    var geocoder = new YMaps.Geocoder(new YMaps.GeoPoint(latitude, longitude), {results: 1, boundedBy: map[i].getBounds()});
	    YMaps.Events.observe(geocoder, geocoder.Events.Load, function () {
	        if (this.length()) {
	            //map.addOverlay(this.get(0));
	            map[i].panTo(this.get(0).getGeoPoint());
	            
	            //Вид балуна
	            var t = new YMaps.Template('<div style="color:#0A0;">$[description]</div>');
	            YMaps.Templates.add("point#template", t);
	
	            var s = new YMaps.Style();
	            s.balloonContentStyle = new YMaps.BalloonContentStyle("point#template");
	
	            //Создание метки в точке с заданными географическими координатами
	            var placemark = new YMaps.Placemark(new YMaps.GeoPoint(latitude, longitude), {style: s});
	            
                if (this.get(0).precision != "exact") {
                	//alert(this.get(0).precision);
                    //В случае, если адрес приблизительный, выводим его, а не тот, который искали
	                var obj = this.get(0).AddressDetails["Country"]["AdministrativeArea"]["Locality"]["Thoroughfare"];
	                var ulica = obj["ThoroughfareName"];
	                var dom = obj["Premise"]["PremiseNumber"];
	                strAddress = ulica + ", " + dom;
                }
	            
	            placemark.description = strAddress;
	            map[i].addOverlay(placemark);
	            placemark.openBalloon();
	            map[i].getBalloon().setOptions({hasCloseButton: false});
	            //
	            
	            var maxZoom = map[i].getMaxZoom();
	            var myZoom = (maxZoom > 20) ? 20 : maxZoom;
	            map[i].setZoom(myZoom);
	        } else {
	            //alert("не найдено")
	        }
	    });

	    YMaps.Events.observe(geocoder, geocoder.Events.Fault, function (geocoder, error) {
	        //alert("Произошла ошибка: " + error);
	    });
    }
}

function mapLinkBind(latitude, longitude, strAddress, i){
	if (typeof(map[i]) == "undefined") showAddress(latitude, longitude, strAddress, i);
	
    var firm = $("#YMapsContainer"+i).parent();
    var a = firm.find('.mapLink');
    
    firm.find('.yandexMap').toggle();
    var altTxt = a.attr('rel');
    a.attr('rel', a.text());
    a.text(altTxt);
}

function showDoctorRating(){
  arrCons=[];
  $('#byABCList').hide();

  if ($('#byConsultsList').length != 0){
    $("#byConsultsList").show();
  } else {
    DoctorListDiv=$('<div class="cDoctorList" id="byConsultsList"></div>');
    $(".contMainRight").append(DoctorListDiv);
    $('#byABCList .docDescTable tr:last-child td:last-child').each(function () {
      arrCons.push(parseInt($(this).text()));
    }); 

           
    items=$(".contMainRight .item").get(); 
          
    for (var k=0; k<arrCons.length-1; k++){
      for (var i=0; i<((arrCons.length-1)-k); i++){  
        if (arrCons[i]<arrCons[i+1]){
          tmp=arrCons[i];
          arrCons[i]=arrCons[i+1];
          arrCons[i+1]=tmp;
                    
          buff=items[i];
          items[i]=items[i+1];
          items[i+1]=buff;
        }; 
      };
    };
             
            
            

    for (var i=0; i<items.length; i++){
      var newDl=$('<dl class="item"></dl>');             
      var clear=$('<div style="clear:both"></div>');
      newDl.appendTo(DoctorListDiv);
      $(items[i].innerHTML).appendTo(newDl);
      newDl.append( clear );
      $("#byConsultsList .docDescTable").remove();
      newTd=$('.contMainRight #byConsultsList table td:last-child').eq(i);
      newTd.append('<p>Консультаций: '+arrCons[i]+'</p>');
      for (var j=0; j<arrCons[i]; j++) {   
        var newSq=$('<div class="sq"></div>');
        $(newSq).clone().appendTo(newTd); 
      }
    }
  };
  $('#byConsults').attr('disabled','disabled');
  $('#byABC').attr('disabled','');
};   

function hideDoctorRating() {
  $('#byConsultsList').hide();
  $("#byABCList").show();

  $('#byConsults').attr('disabled','');
  $('#byABC').attr('disabled','disabled');
}