<?php 
 
$___notjson = 1;
error_reporting(-1);
ini_set('display_errors', true);
header('Content-Type: text/html; charser=utf-8');
date_default_timezone_set ('Europe/Moscow');


require_once 'classes/Cdek_class.php';

if ( isset ( $_POST['town'] ) ) {
    $city = $_POST['town'];
    $cdek = new Cdek();
    $options = $cdek->includeOptions();
    $pvz = $cdek->getPointsFromDb($city);

    if (count($pvz) == 0) {

        $html = <<<HTML

    if(myMap) {
        myMap.destroy();
        myMap = objectManager = null;
    }

    ymaps.ready(init);
    var myMap, objectManager;
    function init () {
        myMap = new ymaps.Map('city_map', {
            center: [55.76, 37.64],
            zoom: 9,
            controls: ['zoomControl']
        })
    }
    $(function () {
        $('#city_list').html('<br><br>При текущих настройках сортировки ничего не найдено');
    });
HTML;

        echo $html;
        exit;

    }

    $city_list = '';
    $features = array();
    $i = 1;

	foreach ( $pvz as $row ) {

		if ( $i % 2 ) {
			$class = ' odd';
		} else {
			$class = '';
		}
		$courier = $row['courier'];

		if ( $options['typeMap'] == 0 ) {

			$city_list .= '<div id="city-info-' . $row['id'] . '" onclick="openBaloon(' . $row['id'] . ');" class="city-list' . $class . '">';
			$city_list .= '<p>' . $i . '. <b>' . $row['City'] . '</b></p>';
			$city_list .= '<p>' . $row['Address'] . '</p>';
			$city_list .= '<p>' . $row['WorkTime'] . '</p></div>';

			$features[] = array(
				"type" => "Feature",
				"id" => $row['id'],
				"geometry" => array(
					"type" => "Point",
					"coordinates" => array(
						(string)$row['coordY'],
						(string)$row['coordX']
					)
				),
				"properties" => array(
					"balloonContent" => '<div id=\"ballonId_' . $row['id'] . '\" class=\"ballon-content\"><b>Пункт выдачи заказов в городе ' . $row['City'] . '</b><br>Код ПВЗ: ' . $row['PVZCode'] . '<br>Адрес ПВЗ: ' . addslashes ($row['Address']) . '<br>Время работы: ' . addslashes ($row['WorkTime']) . '<br>Телефон: ' . $row['Phone'] . '<br><span id=\"cdek_error2\">Стоимость доставки <span id=\"price-delivery-' . $row['id'] . '\"><img src=\"//s26.ucoz.net/img/icon/ajsml.gif\" alt=\"loading\"></span></span><br><span id=\"delper-' . $row['id'] . '\"></span><br><br><button id=\"price_delivery_' . $row['id'] . '\" class=\"button my-button\" disabled=\"disabled\"><span>Заберу свой заказ здесь</span></button></div>',
					"hintContent" => addslashes ($row['Address'])
				),
				"options" => array(
					"iconLayout" => "default#image",
					"iconImageHref" => "/../img/" . $row['courier'] . "-icon.png",
					"iconimgize" => array(32, 37),
					"iconImageOffset" => array(-15, -40)
				)
			);

		} else if ( $options['typeMap'] == 1 ) {

			if ($courier == '') {
				$city_list .= '<div id="city-info-' . $row['id'] . '" onclick="openBalloon(' . $row['id'] . '); return false;" class="city-list' . $class . '">';
			} else {
				$city_list .= '<div id="city-info-' . $row['id'] . '" onclick="openBalloon(' . $row['id'] . '); return false;" class="filter_' . $courier . ' city-list' . $class . '">';
			}
			$city_list .= '<p>' . $i . '. <b>' . $row['City'] . '</b> ';
			$city_list .= '<img class="img-cur" src="/../img/' . $courier . '.png" alt="Курьерская служба ' . $courier . '"></p>';
			$city_list .= '<p>' . $row['Address'] . '</p>';
			$city_list .= '<p>' . $row['WorkTime'] . '</p></div>';
			//$idPvz = $row['latitude'] . '*' . $row['longitude'];
			//$descr = str_replace (array("\r\n", "\r", "\n", "'", "\n\r", "\t"), ' ', $row['drivingdescription'] );

			$features[] = array(
				"type" => "Feature",
				"id" => $row['id'],
				"geometry" => array(
					"type" => "Point",
					"coordinates" => array(
						(string)$row['coordY'],
						(string)$row['coordX']
					)
				),
				"properties" => array(
					"balloonContent" => addslashes ('<div class="baloon-content"><img class="courier-icon" src="/../img/' . $courier . '.png" alt=""><h4><b class="cityName">' . $row['City'] . '</b></h4><h4>' . $row['Address'] . '</h4><hr><p id="cdek_error2">Стоимость доставки <span id="price-delivery-' . $row['id'] . '"><img src="//s26.ucoz.net/img/icon/ajsml.gif" alt="loading"></span></p><hr><p class="delivery-period"><span id="delper-' . $row['id'] . '">Планируемая дата доставки: <img src="//s26.ucoz.net/img/icon/ajsml.gif" alt="loading"></span></p><hr><button id="price_delivery_' . $row['id'] . '" class="button my-button" disabled="disabled"><span>Заберу свой заказ здесь</span></button><hr><p>График работы: ' . $row['WorkTime'] . '</p><hr><p class="description">Код ПВЗ: ' . $row['PVZCode'] . '</p></div>'),
					"hintContent" => addslashes ($row['Address']),
					"courier" => $courier
				),
				"options" => array(
					"iconLayout" => "default#image",
					"iconImageHref" => "/../img/" . $courier . "-icon.png",
					"iconimgize" => array(32, 37),
					"iconImageOffset" => array(-15, -40)
				)
			);

		}

		$i++;

	}

    $FeatureCollection = array(
        "type" => "FeatureCollection",
        "features" => $features
    );

    $json = json_encode($FeatureCollection);
}
if ( $_POST['town'] == 'all' ) {
    $lat = "55.76";
    $long = "37.64";
} else {
    $lat = $pvz[0]['coordY'];
    $long = $pvz[0]['coordX'];
}

if ( $options['typeMap'] == 0 ) {

	$html = <<<HTML

if(myMap) {
    myMap.destroy();
    myMap = objectManager = null;
}

ymaps.ready(init);
var myMap, objectManager;
function init () {
    myMap = new ymaps.Map('city_map', {
        center: [{$lat}, {$long}],
        zoom: 9,
        controls: ['zoomControl']
    }),
    objectManager = new ymaps.ObjectManager({
        clusterize: true,
        gridSize: 32,
        balloonShadow: true,
        balloonOffset: [3, -40]
    });
                
    objectManager.objects.options.set({
        'hideIconOnBalloonOpen': false,
        'preset': 'islands#greenDotIcon'
    });
    
    objectManager.clusters.options.set('preset', 'islands#greenClusterIcons');
    
    objectManager.objects.events.add('click', function (e) {
        var el = $("#city-info-" + e.get('objectId'));
        $('#city_list').stop().animate({scrollTop:0}, 0);
        $('#city_list').stop().animate({scrollTop:el.offset().top -190}, 200);
    });
    objectManager.objects.events.add('balloonopen', function (e) {
        GetPrice(e.get('objectId'), 1);
    });
            
    myMap.geoObjects.add(objectManager);
           
    var data = JSON.parse('{$json}');
    objectManager.add(data);

}

$(function () {
$('#city_list').html('{$city_list}');
});

HTML;

} else if ( $options['typeMap'] == 1 ) {

	$html = <<<HTML

var mapJson = '{$json}';
if(myMap) {
    myMap.destroy();
    myMap = objectManager = null;
}

ymaps.ready(init);
var myMap, objectManager;
function init () {
    myMap = new ymaps.Map('PvzMap', {
        center: [{$lat}, {$long}],
        zoom: 11,
        controls: ['zoomControl']
    }),
    objectManager = new ymaps.ObjectManager({
        clusterize: false,
        //gridSize: 32,
        balloonShadow: true,
        geoObjectOpenBalloonOnClick: false,
        balloonOffset: [3, -40]
    });
    
    objectManager.objects.events.add('click', function (e) { 
    	GetPrice(e.get('objectId'));
    	var objectId = objectManager.objects.getById(e.get('objectId')),
    	    html = objectId.properties.balloonContent;
    	$('#pointInfo').html(html);
    	$('#pointContainer').show();
    	var coords = objectId.geometry.coordinates;
        myMap.setCenter(coords, 18, {
		  checkZoomRange: true
		});
    });
    

            
    myMap.geoObjects.add(objectManager);
           
    var data = JSON.parse(mapJson);
    objectManager.add(data);

}

$(function () {
	$('#cityList').html('{$city_list}');
});

HTML;


}

echo $html;
exit;



?>