function createRequest() {
  try {
    request = new XMLHttpRequest();
  } catch (trymicrosoft) {
    try {
      request = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (othermicrosoft) {
      try {
        request = new ActiveXObject("Microsoft.XMLHTTP");
      } catch (failed) {
        request = false;
      }
    }
  }

//  if (!request) alert("Error initializing XMLHttpRequest!");
}

function sendRequest(cat, id, lng, lat) {
  var url = 'http://'+server_name+'/setgeo.php?cat='+cat+'&id='+id+'&lng='+lng+'&lat='+lat;
  if (!request) createRequest();

//alert(1);
  request.open("GET", url, true);
//alert(2);
  request.send(null);
//  alert(url);
}


function markInfo(id, address, text) {
  var res='<div class="balloon">'+address.replace('Россия, Москва, ', '')+'<br />'+text;
  if (!onWindow) res+='<div class="ballon_a"><a href="http://www.domokrat.ru/seek.php?cat=sd&id='+id+'" target="_blank">Подробности</a></div>';
  res+='</div>';
  return(res);
}


function addMarkPrim(mark, id, address, text, flag) {
  var s=markInfo(id, address, text);
  mark.setStyle('custom#redPoint');
  mark.setBalloonContent(s);
  mark.setHintContent(flag);
  mark.name=flag;
//	mark.tip = "i";i = "Всплывающая подсказка к ПЕРВОЙ (цифровое имя балуна) точке на карте";
  s=address.replace('Россия, ', '').replace('Москва, ', '')+'<br />'+text;
	mark.tip = s;
//  mark.setBalloonContent(address);
  map.addOverlay(mark);
  return(mark);
}


function addMarkReq(id, address, text, flag) {
  // Запускаем процесс геокодирования
  var geocoder = new YMaps.Geocoder(address, {results: 1, boundedBy: map.getBounds()});
    
  YMaps.Events.observe(geocoder, geocoder.Events.Load, function () {
  //Если поиск прошел без ошибок и найден хотя бы один результат
    var mark, info;
    if (this.length()) { 
    // Добавляем оверлей на карту
      mark=this.get(0);
      var lng=mark.getGeoPoint().getLng();
      var lat=mark.getGeoPoint().getLat();
      sendRequest('sd', id, lng, lat);
      mark=addMarkPrim(mark, id, mark.text, text, flag);
    }
  });

/* */
  YMaps.Events.observe(geocoder, geocoder.Events.Fault, function (error) {
    //alert("Произошла ошибка: " + error.message)
  });
/* */
}

function addMarkNow(id, address, text, flag, lng, lat) {
  var point = new YMaps.GeoPoint(lng, lat);
  var mark = new YMaps.Placemark(point); 
  mark.name=flag;
  mark=addMarkPrim(mark, id, address, text, flag);
}

function addMarks() {

  for(var i=0; i<sd.length; i++) {
    if (sd[i].lng>0 && sd[i].lat>0) {addMarkNow(sd[i].id, sd[i].addr, sd[i].text, sd[i].flag, sd[i].lng, sd[i].lat);}
    else {addMarkReq(sd[i].id, sd[i].addr, sd[i].text, sd[i].flag);}
  }
}

function init() {
  var ctrl;
  
  inittip();
  
  map = new YMaps.Map( document.getElementById("YMapsID") );
  map.setCenter(new YMaps.GeoPoint(37.64,55.76 ), 10, YMaps.MapType.MAP);

  map.addControl(new YMaps.ToolBar());
  map.addControl(new YMaps.Zoom());
  map.addControl(new YMaps.MiniMap(3));
  map.addControl(new YMaps.ScaleLine());
  
  var s = new YMaps.Style();
  s.iconStyle = new YMaps.IconStyle("custom#redPointIcon");
  s.iconStyle.offset = new YMaps.Point(0, -20);
  s.iconStyle.href = "http://domokrat.ru/img/sd-flg-00.png";
  s.iconStyle.size = new YMaps.Point(20, 20);
  s.iconStyle.hasHint = true;

  YMaps.Styles.add("custom#redPoint", s);
  
  var t = new YMaps.Template();
  t.text = '<div onMouseover="ddrivetip(\'$[tip]\');" onMouseout="hideddrivetip();"><img style="height:$[style.iconStyle.size.y];width:$[style.iconStyle.size.x]"; src="$[style.iconStyle.href]"/><div class="CustomPointName">$[name]</div></div>';
  YMaps.Templates.add("custom#redPointIcon", t);

  addMarks();

return;
}


function initSingle() {
  var ctrl;
  var lng=0, lat=0;
  
  inittip();

  for (var i=0; i<sd.length; i++) {
    if (lng==0 && lat==0) {lng=sd[i].lng; lat=sd[i].lat;}
    else {lng=(lng+sd[i].lng)/2; lat=(lat+sd[i].lat)/2;}
  }  
  map = new YMaps.Map( document.getElementById("YMapsID") );
  map.setCenter(new YMaps.GeoPoint(lng, lat), 15, YMaps.MapType.MAP);

  map.addControl(new YMaps.ToolBar());
  map.addControl(new YMaps.Zoom());
  map.addControl(new YMaps.MiniMap(3));
  map.addControl(new YMaps.ScaleLine());
  
  var s = new YMaps.Style();
  s.iconStyle = new YMaps.IconStyle("custom#redPointIcon");
  s.iconStyle.offset = new YMaps.Point(0, -20);
  s.iconStyle.href = "http://domokrat.ru/img/sd-flg-00.png";
  s.iconStyle.size = new YMaps.Point(20, 20);
  s.iconStyle.hasHint = true;

  YMaps.Styles.add("custom#redPoint", s);
  
  var t = new YMaps.Template();
  t.text = '<div onMouseover="ddrivetip(\'$[tip]\');" onMouseout="hideddrivetip();"><img style="height:$[style.iconStyle.size.y];width:$[style.iconStyle.size.x]"; src="$[style.iconStyle.href]"/><div class="CustomPointName">$[name]</div></div>';
  YMaps.Templates.add("custom#redPointIcon", t);

  onWindow=true;
  addMarks();

return;
}

/***********************************************
* Cool DHTML tooltip script- © Dynamic Drive DHTML code library (www.dynamicdrive.com)
* This notice MUST stay intact for legal use
* Visit Dynamic Drive at http://www.dynamicdrive.com/ for full source code
***********************************************/


var offsetxpoint=-60 //Customize x offset of tooltip
var offsetypoint=20 //Customize y offset of tooltip
var ie=true;
var ns6=false;
var enabletip=false;
var tipobj=false;
var onWindow=false;

function inittip() {
  ie=document.all?true:false;
  ns6=document.getElementById && !ie;
  if (ie||ns6)
    tipobj=document.all? document.all["flagtooltip"] : document.getElementById? document.getElementById("flagtooltip") : "";
  document.onmousemove=positiontip
}

function ietruebody(){
  return (document.compatMode && document.compatMode!="BackCompat")? document.documentElement : document.body
}

function ddrivetip(thetext, thecolor, thewidth){
  if (ns6||ie){
    if (typeof thewidth!="undefined") tipobj.style.width=thewidth+"px"
    if (typeof thecolor!="undefined" && thecolor!="") tipobj.style.backgroundColor=thecolor
    tipobj.innerHTML=thetext
    enabletip=true
    return false
  }
}

function positiontip(e){
  if (enabletip){
    var curX=(ns6)?e.pageX : event.clientX+ietruebody().scrollLeft;
    var curY=(ns6)?e.pageY : event.clientY+ietruebody().scrollTop;
    //Find out how close the mouse is to the corner of the window
    var rightedge=ie&&!window.opera? ietruebody().clientWidth-event.clientX-offsetxpoint : window.innerWidth-e.clientX-offsetxpoint-20
    var bottomedge=ie&&!window.opera? ietruebody().clientHeight-event.clientY-offsetypoint : window.innerHeight-e.clientY-offsetypoint-20

    var leftedge=(offsetxpoint<0)? offsetxpoint*(-1) : -1000

    //if the horizontal distance isn't enough to accomodate the width of the context menu
    if (rightedge<tipobj.offsetWidth)
    //move the horizontal position of the menu to the left by it's width
    tipobj.style.left=ie? ietruebody().scrollLeft+event.clientX-tipobj.offsetWidth+"px" : window.pageXOffset+e.clientX-tipobj.offsetWidth+"px"
  else if (curX<leftedge)
    tipobj.style.left="5px"
  else
    //position the horizontal position of the menu where the mouse is positioned
    tipobj.style.left=curX+offsetxpoint+"px"

    //same concept with the vertical position
  if (bottomedge<tipobj.offsetHeight)
    tipobj.style.top=ie? ietruebody().scrollTop+event.clientY-tipobj.offsetHeight-offsetypoint+"px" : window.pageYOffset+e.clientY-tipobj.offsetHeight-offsetypoint+"px"
  else
    tipobj.style.top=curY+offsetypoint+"px"
  tipobj.style.visibility="visible"
  }
}

function hideddrivetip(){
  if (ns6||ie){
    enabletip=false
    tipobj.style.visibility="hidden"
    tipobj.style.left="-1000px"
    tipobj.style.backgroundColor=''
    tipobj.style.width=''
  }
}

