//переменные для работы с картами
var smallDelieveryMap,
bigDelieveryMap,
oldRoute=null,
office,
distance=0,
dstAddress,
delieveryText;
$(document).ready(function()
{
//инициализация адреса источника (офиса/склада)
office=storeAddress;
// заказ доставки
$('#order-delievery-button').live('click', function()
{
coords=addressToCoords(dstAddress);
$.ajax({
url:"/cart/add/",
type:"post",
data:{
'Cart':{
'item_id':materialId,
'tableName':'cms_catalog_item',
'count':$(".material-price input[type=number]").val(),
'address':dstAddress,
'comment':delieveryText,
'lat':coords[1],
'lng':coords[0],
'delivery_price':$('.delievery-system .cenaValue .val').attr('data-price'),
},
},
success:function(resp)
{
if (parseInt($(".material-price input[type=number]").val())>0)
{
var obj=$.parseJSON(resp);
$("#flush .wrap").html(obj.response);
$("#flush").fadeIn();
$("#cart-wrap").load("/cart/ajaxcartreload");
}
else
{
alert("Количесво должно быть больше 0");
}
}
});
return false;
})
//открытие окна доставки при наведении на input
/*$('form[name=delievery] input[type=text]').hover(function()
{
if (!$('#item-good-price').hasClass('active'))
{
$('#item-good-price').addClass('active');
}
})*/
//открытие окна доставки при клике на input
$('form[name=delievery] input[type=text]').click(function()
{
if (!$('#item-good-price').hasClass('active'))
{
$('#item-good-price').addClass('active');
}
})
//закрытие окна доставки при клике на крестик
$('#item-good-price .close').click(function()
{
$(this).parent().parent().removeClass('active');
return false;
})
//изменение кол-ва материала
$('form[name=price] .count input[type=number]').change(function()
{
calculateDelievery(distance);
})
//закрытие окна доставки при клике вне области окна
$(document).click(function(e)
{
var isParent=false;
if (!$(e.target).hasClass('fancybox-close'))
{
$(e.target).parents().each(function()
{
if ($(this).hasClass('item-good-price-wrap') || $(this).hasClass('fancybox-lock'))
{
isParent=true;
}
})
if (!isParent)
{
$('#item-good-price').removeClass('active');
}
}
});
//ожидание загрузки исходников яндекс карт
ymaps.ready(function()
{
//инициализация маленькой карты
smallDelieveryMap=init(smallDelieveryMap, 'small-delievery-map', office.coords);
//набор адреса доставки пользователем
$('form[name=delievery] input[type=text]').keyup(function()
{
//адрес доставки
var address=$(this).val();
if (address.length>2)
{
if ((address.indexOf(' ')+1)==0)
{
address="Рязанская область, "+$(this).val();
}
dstAddress=address;
//построение маршрута от склада до адреса доставки
constructRoute(smallDelieveryMap, office.address, address);
}
});
//установка точки вручную
$('form[name=delievery] .map-point').click(function()
{
//открытие попапа с большой картой
$.fancybox.open([
{
content:"
Маршрут доставки
",
}
]);
//инициализация большой карты
bigDelieveryMap=init(bigDelieveryMap, 'big-delievery-map', office.coords);
//нанесение на большую карту маршрута
if (oldRoute!==null)
{
bigDelieveryMap.geoObjects.add(oldRoute);
}
{//маршрут не построен
bigDelieveryMap.events.add('click', function (e)
{//нанесение маршрута от офиса до точки клика
var coords = e.get('coords');
//замена адреса в поле ввода
var deliveryAddress=coordsToAddress(coords);
if (deliveryAddress)
{
$('form[name=delievery] input[type=text]').val(deliveryAddress);
dstAddress=deliveryAddress;
}
//дублирование маршрута на маленькую карту
constructRoute(smallDelieveryMap, office.coords, coords, 0);
//нанесение маршрута на большу карту
constructRoute(bigDelieveryMap, office.coords, coords, 1);
}.bind(office));
}
return false;
});
});
})
function init (obj, mapName, center) {
zoom=10;
if (mapName=='small-delievery-map')
{
zoom=8;
}
obj = new ymaps.Map(mapName, {
center: office.coords,
zoom: zoom,
controls: ['zoomControl'],
});
obj.geoObjects.add(new ymaps.Placemark(office.coords));
return obj;
}
function constructRoute(obj, src, dst, saveRoute)
{
addBalloon=false;
if (saveRoute===1)
{
addBalloon=true;
}
//параметры по-умолчанию
saveRoute=(saveRoute !== undefined) ? saveRoute : 1;
ymaps.route([
src,
dst
]).then(function(route)
{
//очистка карты
obj.geoObjects.removeAll();
//добавление нового маршрута
obj.geoObjects.add(route);
//вычисление расстояния между складом и клиентом
distance=(route.getLength()/1000).toFixed(2);
//route.editor.start();
if (addBalloon)
{
//нанесение метки на большую карту с балуном, в котором предлагается закрыть карту
bigDelieveryMap.balloon.open(dst, 'Маршрут доставки рассчитан и составляет '+distance.replace("\.",',')+' км.
Закройте карту или установите другую точку.', {
// Опция: не показываем кнопку закрытия.
closeButton: true
});
}
calculateDelievery(distance);
//сохранение маршрута
if (saveRoute)
{
oldRoute=route;
}
});
}
function calculateDelievery(distance)
{
if (distance>0)
{
$.ajax({
url:"/catalog/route",
type:"get",
data:{
material_id:materialId,
distance:distance,
count:$('form[name=price] .count input').val(),
},
success:function(res)
{
if (res)
{
$('#item-good-price').addClass('loaded');
$('.delievery-system-wrap').html(res);
$('#item-good-price .distance').html(distance.replace('\.',',')+' км от склада');
}
}
})
}
}
//прямое геокодирование (адрес -> координаты)
function addressToCoords(address)
{
var coords=[];
$.ajax({
url:"https://geocode-maps.yandex.ru/1.x/?apikey=776150e8-5b7a-4610-a9cb-5c0113f0b7af",
type:"get",
async: false,
data:{
geocode:address,
format:'json',
},
success:function(result)
{
if (result.response.GeoObjectCollection.featureMember.length>0)
{
coords=result.response.GeoObjectCollection.featureMember[0].GeoObject.Point.pos.split(' ');
}
else
{//не удалось установить адрес
coords=false;
}
}
});
return coords;
}
//обратное геокодирование (координаты -> адрес)
function coordsToAddress(coords)
{
var address='';
//первая попытка — выбирается адрес с номером дома
$.ajax({
url:"https://geocode-maps.yandex.ru/1.x/?apikey=776150e8-5b7a-4610-a9cb-5c0113f0b7af",
type:"get",
async: false,
data:{
geocode:coords[1]+","+coords[0],
kind:"house",
format:'json',
},
success:function(result)
{
if (result.response.GeoObjectCollection.featureMember.length>0)
{//адрес с номером дома получен
address=result.response.GeoObjectCollection.featureMember[0].GeoObject.metaDataProperty.GeocoderMetaData.text;
}
else
{//не удалось найти номер дома, ищем просто улицу
$.ajax({
url:"https://geocode-maps.yandex.ru/1.x/?apikey=776150e8-5b7a-4610-a9cb-5c0113f0b7af",
type:"get",
async: false,
data:{
geocode:coords[1]+","+coords[0],
format:'json',
},
success:function(result)
{
if (result.response.GeoObjectCollection.featureMember.length>0)
{
address=result.response.GeoObjectCollection.featureMember[0].GeoObject.metaDataProperty.GeocoderMetaData.text;
}
else
{//не удалось установить адрес
address=false;
}
}
});
}
}
});
return address;
}