<?php $___notjson=1;

$key = '';
foreach ( $_COOKIE as $name=>$value ) {
    if ( substr($name, -3) == 'SID' ) {
        $key = md5('cdek' . $value);
        break;
    }
}

/*if ( !isset($_REQUEST['k']) || empty($_REQUEST['k']) || $_REQUEST['k'] != $key ) {
    die('Доступ запрещен');
}*/

require_once 'classes/Cdek_class.php';

//if ( isset($_REQUEST['town']) ) $city = mb_strtoupper(trim($_REQUEST['town']), 'UTF-8');
//else $city = mb_strtoupper('МОСКВА', 'UTF-8');

$cdek = new Cdek();
$options = $cdek->includeOptions();
$city = mb_strtoupper($options['cityMap'], 'UTF-8');
$pvz = $cdek->getPointsFromDb($city=='ВСЕ ГОРОДА'?'all':$city);
$count = $cdek->getCountPoints();
$all_cities = $cdek->getCityPoints();

if ( $city == 'МОСКВА' || $city == 'ВСЕ ГОРОДА' ) {
    $options['cityMapX'] = 55.75244503863624;
    $options['cityMapY'] = 37.615226544921896;
}

$count_plural = $cdek->declination($count[0], 'пункт', 'пункта', 'пунктов');
$count_town_plural = $cdek->declination($count[1], 'городе', 'городах', 'городах');
$find = $cdek->declination($count[0], 'найден', 'найдено', 'найдено');

$select = '<select name="town" onchange="sort();">';
$select .= '<option value="all">все города</option>';
foreach ( $all_cities as $town ) {
    if ( $town['City'] == $city ) {
        $select .= '<option value="' . $town['City'] . '" selected="selected">' . $town['City'] . ' (' . $town['country'] . ')</option>';
    } else {
        $select .= '<option value="' . $town['City'] . '">' . $town['City'] . ' (' . $town['country'] . ')</option>';
    }
}

$select .= '</select>';
$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 ( $options['typeMap'] == 0 ) {

	$html = <<<HTML

<style>#h3{font-size:14px}.fancybox-inner{background:#fff!important;padding-bottom:0!important;box-shadow:none!important}select{padding:5px;width:100%}#delivery_window{position:relative;width:100%;height:100%;background:#fff;overflow:hidden}#city_gid{position:absolute;width:40%;top:0;left:0;height:100%;background:#fff;padding:10px;overflow:hidden}#city_list{position:relative;width:100%;height:83%;margin-top:10px;overflow-y:auto}.city-list{margin:5px 0;padding:5px}.city-list:hover{background:#e6e6e6;cursor:pointer}.city-list p{margin:0;padding:0;color:#000}.odd{background:#f6f6f6}.img-cur{width:70px;margin-bottom:-3.1px}#city_map{position:absolute;width:58%;top:0;left:41%;height:99%;background:#fff;padding:10px;overflow:hidden}.button-default:disabled,.button:active .button-default:disabled{background:#e6e6e6;color:#4c3421;cursor:default;top:0}.ballon-content{padding:20px}.open{background:#ccc;border:1px solid #000}</style><script>var myMap,objectManager;var ajaxflag=0;function GetPrice(id){ $('.city-list').removeClass('open');$('#city-info-'+id).addClass('open');if(ajaxflag==0){ajaxflag=1;$.ajax({url:'/php/cdek/calculate.php',data: 'url=' + allUrl + '&cnt=' + allCnt + '&id='+id+'&weight={$_GET['weight']}&price={$_GET['price']}&radioId={$_GET['delivery_id']}&k={$key}',cache:false,type:'POST',dataType:'script'});};};function init(){myMap=new ymaps.Map('city_map',{center:[{$options['cityMapX']},{$options['cityMapY']}],zoom:12,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');myMap.geoObjects.add(objectManager);var data=JSON.parse('{$json}');objectManager.add(data);objectManager.objects.events.add('click',function(e){var el=$("#city-info-"+e.get('objectId'));$('#city_list').stop().animate({scrollTop:el.offset().top+$('#city_list').scrollTop()-$('#city_list').offset().top-10},200);});objectManager.objects.events.add('balloonopen',function(e){GetPrice(e.get('objectId'));});};function openBaloon(id){objectManager.objects.balloon.open(id);GetPrice(id);};function sort(){var sort=$('#sortform').serialize();$('select').attr('disabled','disabled');$('#city_list').html('<br><br><p style="text-align: center"><img src="//s26.ucoz.net/img/icon/ajsml.gif" alt="loading"></p>');$.ajax({url:'/php/cdek/sort.php',data:sort,cache:false,type:'POST',dataType:'script',complete:function(){ $('select').removeAttr('disabled');}});};ymaps.ready(init);</script><div id="delivery_window"><div id="city_gid"><h3 id="h3">Всего {$find} <b>{$count[0]}</b> {$count_plural} самовывоза в <b>{$count[1]}</b> {$count_town_plural}</h3><form id="sortform"><label>Сортировать по городу:</label>{$select}</form><div id="city_list">{$city_list}</div></div><div id="city_map"></div></div>

HTML;

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

	$html .= <<<HTML

<style>
#mapContainer {width: 100%; height: 100% } 
#mapContainer #PvzMap {float: left; width: 70%; height: 100%;}
#mapContainer #cityContainer {float: left; width: 30%; position: relative;}
#mapContainer #sort, #cityList, #backToList, #pointInfo {padding: 10px;}
#mapContainer #backToList {background: #e6e6e6; cursor: pointer}
#mapContainer #pointContainer {position: absolute; width: 100%; height: 100%; background: #fff; display: none;}
#mapContainer #cityList {height: 100%; overflow-y: auto}
@media (max-width: 991px) {
	#mapContainer #mapContainer {overflow-x: hidden}
	#mapContainer #PvzMap {float: left; width: 100%; height: 200px; overflow-x: hidden}
	/*#mapContainer #cityContainer {width: 100%; height: 300px; overflow-x: hidden}*/
	#mapContainer #cityContainer {width: 100%; height: auto; overflow-x: hidden}
	#mapContainer #pointContainer {width: 100%; height: auto; overflow: hidden}
}
#mapContainer .city-list{margin:5px 0;padding:5px}.city-list:hover{background:#e6e6e6;cursor:pointer}
#mapContainer .city-list p{margin:0;padding:0;color:#000}
#mapContainer .city-list:hover{background:#e6e6e6 !important;cursor:pointer}
#mapContainer .odd{background:#f6f6f6}
#mapContainer .img-cur{width:70px;margin-bottom:-3.1px}
#mapContainer select {width: 100%;}
#mapContainer h1, #mapContainer h2, #mapContainer h3, #mapContainer h4, #mapContainer h5, #mapContainer h6, #mapContainer p, 
#mapContainer span, #mapContainer select, #mapContainer b {text-transform: none !important;}
#mapContainer .cityName {line-height: 30px;}
#mapContainer .description {font-size:12px;}
#mapContainer p {margin: 0px; padding: bottom: 5px;}
#mapContainer .courier-icon {float: right; margin: 0px 0px 5px 5px; width: 100%; max-width: 110px}
</style>
<div id="mapContainer">
	<div id="PvzMap"></div>
	<div id="cityContainer">
		<div id="pointContainer">
			<div id="backToList" onclick="$('#pointContainer').hide(); myMap.setZoom(10)">Назад к списку</div>
			<div id="pointInfo"></div>
		</div>
		<div id="sort">
			<form id="sortform">
				{$select}
			</form>
		</div>
		<div id="cityList">{$city_list}</div>
	</div>
</div>

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

ymaps.ready(init);
var myMap, objectManager;
function init () {
    myMap = new ymaps.Map('PvzMap', {
        center: [{$options['cityMapX']}, {$options['cityMapY']}],
        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);
    autoResizeMap();

}

function openBalloon(id){
	GetPrice(id);
    var objectId = objectManager.objects.getById(id),
    	html = objectId.properties.balloonContent; 
    $('#pointInfo').html(html);
    $('#pointContainer').show();
    var coords = objectId.geometry.coordinates;
    myMap.setCenter(coords, 18, {
		checkZoomRange: true
	});
}

function GetPrice(id){ 
    $('.city-list').removeClass('open');
    $('#city-info-'+id).addClass('open');
    $.ajax({
        url:'/php/cdek/calculate.php',
        data: 'url=' + allUrl + '&cnt=' + allCnt + '&id='+id+'&weight={$_GET['weight']}&price={$_GET['price']}&radioId={$_GET['delivery_id']}&k={$key}',
        cache:false,
        type:'POST',
        dataType:'script'
    });
};

function sort(){
    var sort=$('#sortform').serialize();
    $('select').attr('disabled','disabled');
    $('#cityList').html('<br><br><p style="text-align: center"><img src="//s26.ucoz.net/img/icon/ajsml.gif" alt="loading"></p>');
    $.ajax({
        url:'/php/cdek/sort.php',
        data:sort,
        cache:false,
        type:'POST',
        dataType:'script',
        complete:function(){ 
            $('select').removeAttr('disabled');
        }
    });
};

/*
function filterMap(courier) {
	if ( courier == 'ALL' ) {
		$('.city-list').show();
		objectManager.setFilter();
		$('#sortform select option[value="ALL"]').prop('selected', true);
		return;
	}
	objectManager.setFilter('properties.courier == "' + courier + '"');
	$('.city-list').hide();
	if ( courier == 'Spice108.ru' ) $('#city-info-1').show();
	else $('.filter_' + courier).show();
}*/

/*function autoResizeMap() {
    if ( parseFloat($('#mapContainer').width()) < 992 ) {
        var heightCityList = parseFloat($('#mapContainer').height()) - parseFloat($('#PvzMap').height()) - parseFloat($('#sort').height()) - 50;//45
        var heightPointInfo = parseFloat($('#mapContainer').height()) - parseFloat($('#PvzMap').height()) - parseFloat($('#backToList').height());
    } else {
	    var heightCityList = parseFloat($('#mapContainer').height()) - parseFloat($('#sort').height()) - 45;
	    var heightPointInfo = parseFloat($('#mapContainer').height()) - parseFloat($('#backToList').height());
	}
	$('#cityList').height(heightCityList + 'px');
	$('#pointInfo').height(heightPointInfo + 'px');
	if (myMap) myMap.container.fitToViewport();
}*/

function autoResizeMap() {
    var w = window.innerWidth
    || document.documentElement.clientWidth
    || document.body.clientWidth;
    if ( parseFloat(w) < 992 ) {
        var heightCityList = parseFloat($('#mapContainer').height()) - parseFloat($('#PvzMap').height()) - parseFloat($('#sort').height()) - 50;//45
        var heightPointInfo = parseFloat($('#mapContainer').height()) - parseFloat($('#PvzMap').height()) - parseFloat($('#backToList').height()) + 130;// + 200;
    } else {
	    var heightCityList = parseFloat($('#mapContainer').height()) - parseFloat($('#sort').height());
	    var heightPointInfo = parseFloat($('#mapContainer').height()) - parseFloat($('#backToList').height());
	}
	$('#cityList').height(heightCityList + 'px');
	$('#pointInfo').height(heightPointInfo + 'px');
	if (myMap) myMap.container.fitToViewport();
}

</script>

HTML;

}

echo $html;
exit;

?>