var startmyscript;
$(function() {
  startRequestEvent();
  $("#event_block_switcher").click(function () {
      $("#event_block_details").toggle();
  });
  $("a[rel^=popup]").click(function () {
    $size = $(this).attr('rel').substring(6).split('x');
    PopUp($size[0], $size[1], $(this).attr('target')||'_blank', $(this).attr('href'));
    return false;
  });
  $("h2[id], h3[id]").each(function () {$(this).before("<span id=\"link_"+this.id+"\" class=\"header_link\" title=\"Получить ссылку на этот раздел страницы.\">(ссылка)</span>");});
  $("#event_block_switcher a").click(function () {$("#event_block_switcher").click(); return false;});
  /*$(".display_href").click(function () {prompt('Ниже дана ссылка на выбраное сообщение:', this.href); return false;});*/
  $(".header_link").click(function () {
    if (location.href.indexOf("#") != -1) {
      url = location.href.substring(0, location.href.indexOf("#"));
    } else {
      url = location.href;
    }
    prompt("Скопируйте ссылку на этот раздел страницы.", url+"#"+this.id.substring(5));
  });
  $("[rel^='#hint_']").cluetip({
    clickThrough: true,
    local:true,
    width: '320',
    positionBy: 'mouse',
    cluetipClass: 'jtip',
    sticky: true,
    closeText: '',
    showTitle: false,
    mouseOutClose: true,
    fx: {open: 'fadeIn', openSpeed: 'fast'},
    hoverIntent: {interval: 200},
    onShow: hint_prepare
  });
  $("[rel^=/]").cluetip({
    clickThrough: true,
    width: '320',
    positionBy: 'mouse',
    cluetipClass: 'jtip',
    sticky: true,
    closeText: '',
    showTitle: false,
    mouseOutClose: true,
    fx: {open: 'fadeIn', openSpeed: 'fast'},
    hoverIntent: {interval: 200},
    onShow: hint_prepare
  });
  $("#side_right").append("<a href=\"#\" id=\"lnk_print\" class=\"link_lite\">Распечатать страницу</a>");
  $("#lnk_print").click(function () {
    $("body").html($("#blk_path").html() + $("#blk_body").html()).css("margin", "1em");
    window.print();
    return false;
  });
  Geoloc.init();
});

function hint_prepare (link, tip) {
  if (!person_id || $('input', tip).val() == '[p'+person_id+']')
    $('.fop', tip).remove();
}

function PopUp(width, height, name, url) {
  if (!url) url = "about:blank";
  var settingi = "top=50,left=50,titlebar=no,toolbar=0,width="+width+",height="+height+",scrollbars=1,resize=1,resizable=1";
  open(url, name, settingi);
}
function in_array(chto, gde) {
  for (var i = 0; i < gde.length; i++)
    if (chto == gde[i]) return true;
  return false;
}

function delElement(id) {
  elem = document.getElementById(id);
  elem.parentNode.removeChild(elem);
}
function htmlspecialchars (text) {
  text = text.replace(/\&/g, "&amp;");
  text = text.replace(/\"/g, "&quot;");
  text = text.replace(/\'/g, "&#039");
  text = text.replace(/</g, "&lt;");
  text = text.replace(/>/g, "&gt;");
  return text;
}
function nl2br (text) {
  text = text.replace(/\r?\n/g, "<br />\n");
  return text;
}
function bb2html (text) {
  text = text.replace(/^\s*(=)\s+(.+?)\s+\1\s*/mgi, "<h1>$2</h1>");
  text = text.replace(/^\s*(==)\s+(.+?)\s+\1\s*/mgi, "<h2>$2</h2>");
  text = text.replace(/^\s*(===)\s+(.+?)\s+\1\s*/mgi, "<h3>$2</h3>");
  text = text.replace(/\[b\](.+?)\[\/b\]/mgi, "<b>$1</b>");
  text = text.replace(/\[s\](.+?)\[\/s\]/mgi, "<s>$1</s>");
  text = text.replace(/\[u\](.+?)\[\/u\]/mgi, "<u>$1</u>");
  text = text.replace(/\[i\](.+?)\[\/i\]/mgi, "<i>$1</i>");
  text = text.replace(/\[color=([\#a-z0-9]+?)\](.+?)\[\/color\]/mgi, "<span style=\"color: $1\">$2</span>");
  text = text.replace(/\[quote\](.+?)\[\/quote\]/mgi, "<blockquote>$1</blockquote>");
  return text;
}
function printVersion() {
  if (document.getElementById) var page_body = document.getElementById("page_body");
  else if (document.all) var page_body = document.all("page_body");
  var settingi = "top=50,left=50,titlebar=no,menubar=1,toolbar=0,width=600,height=500,scrollbars=1,resize=1,resizable=1";
  print_win = open("about:blank", "print_win", settingi);
  print_win.document.write(page_body.innerHTML);
  print_win.document.title = window.document.title;
  print_win.print();
  return false;
}

var reqev_timer;
function startRequestEvent() {
  reqev_timer = window.setInterval("requestEvent();", 1000*60);
}
function requestEvent() {
  $.getJSON("/sys/interface/", {act: 'ping'}, function (data) {
    if (data.stoped) window.clearInterval(reqev_timer);
  });
}

function getPageEventCoords (evt) {
  var coords = {left: 0, top: 0};
  if (evt.pageX) {
    coords.left = evt.pageX;
    coords.top  = evt.pageY;
  } else if (evt.clientX) {
    coords.left = evt.clientX + document.body.scrollLeft - document.body.clientLeft;
    coords.top  = evt.clientY + document.body.scrollTop  - document.body.clientTop;
    if (document.body.parentElement && document.body.parentElement.clientLeft) {
      var bodParent = document.body.parentElement;
      coords.left += bodParent.scrollLeft - bodParent.clientLeft;
      coords.top  += bodParent.scrollTop  - bodParent.clientTop;
    }
  }
  return coords;
}

$(function () {$("body").append("<div id=\"dbsMain\" style=\"display: none;\"><table id=\"dbsHeader\"><tr><td id=\"dbsHeaderName\">Поиск и выбор </td><td align=\"right\"><a href=\"#\" onclick=\"DBS.hide(); return false;\"><img src=\"/i/ic_close_win.png\" alt=\"X\" title=\"Закрыть\" width=\"16\" height=\"14\" border=\"0\" /></a></td></tr></table><form onsubmit=\"return(DBS.search())\"><table class=\"dbsForm\"><tr><td width=\"1%\">Искать:</td><td width=\"98%\"><input name=\"substr\" id=\"dbsSearchSubstr\" /></td><td width=\"1%\"><input type=\"submit\" value=\"&gt;&gt;\" id=\"dbsSearchButton\" /></td></tr></table></form><div id=\"dbsContent\">Загрузка...</div></div>");});
DBS = {
  strWait: "Загрузка...", // Фраза в процессе загрузки
  strNotfound: "Ни чего не найдено.", // Фраза в случае нулевого результата
  result_function: false, // Функция обратного вызова
  id2name: false, // База ответа с сервера
  mode: false, // База ответа с сервера

  show: function (evt, mode, result_function) {
    this.mode = mode;
    this.result_function = result_function;
    name = "Поиск и выбор ";
    if (mode == "dog") name += "собаки";
    else if (mode == "person") name += "персоны";
    else if (mode == "exib") name += "выставки";
    $("#dbsHeaderName").text(name);
    evt = (evt) ? evt : ((event ? event : null));
    if (evt) {
      var coords = getPageEventCoords(evt);
      $("#dbsMain").css({"left": coords.left+"px", "top": coords.top +"px", "display": "block"});
      this.search();
    }
    return false;
  },
  hide: function () {
    $("#dbsMain").css("display", "none");
    $("#dbsContent").html(this.strWait);
    $("#dbsSearchSubstr").val("");
    return false;
  },
  search: function () {
    //  Блокирование формы
    $("#dbsSearchSubstr").attr("disabled", "disabled");
    $("#dbsSearchButton").attr("disabled", "disabled");
    $("#dbsContent").html(this.strWait);
    //  Отправка запроса
    $.getJSON("/sys/interface/", {act: 'dbs_'+DBS.mode, substr: $("#dbsSearchSubstr").val()}, function (data) {
      DBS.response(data);
    });
    return false;
  },
  response: function (resp) {
    this.id2name = resp.result_list;
    $("#dbsSearchButton").attr("disabled", "");
    $("#dbsSearchSubstr").attr("disabled", "").focus();
    if (resp.result_count) {
      $("#dbsContent").html("");
      for (var id in this.id2name) {
        $("#dbsContent").append(this.getLine(id));
      }
    } else {
      $("#dbsContent").html(DBS.strNotfound);
    }
  },
  result: function (id) {
    this.hide();
    if (typeof this.result_function == "function") {
      this.result_function(id, this.id2name[id]);
    } else if (document.getElementById(this.result_function)) {
      code = "d";
      if (this.mode == "person") code = "p";
      if (typeof replaceSelectedText == "function")
        replaceSelectedText(document.getElementById(this.result_function), function (t) {return "["+code+id+"]";});
      else
        document.getElementById(this.result_function).value += "["+code+id+"]";
    }
  },
  getLine: function (id) {
    var ret = "";
    ret += "<div class=\"dbsLine\" onclick=\"DBS.result("+id+"); return false;\">";
    ret += this.id2name[id].link;
    ret += "<br />\n";
    ret += "ID: "+id;
    if (this.id2name[id].pedigree_number)
      ret += ", "+this.id2name[id].pedigree_number;
    ret += "</div>\n";
    return ret;
  }
}
WinDogSearch    = {show:function(evt,result_function){DBS.show(evt,'dog',result_function);return false;}}
WinPersonSearch = {show:function(evt,result_function){DBS.show(evt,'person',result_function);return false;}}

// Еспресс-респект
function setRespect(person_id, vote) {
  if (!person_id) return false;
  if (!vote) return false;
  $.getJSON("/sys/interface/", {act: 'respect_set', ajax: 'yes', 'person_id': person_id, 'vote': vote}, function (data) {
    if (data.status == 'ok') {
      alert("Ваш респект принят.");
    }
  });
  return false;
}

// MiniChat
minichat_last_msg_id  = 0;
minichat_last_put_msg = 0;
/*
$(function () {
  if (minichat_last_msg_id) {
    window.realplexor = new Dklab_Realplexor('http://rpl.newfs.ru/', 'bp'+SITE_ID+'_');    
    realplexor.subscribe('chat', function(data, id){
      alert(data);
      if (data.mode == 'message') {
        $('<div></div>').addClass('minichat_msg').attr('id', 'minichat_msg_'+data.id).html(data.html).appendTo('#minichat_msg_box');
      }
    });
    realplexor.execute();
  }
});
*/
function minichat_loadnew() {
  //return false;
  $.getJSON("/sys/interface/", {act: 'minichat_load', 'last_msg_id': minichat_last_msg_id}, function (data) {
    if (data.status == 'ok') {
      minichat_add_msg(data.msg);
    }
  });
  return false;
}

function minichat_add_msg(msg) {
  var msg_box = document.getElementById("minichat_msg_box");
  for (i=0; i<msg.length; i++) {
    if (msg[i].id > minichat_last_msg_id) {
      new_msg = document.createElement("div");
      new_msg.className = "minichat_msg";
      new_msg.id = "minichat_msg_"+msg[i].id;
      new_msg.innerHTML = msg[i].html;
      msg_box.appendChild(new_msg);
      minichat_last_msg_id = msg[i].id;
    }
  }
}

function minichat_post_msg() {
  msg_field = document.getElementById("minichat_msg_filed");
  if (msg_field.value != minichat_last_put_msg) {
    $.getJSON("/sys/interface/", {act: 'minichat_put', 'last_msg_id': minichat_last_msg_id, 'message': msg_field.value}, function (data) {
      if (data.status == 'ok') {
        minichat_last_put_msg = msg_field.value;
        msg_field.value = "";
        msg_field.focus();
        minichat_add_msg(data.msg);
      }
    });
  } else {
    msg_field.value = "";
    msg_field.focus();
  }
  return false;
}

function f_alarm_send(msg_id) {
  if (confirm("Вы считаете, что данное сообщение возможно нарушает правила форума?\n(Оффтоп, грубость или иное)")) {
    $.getJSON("/forum/message/"+msg_id+"/alarm/", {ajax: 'yes'}, function (res) {
      if (res.status == "ok") {
        // Заменяем текст на ссылку
        $("#f_msg_alarm_link_block_"+msg_id).html("<b>!</b>");
        alert("Спасибо за помощь!");
      }
    });
  }
  return false;
}
function f_join_send(msg_id) {
  $.getJSON("/forum/message/"+msg_id+"/join/", {ajax: 'yes'}, function (res) {
  if (res.status == "ok") {
    // Добавляем персону в список
    var item = "<span id=\"f_msg_join_list_item_"+msg_id+"_"+res.person_id+"\">"+res.person_name+" (<a href=\"/forum/message/"+msg_id+"/join/?act=unsign\" onclick=\"return(f_join_unsign_send("+msg_id+", "+res.person_id+"))\">удалить</a>)</span>";
    if ($("#msg_"+msg_id+" .f_join_block").css("display") == "none") {
      $("#msg_"+msg_id+" .f_join_list").html(item);
      $("#msg_"+msg_id+" .f_join_block").css("display", "block");
    } else {
      $("#msg_"+msg_id+" .f_join_list").append(", "+item);
    }
    // Отключаем кнопку
    $("#msg_"+msg_id+" .f_msg_join_link_block").html("ппкс");
  }
  });
  return false;
}
function f_join_unsign_send(msg_id, person_id) {
  $.getJSON("/forum/message/"+msg_id+"/join/", {ajax: 'yes', act: 'unsign'}, function (res) {
  if (res.status == "ok") {
    // Удаляем персону из списка
    $("#f_msg_join_list_item_"+msg_id+"_"+person_id).remove();
    // Обработка запятых
    $("#msg_"+msg_id+" .f_join_list").html($("#msg_"+msg_id+" .f_join_list").html().replace(/, , /, ", ").replace(/^, /, "").replace(/,\s$/, ""));
    // Если больше подписавшихся нет, прячем блок
    if ($("#msg_"+msg_id+" .f_join_list").html().length == 0)
      $("#msg_"+msg_id+" .f_join_block").css("display", "none");
    // Включаем кнопку
    $("#msg_"+msg_id+" .f_msg_join_link_block").html("<a class=\"link_lite\" href=\"#\" onclick=\"return(f_join_send("+msg_id+"))\">ппкс</a>");
  }
  });
  return false;
}

function f_message_offtoped (msg_id) {
  chk = $('#chk_message_offtoped_'+msg_id)[0];
  chk.disabled = true;
  $.getJSON("/forum/message/"+msg_id+"/offtoped/", {ajax: 'yes', act: (chk.checked ? "mark" : "unmark")}, function (res) {
    if (res.status == "ok") {
      $('#chk_message_offtoped_'+msg_id)[0].disabled = false;
    }
  });
}

function f3_alarm_send(msg_id) {
  if (confirm("Вы считаете, что данное сообщение возможно нарушает правила форума?\n(Оффтоп, грубость или иное)")) {
    $.getJSON("/forum/message/"+msg_id+"/alarm/", {ajax: 'yes'}, function (res) {
      if (res.status == "ok") {
        // Заменяем текст на ссылку
        $("#f_msg_alarm_link_block_"+msg_id).html("<b>!</b>");
        alert("Спасибо за помощь!");
      }
    });
  }
  return false;
}
function f3_join_send(msg_id) {
  $.getJSON("/forum/message/"+msg_id+"/join/", {ajax: 'yes'}, function (res) {
  if (res.status == "ok") {
    // Добавляем персону в список
    var item = "<span id=\"f_msg_join_list_item_"+msg_id+"_"+res.person_id+"\">"+res.person_name+" (<a href=\"../message/"+msg_id+"/join/?act=unsign\" onclick=\"return(f_join_unsign_send("+msg_id+", "+res.person_id+"))\">удалить</a>)</span>";
    if ($("#msg_"+msg_id+" .f_join_block").css("display") == "none") {
      $("#msg_"+msg_id+" .f_join_list").html(item);
      $("#msg_"+msg_id+" .f_join_block").css("display", "block");
    } else {
      $("#msg_"+msg_id+" .f_join_list").append(", "+item);
    }
    // Отключаем кнопку
    $("#msg_"+msg_id+" .f_msg_join_link_block").html("ппкс");
  }
  });
  return false;
}
function f3_join_unsign_send(msg_id, person_id) {
  $.getJSON("/forum/message/"+msg_id+"/join/", {ajax: 'yes', act: 'unsign'}, function (res) {
  if (res.status == "ok") {
    // Удаляем персону из списка
    $("#f_msg_join_list_item_"+msg_id+"_"+person_id).remove();
    // Обработка запятых
    $("#msg_"+msg_id+" .f_join_list").html($("#msg_"+msg_id+" .f_join_list").html().replace(/, , /, ", ").replace(/^, /, "").replace(/,\s$/, ""));
    // Если больше подписавшихся нет, прячем блок
    if ($("#msg_"+msg_id+" .f_join_list").html().length == 0)
      $("#msg_"+msg_id+" .f_join_block").css("display", "none");
    // Включаем кнопку
    $("#msg_"+msg_id+" .f_msg_join_link_block").html("<a class=\"link_lite\" href=\"#\" onclick=\"return(f_join_send("+msg_id+"))\">ппкс</a>");
  }
  });
  return false;
}

function f3_message_offtoped (msg_id) {
  chk = $('#chk_message_offtoped_'+msg_id)[0];
  chk.disabled = true;
  $.getJSON("../message/"+msg_id+"/offtoped/", {ajax: 'yes', act: (chk.checked ? "mark" : "unmark")}, function (res) {
    if (res.status == "ok") {
      $('#chk_message_offtoped_'+msg_id)[0].disabled = false;
    }
  });
}

function f_message_offtop_show (msg_id) {
  $("#msg_"+msg_id+" .f_is_offtop").hide();
  $("#msg_"+msg_id+" .f_is_offtop_header").show();
  $("#msg_"+msg_id+" .msg_block").slideDown();
  return false;
}
//$("#f_msg_alarm_link_block_"+msg_id).html("!<span id=\"#f_msg_alarm_link_"+msg_id"\" style=\"display: none;\">"+$("#f_msg_alarm_link_block_"+msg_id).html()+"</span>");

/*****************************************************************************
                                                        BB-Editor
******************************************************************************/
function bbed_priview (bbed_id) {
    document.getElementById("bbed_preview_switcher_"  +bbed_id).style.display = "none";
    document.getElementById("bbed_preview_"+bbed_id).style.display = "block";
    bbed_make_priview(bbed_id);
}
function bbed_priview_close (bbed_id) {
    document.getElementById("bbed_preview_"  +bbed_id).style.display = "none";
    document.getElementById("bbed_preview_switcher_"  +bbed_id).style.display = "block";
}
function bbed_make_priview (bbed_id) {
  text = document.getElementById("bbed_textarea_field_" +bbed_id).value;
  text = htmlspecialchars(text);
  text = nl2br(text);
  text = bb2html(text);
  document.getElementById("bbed_preview_field_"+bbed_id).innerHTML = text;
  $.ajax({url: "/sys/interface/", dataType: 'json', data: {act: 'prepare_text', 'text': document.getElementById("bbed_textarea_field_" +bbed_id).value}, 'success': function (data) {
    if (data.status == 'ok') {
      document.getElementById("bbed_preview_field_"+bbed_id).innerHTML = data.text;
    }
  }, 'type': 'post'
  });
  return text;
}
function bbed_insert_bold(bbed_id) {
  replaceSelectedText(document.getElementById("bbed_textarea_field_" +bbed_id), function (t) {
    if (t.length == 0) {
      t = prompt("Укажите текст, который будет отображен жирно.", "жирно");
      if (typeof(t) != "string") t = "";
    }
    return "[b]"+t+"[/b]";
  });
}
function bbed_insert_italic(bbed_id) {
  replaceSelectedText(document.getElementById("bbed_textarea_field_" +bbed_id), function (t) {
    if (t.length == 0) {
      t = prompt("Укажите текст, который будет отображен курсивом.", "курсив");
      if (typeof(t) != "string") t = "";
    }
    return "[i]"+t+"[/i]";
  });
}
function bbed_insert_link(bbed_id) {
  replaceSelectedText(document.getElementById("bbed_textarea_field_" +bbed_id), function (t) {
    url = prompt("Укажите полный адрес ссылки.", "http://");
    if (typeof(url) != "string") return "";
    if (t.length == 0) {
      t = prompt("Укажите текст, который будет ссылкой.", url);
      if (typeof(t) != "string") t = url;
    }
    return "[url="+url+"]"+t+"[/url]";
  });
}
function bbed_insert_quote(bbed_id) {
  replaceSelectedText(document.getElementById("bbed_textarea_field_" +bbed_id), function (t) {
    if (t.length == 0) {
      t = prompt("Укажите цитату.", "цитата");
      if (typeof(t) != "string") t = "";
    }
    return "\n[quote]\n"+t+"\n[/quote]\n";
  });
}
function bbed_body_count_time () {window.setTimeout("bbed_body_count('"+this.id+"')", 50);}
function bbed_body_count (id) {
  var maxlength = $("#bbed_maxlength_"+id.substr(20)).attr("title");
  last = maxlength-$("#"+id).val().length;
//    if (last >= 30) $("#body_count").css("color", "");
//    else $("#body_count").css("color", "red");
  if (last <= 0) {
    last = "<b>0</b>";
    $("#"+id).val($("#"+id).val().substr(0, maxlength));
  }
  $("#bbed_maxlength_"+id.substr(20)).html(last);
}

function replaceSelectedText(obj, cbFunc) {
  obj.focus();
  if (document.selection) {
    var s = document.selection.createRange();
    s.text = cbFunc(s.text);
    s.select();
    return true;
  } else if (typeof(obj.selectionStart)=="number") {
    var start = obj.selectionStart;
    var end = obj.selectionEnd;
    var rs = cbFunc(obj.value.substr(start,end-start));
    obj.value = obj.value.substr(0,start)+rs+obj.value.substr(end);
    obj.setSelectionRange(end,end);
    return true;
  }
  return false;
}

Geoloc = {
  "map": {},
  "info": {},
  "init": function (e) {
    var _this = this;
    $(".geoloc").each(function (e) {
      _this.info[this.id] = {"top": $(this).position().top, "left": $(this).position().left, "width": $(this).width(), "height": $(this).height()};
      $(this).hide();
      $(this).after("<a href=\"#\" id=\"lnk_set_"+this.id+"\" onclick=\"return(Geoloc.open(this))\">установить координату</a>");
      if ($(this).val()) _this.bildbar(this.id);
      YMaps.load();
    });
  },
  "open": function (e) {
    main_id = e.id.substr(8);
    var _this = this;
    fld = $("#"+main_id);
    if (document.getElementById("wnd_"+main_id)) {
      $("#wnd_"+main_id).show();
        $("#search_field_"+main_id).val($("#"+main_id+"_address").val());
      if ($("#"+main_id).val()) {
        point = YMaps.GeoPoint.fromString($("#"+main_id).val());
        this.map[main_id].setCenter(point);
      }
    } else {
      // Создание карты
      $("<div id=\"wnd_"+main_id+"\" class=\"geoloc_win\"><div class=\"geoloc_win_map\" id=\"wnd_map_"+main_id+"\"></div></div>").appendTo("body").css({
        'top': (this.info[main_id].top-10)+'px', 'left': (this.info[main_id].left-7)+'px'
      }).show().
      prepend("<form onsubmit=\"return(Geoloc.search('"+main_id+"'))\"><table><tr><td class=\"geoloc_search\"><input size=\"60\" id=\"search_field_"+main_id+"\"></td><td  class=\"geoloc_button\"><input type=\"submit\" value=\"Найти\"/><input type=\"button\" value=\"Удалить\" onclick=\"return(Geoloc.del('"+main_id+"'))\" disabled=disabled id=\"btn_del_"+main_id+"\"/><input type=\"button\" value=\"Сохранить\"  onclick=\"return(Geoloc.close('"+main_id+"'))\"/><td></tr></table></form>");
      this.map[main_id] = new YMaps.Map(document.getElementById("wnd_map_"+main_id));
      this.map[main_id].addControl(new YMaps.TypeControl());
      this.map[main_id].addControl(new YMaps.SmallZoom());
      this.map[main_id].enableScrollZoom();
      $("#search_field_"+main_id).val($("#"+main_id+"_address").val());
      // Установка точки
      if ($("#"+main_id).val()) {
        this.val(main_id, $("#"+main_id).val());
        this.map[main_id].setCenter(YMaps.GeoPoint.fromString($("#"+main_id).val()), 7);
        var placemark = new YMaps.Placemark(YMaps.GeoPoint.fromString($("#"+main_id).val()), {draggable: true});
        placemark.setBalloonContent("<b>Точка</b>");
        this.map[main_id].addOverlay(placemark);
        YMaps.Events.observe(placemark, placemark.Events.Drag, function (mEvent) {
            _this.val(main_id, mEvent.getGeoPoint().toString());
        });
      } else {
        this.map[main_id].setCenter(new YMaps.GeoPoint(37.64, 55.76), 7);
      }
    }
    return false;
  },
  "close": function (main_id) {
    this.bildbar(main_id);
    $("#wnd_"+main_id).hide();
    return false;
  },
  "del": function (main_id) {
    this.val(main_id, '');
    this.close(main_id);
  },
  "search": function (main_id) {
    var _this = this;
    value = $("#search_field_"+main_id).val();
    if (!value) value = "Россия";
    // Удаляем все оверлеи
    this.map[main_id].removeAllOverlays();
    // Запускаем процесс геокодирования
    var geocoder = new YMaps.Geocoder(value, {results: 1, boundedBy: _this.map[main_id].getBounds()});

    YMaps.Events.observe(geocoder, geocoder.Events.Load, function () {
    //Если поиск прошел без ошибок и найден хотя бы один результат
      if (this.length()) {
        placemark = this.get(0);
        // Добавляем оверлей на карту
        placemark.setOptions({draggable: true});
        _this.map[main_id].addOverlay(placemark);
        placemark.setBalloonContent("<b>Точка</b>");
        // Открываем балун
        //placemark.openBalloon();
        _this.map[main_id].setCenter(placemark.getGeoPoint());
        _this.val(main_id, placemark.getGeoPoint().toString());
        YMaps.Events.observe(placemark, placemark.Events.Drag, function (mEvent) {
          _this.val(main_id, mEvent.getGeoPoint().toString());
        });
      }else {
        alert("Ничего не найдено")
      }
    });
    // Если при геокодировании произошла ошибка, то сообщаем о ней
    YMaps.Events.observe(geocoder, geocoder.Events.Fault,
    function (error) {alert("Произошла ошибка: " + error.message)});
    return false;
  },
  "val": function (main_id, value) {
    $("#"+main_id).val(value);
    if (value == '') {
      this.map[main_id].removeAllOverlays();
      $('#btn_del_'+main_id).attr("disabled", "disabled");
    } else {
      $('#btn_del_'+main_id).attr("disabled", "");
    }
  },
  "bildbar": function (main_id) {
    var coord = $("#"+main_id).val();
    if (coord)
      $('#lnk_set_'+main_id).html("<img src=\"http://static-maps.yandex.ru/1.x/?ll="+coord+"&size="+this.info[main_id].width+","+this.info[main_id].height+"&z=7&l=map&pt="+coord+",pmwtm&key=APcF50kBAAAAjRyxcQIAK_25pIeTi6s228lh2RQi2hyExogAAAAAAAAAAACsRDP5-K9wvrpCUaK9odYkSbCRUQ==\" alt='координата установлена' width=\""+this.info[main_id].width+"\" height=\""+this.info[main_id].height+"\" />");
    else
      $('#lnk_set_'+main_id).text("установить координату");
  }
}

