//var CODECAT_REQUEST_TYPE = 'country';

$(function(){
	
	$('#codecat .spinner').click(onCodecatSpinnerClick); 
	
	var sf = $("#search_fild").autocomplete('/wp-content/plugins/dynamic-ipport/ajax.php', {
		dataType: "json",
		requestParamName: 'qst',
		max: 20,
		minChars: 3,
		width: '100%',
		appendTo: $('#codecat .codecat-dd-wrap'),
		position: '',
		left: ' ',
		top: ' ',
		highlight: false,
//		scrollHeight: ($.browser.msie) ? '11.2em' : '154px',   //11.65e
//		scrollHeight: '174px',
//		scrollHeight: '10.5em',
		scrollHeight: '154px',
		//autoFill: false
		//mustMatch: true,
		matchSubset: false,
		matchContains: true,
//		autoFill: false,
		extraParams: {query: ( (typeof CODECAT_REQUEST_TYPE != 'undefined') ? CODECAT_REQUEST_TYPE : 'codes' )},   //Параметр используется в мобильной версии сайта

		formatItem: function(data, i, total, value, term) {
			
			var val='';
			if (data.city) {
				val += data.city + ', ';
				//val += parseInt(data.mobile) ? ' (сот.), ' : ', ';
			}
			if (data.region) val += data.region + ', ';
			if (data.country) {
				val += data.country;
				val += parseInt(data.mobile) ? ' (сот.)' : '';
			}
			
			var cityCodeLst = '';
			
			if (data.city_code.length) {
				var cityCodeLstLength = 5;
				var count = Math.min(cityCodeLstLength, data.city_code.length);
				
				cityCodeLst = data.city_code[0];
				
				for (var i = 1; i < count; i++) {
				
					cityCodeLst += ', ' + data.city_code[i];
					
				};
				
				if (data.city_code.length > cityCodeLstLength) 
					cityCodeLst += ' ...';
			} 

			var result = (data.type == 'country') ? val : val + '<br />' + '+' + data.country_code + ' ' + cityCodeLst
			
			return result;
		},
		
		formatResult: function(data, value) {
			
			//debugger;
			//var d = data[0].split('|');
			//return d[0];
			return value;
		},

		startLoading: function(){
			
			$('#codecat .inputbox').addClass('spinned');
			
		}, 
		
		stopLoading: function(){
			
			$('#codecat .inputbox').removeClass('spinned');
			
		},

		parse: function(data) {

			if (!data) return;
			
			if (data.error_code != 0){
				showErrorMsg('Сервис недоступен')
				return;
			}

			var items = data.items;
			
			if (!items.length) {
				showErrorMsg('Направление не найдено');
				return;
			}
			
			var parsed = [];
						
			for (var i=0; i < items.length; i++) {
				var row = items[i];
//				debugger;
				var val = '';
				if (row.city) val += row.city + ', ';
				if (row.region) val += row.region + ', ';
				if (row.country) val += row.country;
				
				if (row.city_code) 
				{
					row.cityCodeLst = (row.city_code[0]) ? row.city_code[0] : '';
					for (var j = 1; j < row.city_code.length; j++) 
					{
					
						row.cityCodeLst += ', ' + row.city_code[j];
						
					};
				}
				
				parsed[parsed.length] = {
					data: row,
					value: val,
					result: this.formatResult && this.formatResult(row, val) || val
				};
			}
			return parsed;
		}



	});	
	
	
	sf.result(function(event, data, formatted) {
//		debugger;
		//var $ldr = $('#codecat .result_loader').show();
		//$ldr.hide();
		var $codecatNode = $('#codecat');
		
		$('.result', $codecatNode).show();
		$('.result_error', $codecatNode).hide();
		
		var country = data.country;
		if (parseInt(data.mobile)) country += ' (сот.)';
		
		$('.country', $codecatNode).html(country);
		
		var city = (data.city) ? data.city : '';
		if ((data.city)&&(data.region)) city += ', ';
		city += data.region;
		//debugger;
		//if (parseInt(data.mobile)) city += ' (сот.)';
		
		$('.city', $codecatNode).html(city);
		
		if (data.country_code) 
		{
			$('.country_code', $codecatNode).html('+' + data.country_code);
		}
		
		
		var city_code = '';

		var cityCodeRowCount = 5;
		if (cityCodeRowCount > data.city_code.length ) city_code = data.cityCodeLst
		else {
			
			var maxCode = 0;
			for (var i = 0; i < data.city_code.length; i++) {
				maxCode = Math.max(maxCode, data.city_code[i].length);
			};
			var spanWidth = (maxCode > 2) ? maxCode-- : 2;
			
			for (var i = 0; i < data.city_code.length-1; i++) {
				city_code += '<span style="width:' + spanWidth + 'em">' + data.city_code[i] + ',</span>';
			};
			
			city_code += '<span style="width:' + spanWidth + 'em">' + data.city_code[data.city_code.length-1] + '</span>';						
			
		}
		
		var $cc = $('.city_code', $codecatNode).html(city_code);
		
		
		if (data.type == 'country') 
		{
			$('#result_tariff', $codecatNode).html('на городской от ' + data.price + ' р./мин.<br />на мобильный от ' + data.mobile_price + ' р./мин.');
		}
		else 
		{
			$('#result_tariff span', $codecatNode).html(data.price);
		}
		
		if ($.browser.safari||$.browser.webkit){
			($cc.height()<61) ? $cc.css('overflow', 'visible') : $cc.css('overflow', 'auto');	
		} 
		
	});


	if (typeof CODECAT_REQUEST_TYPE != 'undefined' && CODECAT_REQUEST_TYPE == 'country')
	{
		//Используется в мобильной версии сайта
		$('.codecat-header').text('Чтобы узнать стоимость звонка, введите название страны');
	}

		
});


function showErrorMsg(msg){
	
	$('#codecat .result_error').html(msg).show();
	$('#codecat .result').hide();
	
}


function onCodecatSpinnerClick(){

	if (!$(this).hasClass('spinned')) {
		var event = $.Event($.browser.opera ? "keypress" : "keydown");
		event.keyCode = 40;
		$("#search_fild").focus();
		setTimeout(function(){$("#search_fild").trigger(event);}, 100);
	}
}
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
