<?php $___notjson=1;

if ( !isset($_REQUEST['delivery_id']) ) exit;
$delivery_id = $_REQUEST['delivery_id'];

require_once 'classes/Install_class.php';

$init = new Install();
$options = $init->getParamFromDb();


if ( $options['rusDel'] == 0 && $options['ukrDel'] == 0 && $options['blrDel'] == 0 && $options['kazDel'] == 0 && $options['armDel'] == 0 && $options['kgzDel'] == 0 ) {
	echo '$("#delivery-cdek").html("Не выбрано ни одной страны для доставки.").show();';
	exit;
}

$country = '';
if ( $options['rusDel'] == 1 ) {
	$country .= "item.name.substr(-6) == 'Россия'";
}
if ( $options['ukrDel'] == 1 ) {
	if ( !empty($country) ) $country .= ' || ';
	$country .= "item.name.substr(-7) == 'Украина'";
}
if ( $options['blrDel'] == 1 ) {
	if ( !empty($country) ) $country .= ' || ';
	$country .= "item.name.substr(-10) == '(Беларусь)'";
}
if ( $options['kazDel'] == 1 ) {
	if ( !empty($country) ) $country .= ' || ';
	$country .= "item.name.substr(-9) == 'Казахстан'";
}
if ( $options['armDel'] == 1 ) {
	if ( !empty($country) ) $country .= ' || ';
	$country .= "item.name.substr(-7) == 'Армения'";
}
if ( $options['kgzDel'] == 1 ) {
	if ( !empty($country) ) $country .= ' || ';
	$country .= "item.name.substr(-8) == 'Киргизия'";
}

$delivery = <<<HTML

var selected = false;
var radioId = {$delivery_id};
    
if ( $('#del-type-' + radioId).is(':checked') ) {
    $("#delivery-cdek").show();
} else {
    $("#delivery-cdek").hide();
    $('#cdek_error, #delivery-date').remove();
};
    
$('#delivery-list tr').on('click', function() {
    if ( $(this).attr('id') == 'delivery-block-' + radioId && !$('#del-type-' + radioId).is(':disabled') ) {
        $("#delivery-cdek").show();
    } else {
        $("#delivery-cdek").hide();
        $('#cdek_error, #delivery-date').remove();
    }
});

var allUrl = [],
	allCnt = [];
$(function() {
	var orderItemLen = $('.order-item-name').length;
	for ( i = 0; i < orderItemLen ;i++ ) {
		allUrl[i] = $('.order-item-name a').eq(i).attr('href');
		allCnt[i] = $('.order-item-cnt input').eq(i).val();
	}
});

HTML;

echo $delivery;
if ( is_numeric($options['orderField']) && $options['orderField'] > 0 ) {
	$orderField = "$('#order-fld-{$options['orderField']}').attr('value', ui.item.label); $('#order-fld-{$options['orderField']}').val(ui.item.label);";
	$orderField2 = "$('#order-fld-{$options['orderField']}').attr('value', address); $('#order-fld-{$options['orderField']}').val(address);";
} else {
	$orderField = '';
	$orderField2 = '';
}

if ( is_numeric($options['orderFieldDate']) && $options['orderFieldDate'] > 0 ) {
	$orderFieldDate = "var delDate = del.substr(31);";
	$orderFieldDate .= "$('#order-fld-{$options['orderFieldDate']}').attr('value', delDate.slice(0, -4)); $('#order-fld-{$options['orderFieldDate']}').val(delDate.slice(0, -4));";
} else {
	$orderFieldDate = '';
}

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

$ui = <<<HTML

$(function() {
	  $("#cdek").autocomplete({
	    source: function(request,response) {
	      $.ajax({
	        url: "//api.cdek.ru/city/getListByTerm/jsonp.php?callback=?",
	        dataType: "jsonp",
	        data: {
	        	q: function () { return $("#cdek").val() },
	        	name_startsWith: function () { return $("#cdek").val() }
	        },
	        success: function(data) {
	          $('#cdek').removeClass('ui-autocomplete-loading')
	          if ( data.geonames ) {
	              $('#cdek').attr('style', 'width:100%;');
                  response($.map(data.geonames, function(item) {
                    if ( {$country} ) {
                        var a = item.name.split(',');
                        for ( i=0; i<a.length; i++ ) a[i] = $.trim(a[i]);
                        var newItem = a.reverse();
                        if ( a[1] == a[2] || a[1].length == 0 ) newItem.splice(1,1);
                        return {
                          label: newItem.join(', '),
                          value: newItem.join(', '),
                          id: item.id
                        }
                    }
                  }));
	          } else {
	             $('#cdek').removeClass('ui-autocomplete-loading')
	             $('#cdek').css('border', '1px solid red');
	          }
	        }
	      });
	    },
	    minLength: 1,
	    select: function(event,ui) {
	    	selected = true;
	    	calcCdek(ui.item.id,radioId); 
	    	{$orderField}
	    },
	    close: function( event, ui ) {
	    	if ( selected == false ) $('#cdek, #order-fld-{$options['orderField']}').val('');
	    }
	  });
	  
});

function calcCdek(city_id,radioId) {
    $('#cdek_error, #delivery-date').remove();
    $.ajax({
        url: '/php/cdek/calculate.php',
        data: 'url=' + allUrl + '&cnt=' + allCnt + '&clientId=' + city_id + '&weight=' + all_weight + '&price=' + all_price + '&radioId=' + radioId + '&k={$key}',
        type: 'POST',
        cache: false,
        dataType: 'script',
        error: function(err, msg) {
            if ( $('#cdek_error').length == 0 ) $('#delivery-cdek').after('<p id="cdek_error">'+msg+'</p>');
            else $('#cdek_error').html('<p id="cdek_error">'+msg+'</p>');
        }
    });
};

HTML;

$map_js = <<<HTML

$.getScript('//api-maps.yandex.ru/2.1/?lang=ru-RU');
$(function() {
    $(".getpointdelivery").fancybox({
        maxWidth : 1200,
        maxHeight : 600,
        fitToView : false,
        width : '95%',
        height : '95%',
        autoSize : false,
        closeClick : false,
        openEffect : 'none',
        closeEffect : 'none',
        scrolling: 'no',
        helpers : {
            overlay : {
                locked : true,
                css : {
                    'background' : 'rgba(0, 0, 0, 0.5)'
                }
            }
        },
        afterShow: function() {
			
		},
		onUpdate: function() {
			autoResizeMap();
		}
    });
});

function insertPrice(price, address, cur, del) {
	if ( $('#delivery-date').length == 0 ) 
		$('#delivery-cdek').after('<p id="delivery-date">Выбран пункт самовывоза: <b>' + address + '</b>.' + del + '</p>');
	else 
		$('#delivery-date').html('Выбран пункт самовывоза: <b>' + address + '</b>.' + del);
	{$orderField2}
	if ( $('input[name="custom_delivery_tax"]').length == 0 ) $('#checkout-form').append('<input type="hidden" name="custom_delivery_tax" value>');
	$('input[name="custom_delivery_tax"]').val(price);
	{$orderFieldDate}
	$('#delivery_id').val(radioId);
	$('span.osum').html('<img alt="" src="//s26.ucoz.net/img/icon/ajsml.gif" style="vertical-align:-4px;">');
	$('#checkout-form-mode').val('change');
	_uPostForm('checkout-form');
	myMap.destroy();
    myMap = data = null;
    $('#delivery_window').remove();
    $.fancybox.close();
};

HTML;



if ( !isset($_REQUEST['weight']) ) $weight = '';
else $weight = $_REQUEST['weight'];

if ( !isset($_REQUEST['price']) ) $price = '';
else $price = $_REQUEST['price'];



$map = '<a href="/php/cdek/pvz.php?weight=' . $weight . '&price=' . $price . '&delivery_id=' . $delivery_id . '&k=' . $key . '" class="getpointdelivery fancybox.ajax">Выберите пункт самовывоза</a>';
$cur = '<input type="text" id="cdek" style="width:100%" placeholder="Укажите адрес курьерской доставки">';

if ( $options['userDelType'] == 1 ) {
	echo "$('#delivery-cdek').html('$cur или $map');";
	echo $ui . $map_js;
} else {
	if ( $options['type'] == 1 || $options['type'] == 3 ) {
		echo "$('#delivery-cdek').html('$cur');";
		echo $ui;
	} else {
		echo "$('#delivery-cdek').html('$map');";
		echo $map_js;
	}
}

if ( is_numeric($options['orderField']) && $options['orderField'] > 0 && $options['type'] == 1 || $options['type'] == 3 || $options['type2'] == 1 || $options['type2'] == 3 ) {
	echo <<<HTML

$('#cdek').on('keyup', function() {
	$('#order-fld-{$options['orderField']}').attr('value', $('cdek').val());
	$('#order-fld-{$options['orderField']}').val($(this).val());
});

function set_cookie ( name, value, exp_y, exp_m, exp_d, path, domain, secure ) {
    var cookie_string = name + "=" + escape ( value );
    if ( exp_y ) {
        var expires = new Date ( exp_y, exp_m, exp_d );
        cookie_string += "; expires=" + expires.toGMTString();
    }
    if ( path ) cookie_string += "; path=" + escape ( path );
    if ( domain ) cookie_string += "; domain=" + escape ( domain );
    if ( secure ) cookie_string += "; secure";
    document.cookie = cookie_string;
}

function get_cookie ( cookie_name ) {
    var results = document.cookie.match ( '(^|;) ?' + cookie_name + '=([^;]*)(;|$)' );
    if ( results ) return ( unescape ( results[2] ) );
    return null;
}

function checkPromo(id, clear_code){
	$('#res'+id).show();
	var formData = formToObj(document.forms["checkout-form"]);
	set_cookie('deliveryInfo', $('input[name="custom_delivery_tax"]').val()+'|'+$('#order-fld-{$options['orderField']}').val()+'|{$options['orderField']}|'+$('#delivery-date').html());
	formData['mode'] = 'apply-promo';
	formData['fid'] = id;
	if(typeof clear_code != 'undefined'){
		formData['clear_code'] = 1;
		formData['code'] = 1;
	}else{
		formData['code'] = $('[name=fld'+id+']').val();
	}
	delete formData['fld'+id];
	_uPostForm('', {type:'POST', url:decodeURIComponent('/shop/checkout'), data:formData});
} 

var deliveryInfo = get_cookie('deliveryInfo');
    
if ( deliveryInfo && typeof deliveryInfo !== undefined && $('#delivery_id').val() == radioId ) { console.log(990);
    $("#delivery-cdek").show();
    deliveryInfo = deliveryInfo.split('|');
    if ( $('input[name="custom_delivery_tax"]').length ) $('input[name="custom_delivery_tax"]').remove();
    var data = '<input type="hidden" name="custom_delivery_tax" value="'+deliveryInfo[0]+'">';
    data += '<script>';
    data += '$("#order-fld-'+deliveryInfo[2]+'").val("'+deliveryInfo[1]+'");';
    data += "$('#delivery-cdek').after('<p id=\"delivery-date\">"+deliveryInfo[3]+"</p>');";
    data += "$('#del-type-"+radioId+"').prop('checked', true);";
    data += '</script>';
    $('#checkout-form').prepend(data);
    $('#checkout-form-mode').val('change');
    _uPostForm('checkout-form');
}

HTML;
}

?>