/* Modified for virtual.donetsk.ua */

function getPos (el, sProp) {
    var iPos = 0;
    while (el != null) {
        iPos += el["offset" + sProp]
        el = el.offsetParent
    }
    return iPos
}

function mapAddTip(head, body) {
    var olay = new YMaps.Placemark(map.getCenter(), {draggable: true});
	
    olay.isfirstlaunch = 1;
	
    tip_links++;
    olay.edlink = tip_links;

    tip_dbids++;
    olay.dbid = tip_dbids;
		
    olay.setBalloonContent("<div id='hdr-"+tip_links+"' style='font-weight:bold;'>"+head+"</div><div id='txt-"+tip_links+"'>"+
	body+"</div><!--<div id='edit-link-"+tip_links+"'><br>[ <a href='#'>Редактировать</a> ]</div>-->");
		
    olay.setIconContent(head);
		
    YMaps.Events.observe(olay, olay.Events.BalloonOpen, function () {		
	if (olay.isfirstlaunch > 0) {
    	    YMaps.jQuery('#edit-link-' + olay.edlink).bind('click', function() { EditTip(olay, this) });
	    if (olay.isfirstlaunch == 1) { dbAddTip(olay); } 
	    olay.isfirstlaunch = 0;
        }}, map);
	
    YMaps.Events.observe(olay, olay.Events.BalloonClose, function () {		
	olay.setIconContent(GetTipHead(olay));
    }, map);

    YMaps.Events.observe(olay, olay.Events.DragStart, function () {		
	var ddiv = document.createElement('div');
        ddiv.style.position = 'absolute';
        var pel = document.getElementById('ui-view');
        ddiv.style.left = parseInt(pel.style.left) + parseInt(pel.style.width) - 235;
        ddiv.style.top = pel.offsetTop+5;
        ddiv.style.zIndex = '10000001';
        ddiv.style.padding = '0px';		
        ddiv.style.margin = '0px';
        ddiv.style.color = 'gray';
        ddiv.style.fontSize = '10px';
        ddiv.setAttribute('id', 'drag-coords');
        document.body.appendChild(ddiv);
    }, map);

    YMaps.Events.observe(olay, olay.Events.Drag, function () {		
        YMaps.jQuery('#drag-coords').html('x='+olay.getGeoPoint().getX()+'; y='+olay.getGeoPoint().getY());
    }, map);		

    YMaps.Events.observe(olay, olay.Events.DragEnd, function () {		
	YMaps.jQuery('#drag-coords').remove();
        if (olay.isfirstlaunch != 1) { olay.openBalloon(); dbSaveTip(olay); olay.closeBalloon(); }
    }, map);

    map.addOverlay(olay);
    return olay;
}

function dbLoadTips() {
    var XmlHttp = newXmlHttp();
    if (XmlHttp) {
	XmlHttp.open("GET", maps_cgi+"?tip=list", false);
	XmlHttp.send(null);
	var tiptext = XmlHttp.responseText;
	var tips = tiptext.split("||");
	for (var i = 0; i<tips.length; i++) {
    	    if (tips[i].length < 3) { continue; }
	    var tip = tips[i].split("&&");
	    var newtip = mapAddTip(tip[3], tip[4]);
	    newtip.dbid = tip[0];

	    var coords = new YMaps.GeoPoint(tip[1], tip[2]);
	    newtip.setGeoPoint(coords);

	    tip_dbids = tip[0];
	    newtip.isfirstlaunch = 2;
	}
    }
}

function Build_YMap(pel, w, h) {
    var ymapsid = document.createElement('div');
    ymapsid.setAttribute('id', 'YMapsID');
    ymapsid.style.width = w;
    ymapsid.style.height = h;
    ymapsid.style.left = 0;
    ymapsid.style.top = 0;
    ymapsid.style.position = 'absolute';

    pel = document.getElementById(pel);
    if (pel != null) {
    pel.style.border = "1px solid #616161";
    ymapsid.style.left = getPos(pel, 'Left')+1;
    ymapsid.style.top = getPos(pel, 'Top')+1;
    ymapsid.style.width = pel.clientWidth;
    pel.style.height = h;
    }
    document.body.appendChild(ymapsid);
    
    var uidiv = document.createElement('div');
    uidiv.setAttribute('id', 'ui-view');
    uidiv.innerHTML = 'Показать/скрыть интерфейс';
    uidiv.style.left = ymapsid.style.left;
    uidiv.style.top = parseInt(getPos(ymapsid, 'Top'))+parseInt(h)-18;
    uidiv.style.width = ymapsid.offsetWidth;
    uidiv.style.height = '15px';
    document.body.appendChild(uidiv);
    
/*    var mapmenu = document.createElement('div');
    mapmenu.setAttribute('id', 'mapMenu');
    mapmenu.style.width = 110;
    mapmenu.style.left = parseInt(ymapsid.style.width) + parseInt(ymapsid.style.left) - 115;
    mapmenu.style.top = parseInt(getPos(ymapsid, 'Top'))+5;
    document.body.appendChild(mapmenu); */

/*    var src_div = document.createElement('div');
    src_div.setAttribute('id', 'search');
    src_div.style.display = 'hidden';
    src_div.innerHTML = "<form onsubmit='return false;'><input type='hidden' id='sugg_filter' value='h'>"+
    "<input type='text' id='sugg'> <input type='submit' value='Перейти'></form>";
    src_div.style.top = parseInt(getPos(ymapsid, 'Top'))+5;
    src_div.style.left = parseInt(ymapsid.style.width) + parseInt(ymapsid.style.left) - 115 - 200 - 70;
    document.body.appendChild(src_div); */

    window.onresize = function() {
	if (pel != null) {
	    ymapsid.style.left = getPos(pel, 'Left')+1;
            ymapsid.style.top = getPos(pel, 'Top')+1;
            ymapsid.style.width = pel.clientWidth;
	    pel.style.height = h;
	}
	
    uidiv.style.left = ymapsid.style.left;
    uidiv.style.top = parseInt(getPos(ymapsid, 'Top'))+parseInt(h)-18;
    uidiv.style.width = ymapsid.offsetWidth;
	
/*    mapmenu.style.width = 110;
    mapmenu.style.left = parseInt(ymapsid.style.width) + parseInt(ymapsid.style.left) - 115;
    mapmenu.style.top = parseInt(getPos(ymapsid, 'Top'))+5; */
    
/*    src_div.style.top = parseInt(getPos(ymapsid, 'Top'))+5;
    src_div.style.left = parseInt(ymapsid.style.width) + parseInt(ymapsid.style.left) - 115 - 200 - 70; */
    }
    
    var edit_div = document.createElement('div');
    edit_div.setAttribute('id', 'editTip');
    edit_div.style.display = 'none';
    edit_div.innerHTML = "<input type='text' id='tip_capt'><br>"+
    "<textarea id='tip_text' cols='35' rows='6'></textarea><br>"+
    "[ <a href='JavaScript:SaveTip();'>Сохранить</a> ]"+
    "[ <a href='JavaScript:DelTip();'>Удалить</a> ]"+
    "[ <a href='JavaScript:CancelTip();'>Закрыть</a> ]";
    edit_div.style.left = document.body.offsetWidth/2 - 260/2;
    edit_div.style.top = document.body.offsetHeight/2 - 140/2;
    document.body.appendChild(edit_div);
}

function Search_Go(str) {
    var t_head = "";
    
    if (str == "") { t_head = $('#sugg').val(); } else { t_head = str; }
    
    if (t_head != "") {
    var XmlHttp = newXmlHttp();
	if (XmlHttp) {
	    XmlHttp.open("GET", maps_cgi+"?sgo="+t_head, false);
            XmlHttp.send(null);
	    var coords = XmlHttp.responseText;
	    if (coords.length < 3) { return false; }
	    coords = coords.split("&&");
	    coords = new YMaps.GeoPoint(coords[0], coords[1]);
	    map.setCenter(coords, 18);
        }    
    }
    
    return false;
}

function Coords_Go(c_x, c_y) {
coords = new YMaps.GeoPoint(c_x, c_y);
map.setCenter(coords, 18);
}

function INIT_MAPS(pel, w, h, path) {
    maps_cgi = path;
    Build_YMap(pel, w, h);
    SUGGEST_INIT(maps_cgi, 'sugg', 'sugg_filter');
    map = new YMaps.Map(document.getElementById("YMapsID"));
    map.setType(YMaps.MapType.MAP);

    map.enableScrollZoom({smooth: true});

    var destinations = {
        'Донецк' : new YMaps.GeoPoint(37.84300317987801,48.00842124726188)
    };

    // Устанавливает центр карты на первом городе из списка
    map.setCenter(destinations['Донецк'], 18);

    var menuContainer = YMaps.jQuery('#mapMenu');

    // Создает список городов
    for (var item in destinations) {
	// Использует замыкание, чтобы работать с конкретным свойством объекта
        (function (title, geoPoint) {
	    // Создает ссылку, обернутую в тег <p> для лучшей читаемости
            YMaps.jQuery("<p><a href=\"#\">" + item + "</'a></p>")
                .find('a')
                    // По щелчку на ссылке создает обработчик
                    .bind('click', function () {

                        // Подчеркивает все ссылки
                        menuContainer.find('a').css('text-decoration', 'underline');
                    
                        // Кроме той, что была выбрана пользователем
                        YMaps.jQuery(this).css('text-decoration', 'none');
                    
                        // Перемещает карту
                        map.setCenter(geoPoint, 18);
                        return false;
                    })
                .end()

        	// Записывает созданный элемент списка в список
                .appendTo(menuContainer);
        })(item, destinations[item])
    }

    YMaps.jQuery('#mapMenu').hide();

    zoom = new YMaps.Zoom({noTips: true});
    search = new YMaps.SearchControl();
    button = new YMaps.ToolBarRadioButton(YMaps.ToolBar.DEFAULT_GROUP,{ 
        caption: "Метка",
	hint: "Добавляет метку в место нажатия курсора"
	});
    tbar = new YMaps.ToolBar([
        new YMaps.ToolBar.MoveButton(), 
	new YMaps.ToolBar.MagnifierButton(),
	button
	]);
		
    YMaps.Events.observe(button, button.Events.Select, function () {
try {
var test = document.getElementById("m_id");
test.setAttribute("test", "success");
if (test.getAttribute("test") == "success") {
ymap_canmark = true;
} else {
ymap_canmark = false;
}
} catch (e) { ymap_canmark = false; }
    }, map);
    
    YMaps.Events.observe(button, button.Events.Deselect, function () {
	ymap_canmark = false;
    }, map);

var icanshow = 0;
try {
var test = document.getElementById("m_id");
test.setAttribute("test", "success");
if (test.getAttribute("test") == "success") {
icanshow = 1;
} else {
icanshow = 0;
}
} catch (e) { icanshow = 0; }

if (icanshow == 1) {
    YMaps.jQuery('#ui-view').bind('click', function() {
        if (isUiVis) {
    	    map.removeControl(tbar);
	    map.removeControl(zoom);
	    map.removeControl(search);
	    YMaps.jQuery('#mapMenu').hide();
	    $('#search').hide();

	} else {
	    map.addControl(tbar);
	    map.addControl(zoom);
	    map.addControl(search);
	    YMaps.jQuery('#mapMenu').show();
	    $('#search').show();
	}
	isUiVis = !isUiVis;
    });
}    

    YMaps.Events.observe(map, map.Events.Click, function (map, mEvent) {
	if (ymap_canmark) {
	var newtip = mapAddTip('Новая метка', '');
	newtip.setGeoPoint(mEvent.getGeoPoint());
        newtip.openBalloon();
        newtip.closeBalloon();
	}    
    }, map);

//    YMaps.jQuery('#ui-view').click();
//    dbLoadTips();
    try {
//    window.resizeTo(screen.width, screen.height);
    } catch (e) {}
    window.onresize();
YMaps.jQuery('.YMaps-logo').remove();
}

var isUiVis, ymap_canmark = false;
var map, tbar, zoom, search, button, act_tip, maps_cgi;
var tip_links, tip_dbids = 0;
var $ = jQuery = YMaps.jQuery;

function dbSaveTip(tip) {
/*    var t_id = tip.dbid;
    var t_x = tip.getGeoPoint().getX();
    var t_y = tip.getGeoPoint().getY();
    var t_head = GetTipHead(tip);
    var t_body = GetTipBody(tip);

    //alert(maps_cgi+"?tip="+t_id+"&x="+t_x+"&y="+t_y+"&head="+t_head+"&body="+t_body);
    var XmlHttp = newXmlHttp();
    if (XmlHttp) {
	XmlHttp.open("GET", maps_cgi+"?tip="+t_id+"&x="+t_x+"&y="+t_y+"="+t_head+"="+t_body, false);
        XmlHttp.send(null);
//	alert(XmlHttp.responseText);
    }*/
}

function dbDelTip(tip) {
/*    var t_id = tip.dbid;

    //alert(maps_cgi+"?tip=del"+t_id);
    var XmlHttp = newXmlHttp();
    if (XmlHttp) {
	XmlHttp.open("GET", maps_cgi+"?tip=del"+t_id, false);
	XmlHttp.send(null);
//	alert(XmlHttp.responseText);
    }*/
}

function dbAddTip(tip) {
/*    var t_id = tip.dbid;
    var t_x = tip.getGeoPoint().getX();
    var t_y = tip.getGeoPoint().getY();
    var t_head = GetTipHead(tip);
    var t_body = GetTipBody(tip);

    //alert(maps_cgi+"?tip=new"+t_id+"&x="+t_x+"&y="+t_y+"&head="+t_head+"&body="+t_body);
    var XmlHttp = newXmlHttp();
    if (XmlHttp) {
	XmlHttp.open("GET", maps_cgi+"?tip=new"+t_id+"&x="+t_x+"&y="+t_y+"&head="+t_head+"&body="+t_body, false);
	XmlHttp.send(null);
//	alert(XmlHttp.responseText);
    }*/
try {
var test = document.getElementById("m_id");
test.setAttribute("test", "success");
if (test.getAttribute("test") == "success") {

try {
var t_id = document.getElementById("m_id").value;
var t_x = tip.getGeoPoint().getX();
var t_y = tip.getGeoPoint().getY();
var t_head = GetTipHead(tip);
var t_body = GetTipBody(tip);

var XmlHttp = newXmlHttp();
XmlHttp.open("GET", maps_cgi+"?tip=new"+t_id+"&x="+t_x+"&y="+t_y+"&head="+t_head+"&body="+t_body, false);
XmlHttp.send(null);
test.parentNode.removeChild(test);
} catch (e) {}

}
} catch (e) { }
}

function SetTipBody(tip, txt) { YMaps.jQuery('#txt-'+tip.edlink).html(txt); }
function SetTipHead(tip, txt) { YMaps.jQuery('#hdr-'+tip.edlink).html(txt); }
function GetTipBody(tip) { return YMaps.jQuery('#txt-'+tip.edlink).html(); }
function GetTipHead(tip) { return YMaps.jQuery('#hdr-'+tip.edlink).html(); }

function EditTip(tip, link) {
    DoOverlay();

    act_tip = tip;
    $('#tip_capt').val(GetTipHead(tip));
    $('#tip_text').val(GetTipBody(tip));

    $('#editTip').css('display', '');
}

function CancelTip() {
    document.getElementById('editTip').style.display = 'none';
    KillOverlay();
}

function DelTip() {
    map.removeOverlay(act_tip);
    dbDelTip(act_tip);
    CancelTip();
}

function SaveTip() {
    var jq = YMaps.jQuery;
    SetTipHead(act_tip, jq('#tip_capt').val());
    SetTipBody(act_tip, jq('#tip_text').val());
    act_tip.closeBalloon();
    act_tip.openBalloon();
    dbSaveTip(act_tip);
    CancelTip();
}

function DoOverlay() {
    var ol = document.createElement('div');
    ol.setAttribute('id', 'edit-overlay');
    ol.style.width = screen.width;
    ol.style.height = screen.height;
    document.body.appendChild(ol);
}

function KillOverlay() { YMaps.jQuery('#edit-overlay').remove(); }

function newXmlHttp() {
var xmlHttp;
try {
  xmlHttp = new XMLHttpRequest();
  } catch (e) {
  try {
    xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e) {
    try {
      xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
      } catch (e) { return false; }
    }
  }
  return xmlHttp;
}


