function l(id)
{
    return document.getElementById(id);
}
function l(id)
{
    return document.getElementById(id);
}
function checkbox(elementEmulation)
{
   element = l(elementEmulation.id+"_true_checkbox");
   if(elementEmulation.className == "checkbox_bg")
   {
      elementEmulation.className = "checkbox_bgr";
      element.checked=true;
   }
    else{
      elementEmulation.className = "checkbox_bg";
      element.checked=false;
   }
}
var isPlaceLocationShown = false;
var placeLocation = null; //location of a test object
var placeLocationPoint = null;

var isUserLocationShown = false;
var userLocation = null; //location of a test object
var userLocationPoint = null;

function clearLastPlaceLocation ()
{
    if (centerMarker != null)
    {
        //map.removeOverlay (centerMarker);
        isPlaceLocationShown = false;
        centerMarker.setCoordPoint(map.getCenter());
    }
}

function clearLastUserLocation ()
{
    if (centerMarker != null)
    {
        //map.removeOverlay (centerMarker);
        isUserLocationShown = false;
        centerMarker.setCoordPoint(map.getCenter());
    }
}


function setEventPlace (placeId , placeName)
{
    if (placeId != null)
    {
        l("event_place_id").value = placeId;
        l("event_place_name").innerHTML = "<a href='"+cyburl+ "place/place-"+placeId+ "'>"+placeName+"</a>";
    }

    popup("pop_map_current_location");
}

//restore event marker after page reload
function restoreEventMarker ()
{
    var lat = l('event_lat').value;
    var lng = l('event_lng').value;

    if (lat != "" && lng != "")
    {
        userLocationPoint = new YMaps.GeoPoint (lng , lat);
        isUserLocationShown = true;
        userLocation = addUserLocationMarker(userLocationPoint , "add_event");

        map.setCenter (userLocationPoint);
        map.setZoom (14);        
    }    
}

function onDragEnd (mode)
{
    var loc = centerMarker.getGeoPoint();
    var geocoder = new YMaps.Geocoder(loc, {results: 1});

    if (l("event_lng") != null)
    {
        l("event_lng").value = centerMarker.getGeoPoint().getLng();
        l("event_lat").value = centerMarker.getGeoPoint().getLat();
    }

    YMaps.Events.observe(geocoder, geocoder.Events.Load, function (geocoder) {
        var geoResult = this.get(0);
        
        var location = getCountryCity(geoResult);

        if (geoResult) {
            if (l('nearest_address') != null)
                l('nearest_address').value = geoResult.text;

            if (mode == "add_event") {
                l("event_address").value = geoResult.text;
                l("event_place_name").innerHTML = geoResult.text;
            }

            xajax_places_at_this_address(centerMarker.getGeoPoint().getLat(), centerMarker.getGeoPoint().getLng(), mode, geoResult.text , location.country , location.city);
        }
        else
        {
            alert("Ошибка геокодирования , попробуйте через 10 минут")
        }
    });

    isUserLocationShown = true;
}

function showUserLocationOnMap (mode , currentLng , currentLat)
{
    if (mode == null)
        mode = "current_location";
    
    popup("pop_map_current_location");
    
    l('pop_map_current_location').style.top = "20px";
    l('pop_map_current_location').style.left = "20px";

    /*map.redraw(true, function ()
    {
     if ($('city_name') != null)
     {
         if ($('city_name').value != "")
         {
             panMapTo($('country_name').value + " " + $('city_name').value);
         }
     }           
    });*/
    //var isMapScrolled = false;
    if (currentLng != null) //user position is not changed
    {
        var loc = new YMaps.GeoPoint (currentLng , currentLat);
        //addUserLocationMarker (loc , mode);
        isUserLocationShown = true;

        map.redraw(true, function ()
        {
            centerMarker = new YMaps.Placemark(loc , {draggable:true});
            YMaps.Events.observe(centerMarker, centerMarker.Events.DragEnd, function () {onDragEnd(mode)});
            map.addOverlay(centerMarker);

            xajax_places_at_this_address (centerMarker.getGeoPoint().getLat() , centerMarker.getGeoPoint().getLng() , mode);

            map.setCenter (loc);
            map.setZoom (14);
        });
    }
    else
    {
        map.redraw(true, function ()
            {
             if (l('city_name') != null)
             {
                 if (l('city_name').value != "")
                 {
                     panMapTo(l('country_name').value + " " + l('city_name').value);
                 }
             }
            });
    }

    if (mode != "show_place_location")
    {        
     YMaps.Events.observe(map,map.Events.BoundsChange, function (map, mEvent)
     {
        if (centerMarker == null)
        {
            centerMarker = new YMaps.Placemark(map.getCenter() , {draggable:true});
            YMaps.Events.observe(centerMarker, centerMarker.Events.DragEnd, function () {onDragEnd(mode)});
            map.addOverlay(centerMarker);
        }
        else
        {
            if (!isUserLocationShown)
                centerMarker.setCoordPoint(map.getCenter());
        }         
     });
    }
}

//restore 
function restorePlaceMarker ()
{
    var lat = l('place_lat').value;
    var lng = l('place_lng').value;

    if (lat != "" && lng != "")
    {
        placeLocationPoint = new YMaps.GeoPoint (lng , lat);
        isPlaceLocationShown = true;
        map.setCenter (placeLocationPoint);
        map.setZoom (14);

        addPlaceLocationMarker (placeLocationPoint);
    }
}

function getCountryCity (geoResult)
{
    var result = {};
    result.city = "";
    result.country = "";

    result.country = geoResult.AddressDetails.Country.CountryName;

    if (geoResult.AddressDetails.Country.Locality != null)
        result.city = geoResult.AddressDetails.Country.Locality.LocalityName;

    if (geoResult.AddressDetails.Country.AdministrativeArea != null)
    {
        if (geoResult.AddressDetails.Country.AdministrativeArea.Locality != null)
            result.city = geoResult.AddressDetails.Country.AdministrativeArea.Locality.LocalityName;
    }

    result.text = geoResult.text;

    return result;    
}


var centerMarker =  null;

function showPlaceLocationOnMap ()
{    
    popup("pop_map_current_location");
    l('pop_map_current_location').style.top = "20px";
    l('pop_map_current_location').style.left = "20px";

     map.redraw(true, function ()
     {
         if (l('city_name') != null)
         {
             if (l('city_name').value != "")
             {
                 panMapTo(l('country_name').value + " " + l('city_name').value);
             }
         }
     });

    //map.addEventListener(BoundsChange)

    YMaps.Events.observe(map,map.Events.BoundsChange, function (map, mEvent)
    {
        if (centerMarker == null)
        {
            centerMarker = new YMaps.Placemark(map.getCenter() , {draggable:true});

            YMaps.Events.observe(centerMarker, centerMarker.Events.DragEnd, function (obj)
            {
                var loc = centerMarker.getGeoPoint();
                var geocoder = new YMaps.Geocoder(loc, {results: 1});

                YMaps.Events.observe(geocoder, geocoder.Events.Load, function (geocoder) {
                    var geoResult = this.get(0);

                    var locate = getCountryCity(geoResult);
                    var selCountry = l("country_name").options[l("country_name").selectedIndex].text;
                    var selCity = l("city_name").value;

                    if (selCountry.toLocaleLowerCase() != locate.country.toLocaleLowerCase() || selCity.toLocaleLowerCase() != locate.city.toLocaleLowerCase())
                        l("city_country_notify_div").innerHTML = "Проверьте выбор города и страны.Вы указали на карте : " + geoResult.text;

                    if (geoResult) {
                        l('place_address').value = geoResult.text;
                        l('place_address_disabled').value = geoResult.text;
                        l('nearest_address').value = geoResult.text;
                        var point = geoResult.getGeoPoint();
                        xajax_places_at_this_address(point.getLat(), point.getLng());
                    }
                    else {
                        alert("не найдено")
                    }
                });

                //addPlaceLocationMarker(loc);


                l('place_lat').value = loc.getLat();
                l('place_lng').value = loc.getLng();

                isPlaceLocationShown = true;
            });
            
            map.addOverlay(centerMarker);
        }
        else
        {
            if (!isPlaceLocationShown)
                centerMarker.setCoordPoint(map.getCenter());
        }
    });


     //map.disableDblClickZoom ();

    if (placeLocationPoint != null)
    {
        map.removeAllOverlays ();
        addPlaceLocationMarker(placeLocationPoint);
        isPlaceLocationShown = true;        
        xajax_places_at_this_address (placeLocationPoint.getLat() , placeLocationPoint.getLng() , "add_place");
        map.setCenter (placeLocationPoint);
        map.setZoom (14);
    }

     /*YMaps.Events.observe(map,map.Events.DblClick, function (map, mEvent)
     {
        if (isPlaceLocationShown == false)
        {
            //placeLocation = mEvent.getGeoPoint();
            var loc = mEvent.getGeoPoint();
            var geocoder = test YMaps.Geocoder(loc, {results: 1});
            placeLocationPoint = loc; 

                YMaps.Events.observe(geocoder, geocoder.Events.Load, function (geocoder)
                {
                    var geoResult = this.get (0);

                    var locate = getCountryCity (geoResult);
                    var selCountry  = $("country_name").options[$("country_name").selectedIndex].text;
                    var selCity  = $("city_name").value;

                    if (selCountry.toLocaleLowerCase() != locate.country.toLocaleLowerCase() || selCity.toLocaleLowerCase() != locate.city.toLocaleLowerCase())
                    $("city_country_notify_div").innerHTML = "Проверьте выбор города и страны.Вы указали на карте : " + geoResult.text;
                    
                    if (geoResult)
                    {
                        $('place_address').value = geoResult.text;
                        $('nearest_address').value =  geoResult.text;
                        var point = geoResult.getGeoPoint ();                        
                        xajax_places_at_this_address (point.getLat() , point.getLng());
                    }
                    else
                    {
                        alert("не найдено")
                    }
                });            

            addPlaceLocationMarker (loc);


            $('place_lat').value = loc.getLat ();
            $('place_lng').value = loc.getLng ();

            
            isPlaceLocationShown = true;
        }
     });*/
}


function placeHasAddress (el)
{
    if (el.checked)
        l("place_address").disabled = "disabled";
    else
        l("place_address").disabled = "";
}

function searchPlace (what)
{
    map.removeAllOverlays ();
    var bounds = map.getBounds ();
    var leftBottom = bounds.getLeftBottom() ;
    var rightTop = bounds.getRightTop ();
   
    xajax_search_place (what , leftBottom.toString() , rightTop.toString());
}

function panMapToGeoPoint (lng , lat , id)
{
    if (id != null)
    {
        var placemark = overlayReg[id];
        placemark.openBalloon();
    }
    
    var toPoint = new YMaps.GeoPoint (lng , lat);
    map.panTo(toPoint);
}

function panMapTo (address , updateBounds , callLoadMapFunction)
{    
    var geocoder = new YMaps.Geocoder(address, {results: 1, boundedBy: map.getBounds()});    

    // Создает обработчик успешного завершения геокодирования
    YMaps.Events.observe(geocoder, geocoder.Events.Load, function ()
    {
        if (this.length()) {
             var geoResult = this.get(0);
             map.setBounds(geoResult.getBounds());

            if (callLoadMapFunction != null && typeof mapLoaded == 'function')
            {
                mapLoaded();
            }

            if (updateBounds != null)
            {
                updateMapBounds();
            }
        }
        else
        {
             alert("Ошибка геокодирования");
        }
    });

            // Процесс геокодирования завершен с ошибкой
     YMaps.Events.observe(geocoder, geocoder.Events.Fault, function (gc, error) {
           alert("Произошла ошибка: " + error);
     });    
}


function showFoundPlaces (places , showMoreDetails)
{
  //var places = JSON.parse(places_string, null);
    
  for (var i = 0 ; i < places.length ; i++)
  {
        place = places[i];
        var point =  new YMaps.GeoPoint (place.lng , place.lat);
        showPlaceOnMap(point , place , showMoreDetails);
  }
}

//var currentNumber = 1;

function showAddressOnMap (loc , info)
{
    var s = new YMaps.Style();
    s.iconStyle = new YMaps.IconStyle();
    s.iconStyle.href = cybimg +  "/map_icon/" + info.icon;
    s.iconStyle.size = new YMaps.Point(info.icon_x, info.icon_y);
    s.iconStyle.offset = new YMaps.Point(info.icon_off_x, info.icon_off_y);

    var infomark = new YMaps.Placemark(loc, {hideIcon: false , style: s ,balloonOptions: {maxWidth: 200}});

    infomark.name = info.name;

    infomark.description =
            "<div style='cursor:pointer;text-decoration:underline;' onclick=zoomToPlace("+loc+");>Увеличить </div><br>"            ;

    map.addOverlay(infomark);
}

function showPlaceOnMap (loc , place , showMoreDetails)
{
    if (place.icon != null && place.icon != "")
    {
        var iconId = parseInt (place.icon);

        if (isNaN(iconId))
        {
            var s = new YMaps.Style();
            s.iconStyle = new YMaps.IconStyle();
            s.iconStyle.href = cybimg +  "/map_icon/" + place.icon;
            s.iconStyle.size = new YMaps.Point(place.icon_x, place.icon_y);
            s.iconStyle.offset = new YMaps.Point(place.icon_off_x, place.icon_off_y);
        }
        else //custom icon for places
        {
            if (iconId != 0)
            {
                var s = new YMaps.Style();
                s.iconStyle = new YMaps.IconStyle();
                s.iconStyle.href = cybimg +  "/map_icon/" + iconId + ".gif";
                s.iconStyle.size = new YMaps.Point(21, 20);
                s.iconStyle.offset = new YMaps.Point(-10, -20);
            }
        }
        
        var placemark = new YMaps.Placemark(loc, {hideIcon: false , style: s ,balloonOptions: {maxWidth: 200}});
    }
    else
    {
        var placemark = new YMaps.Placemark(loc, {hideIcon: false , balloonOptions: {maxWidth: 200}});    
    }



    placemark.name = place.name;
    placemark.id = place.id;

    /*if (place.icon == null)
    {
        placemark.setIconContent (currentNumber.toString());
        currentNumber++;
    }*/


    placemark.description =
            "<div style='cursor:pointer;text-decoration:underline;' onclick=zoomToPlace("+loc+");>Увеличить </div><br>" +
            "<a href='"+cyburl+"place/place-"+place.id+"'>Страница места</a>"
            ;
    
    if (showMoreDetails != null)
    {
        YMaps.Events.observe(placemark, placemark.Events.Click, function (obj) {
            xajax_get_place_info (obj.id);
        });
    }

    overlayReg[place.id] = placemark;

    map.addOverlay(placemark);
}

function showFoundEvents (events , showMoreDetails)
{
  //var events = JSON.parse(events_string, null)

  for (var i = 0 ; i < events.length ; i++)
  {
        event = events[i];
        var point =  new YMaps.GeoPoint (event.lng , event.lat);
        showEventOnMap(point , event , showMoreDetails);
  }
}

function showEventOnMap (loc , event , showMoreDetails)
{
    if (event.icon != null && event.icon != "")
    {
        var iconId = parseInt (event.icon);

        if (isNaN(iconId))
        {
            var s = new YMaps.Style();
            s.iconStyle = new YMaps.IconStyle();
            s.iconStyle.href = cybimg +  "/map_icon/" + event.icon;
            s.iconStyle.size = new YMaps.Point(event.icon_x, event.icon_y);
            s.iconStyle.offset = new YMaps.Point(event.icon_off_x, event.icon_off_y);
        }
        else //custom icon for places
        {
            if (iconId != 0)
            {
                var s = new YMaps.Style();
                s.iconStyle = new YMaps.IconStyle();
                s.iconStyle.href = cybimg +  "/event_icon/" + iconId + ".gif";
                s.iconStyle.size = new YMaps.Point(21, 20);
                s.iconStyle.offset = new YMaps.Point(-10, -20);
            }
        }


        var placemark = new YMaps.Placemark(loc, {hideIcon: false , style: s , balloonOptions: {maxWidth: 200}});
    }
    else
    {
        var placemark = new YMaps.Placemark(loc, {hideIcon: false , balloonOptions: {maxWidth: 200}});
    }

    //var placemark = test YMaps.Placemark(loc, {hideIcon: false});
    placemark.name = event.name;
    placemark.id = event.id;
    placemark.description =
            "<div style='cursor:pointer;text-decoration:underline;' onclick=zoomToPlace("+loc+");>Увеличить </div>";

    if (event.place_id != null)
    placemark.description+=
            "Где:<a href='"+cyburl+"place/place-"+event.place_id+"'>"+event.place_name+"</a><br>";

    placemark.description+= 
            "<a href='"+cyburl+"events/event-"+event.id+"'>Страница события</a>";

    if (showMoreDetails != null)
    {
        YMaps.Events.observe(placemark, placemark.Events.Click, function (obj) {
            xajax_get_event_info (obj.id);
        });
    }

    overlayReg[event.id] = placemark;
    map.addOverlay(placemark);
}


function showFoundDeals (deals)
{
  //var events = JSON.parse(events_string, null)

  for (var i = 0 ; i < deals.length ; i++)
  {
        var deal = deals[i];
        var point =  new YMaps.GeoPoint (deal.lng , deal.lat);
        showDealOnMap(point , deal);
  }
}

function showDealOnMap (loc , deal)
{
   if (deal.icon != null && deal.icon != "")
    {
        var iconId = parseInt (deal.icon);

        if (isNaN(iconId))
        {
            var s = new YMaps.Style();
            s.iconStyle = new YMaps.IconStyle();
            s.iconStyle.href = cybimg +  "/map_icon/" + deal.icon;
            s.iconStyle.size = new YMaps.Point(deal.icon_x, deal.icon_y);
            s.iconStyle.offset = new YMaps.Point(deal.icon_off_x, deal.icon_off_y);
        }
        else //custom icon for deals
        {
            if (iconId != 0)
            {
                var s = new YMaps.Style();
                s.iconStyle = new YMaps.IconStyle();
                s.iconStyle.href = cybimg +  "/deal_icon/" + iconId + ".gif";
                s.iconStyle.size = new YMaps.Point(21, 20);
                s.iconStyle.offset = new YMaps.Point(-10, -20);
            }
        }

        var placemark = new YMaps.Placemark(loc, {hideIcon: false , style: s , balloonOptions: {maxWidth: 200}});
    }
    else
    {
        var placemark = new YMaps.Placemark(loc, {hideIcon: false , balloonOptions: {maxWidth: 200}});
    }

    placemark.name = deal.name;
    placemark.id = deal.id;
    placemark.description =
            "<div style='cursor:pointer;text-decoration:underline;' onclick=zoomToPlace("+loc+");>Увеличить </div>";

    if (deal.place_id != null)
    placemark.description+=
            "Где:<a href='"+cyburl+"place/place-"+deal.place_id+"'>"+deal.place_name+"</a><br>";

    placemark.description+=
            "<a href='"+cyburl+"kupon/kupon-"+deal.id+"'>Информация о акции</a>";

    /*if (showMoreDetails != null)
    {
        YMaps.deals.observe(placemark, placemark.deals.Click, function (obj) {
            xajax_get_deal_info (obj.id);
        });
    }*/

    overlayReg[deal.id] = placemark;
    map.addOverlay(placemark);
}

function showUserOnMap (loc , user)
{
    var placemark = new YMaps.Placemark(loc, {hideIcon: false , balloonOptions: {maxWidth: 200}});

    placemark.name = user.friend_login;
    placemark.description =
            "<div style='cursor:pointer;text-decoration:underline;' onclick=zoomToPlace("+loc+");>Увеличить </div><br>" +
            "<a href='/user/show/"+user.friend_login+"'>Профайл пользователя</a>"
            ;
    //placemark.setBalloonContent(place.name);

    var s = new YMaps.Style();

    // Создает стиль значка метки
    s.iconStyle = new YMaps.IconStyle();
    s.iconStyle.href = cybimg + "user/" + user.image;
    s.iconStyle.size = new YMaps.Point(40, 40);
    placemark.setStyle (s);
    
    map.addOverlay(placemark);
    map.setCenter (loc);
}

function zoomToPlace (lng , lat)
{
    var point =  new YMaps.GeoPoint (lng , lat);
    map.setCenter (point);
    var maxZoom = map.getMaxZoom (map.getBounds());
    map.setZoom (maxZoom);
}


function apifault(err) {
    // Создает обработчик события window.onLoad
    // Отображает сообщение об ошибке в контейнере над картой
    window.onload = function () {
        var errorContainer = document.getElementById("error");
        errorContainer.innerHTML = "При загрузке API произошел сбой. Сообщение об ошибке: \"" + err + "\"";
        errorContainer.style.display = "";
    }
}


function addPlaceLocationMarker (loc)
{
    var placemark = new YMaps.Placemark(loc);

    placemark.name = loc.toString();
    placemark.description = loc.toString();
    placemark.setBalloonContent(loc.toString());
    placeLocation = placemark;
    map.addOverlay(placemark);

    YMaps.Events.observe(placemark, placemark.Events.Click, function (obj)
    {
        isPlaceLocationShown = false;        
        map.removeOverlay (placemark);
    });
}

function addUserLocationMarker (loc , mode)
{
    var placemark = new YMaps.Placemark(loc);

    placemark.name = loc.toString();
    placemark.description = loc.toString();
    placemark.setBalloonContent(loc.toString());
    map.addOverlay(placemark);

    if (mode != "show_place_location")
    {
        YMaps.Events.observe(placemark, placemark.Events.Click, function (obj)
        {
            isUserLocationShown = false;
            map.removeOverlay (placemark);
        });
    }

    return placemark;
}

function placeMarker (loc)
{
    var placemark = new YMaps.Placemark(loc);

    placemark.name = loc.toString();
    placemark.description = loc.toString();
    placemark.setBalloonContent(loc.toString());

    map.addOverlay(placemark);

  
    // Открывает балун с надписью: <div>Новое описание метки</div>
    //placemark.balloonOpen();
}

function setStreet (name)
{
    l('address_location').value = name;
    l("street_autocomplete").style.display = "none";
}

function updateMapBounds ()
{
    if (l("left_bot") != null)
    {
        var bounds = map.getBounds ();
        var leftBottom = bounds.getLeftBottom() ;
        var rightTop = bounds.getRightTop ();
        l("left_bot").value = leftBottom.toString();
        l("right_top").value = rightTop.toString();
        

        if (l("q").value != "" && l("q").value != "Что")
        {
            xajax_update_places_on_map_move (l("q").value , l("search_type").value ,  leftBottom.toString() , rightTop.toString());
        }
    }
}

function setMapBounds (leftBotLat , leftBotLng , rightTopLat , rightTopLng)
{
    var leftBot = new YMaps.Point (leftBotLng , leftBotLat);
    var rightTop = new YMaps.Point (rightTopLng , rightTopLat);

    var bounds = new YMaps.Bounds (leftBot , rightTop);
    map.setBounds (bounds);
    //alert("bu");
}

function submitSearch ()
{
    if (l("location").value)
    {
        var geocoder = new YMaps.Geocoder( l("location").value, {results: 1, boundedBy: map.getBounds()});

        // Создает обработчик успешного завершения геокодирования
        YMaps.Events.observe(geocoder, geocoder.Events.Load, function ()
        {
            if (this.length()) {
                 var geoResult = this.get(0);

                var bounds = geoResult.getBounds();
                var leftBottom = bounds.getLeftBottom() ;
                var rightTop = bounds.getRightTop ();
                l("left_bot").value = leftBottom.toString();
                l("right_top").value = rightTop.toString();
                //placeMarker(leftBottom);
                //placeMarker(rightTop);
                l("search_form").submit();
            }
            else
            {
                 alert("Область поиска задана некорректно");
            }
        });

                // Процесс геокодирования завершен с ошибкой
         YMaps.Events.observe(geocoder, geocoder.Events.Fault, function (gc, error)
         {
               alert("Произошла ошибка: " + error);
         });

    }
    else
    {
         l("search_form").submit();      
    }

    return false;
}

    function notify ()
    {
          xajax_notify_online();
          setTimeout (function () {notify ();}, 60 * 1000);
    }


