$(document).ready(function() {
    function escapeValue(value) {
        return value.replace(/\^/g, "\\^")
            .replace(/\$/g, "\\$")
            .replace(/\./g, "\\.")
            .replace(/\[/g, "\\[")
            .replace(/\|/g, "\\|")
            .replace(/\(/g, "\\(")
            .replace(/\)/g, "\\)")
            .replace(/\?/g, "\\?")
            .replace(/\*/g, "\\*")
            .replace(/\+/g, "\\+")
            .replace(/\{/g, "\\{");
    }

	function formatterNum(t, d, num) {
		return (num + 1) + '.';
	}
	
	function formatterPhone(t, i, k) {
		var buf = t.split(/, ?/),
			ar = [];
			
		for (var i = 0; i < buf.length; i++) {
			var str = buf[i];
			if (str.length > 2) {
				ar.push(str.substr(0,1) + '-' + str.substr(1,2) + '-' + str.substr(3,2));
			}
			else {
				ar.push(str);
			}
		}
		
		return ar.join(', ');
	}
	
	var lastOrg = '';
	function formatterOrg(t) {
		if (t != lastOrg) {
			lastOrg = t;
			return '<b>' + t + '</b>';
		}
	
		return t;
	}
	
	var results = $('#ui-phones'),
		PAD = 50,
		height = $(window).height() - results.offset().top - PAD;
	
	if (height < 300) {
		height = 300;
	}
	
	results.height(height);
	
	uki(
		[{ view: 'TextField', rect: '0 -44 270 22', anchors: 'left top right', minSize: '270 22', maxSize: '270 22', placeholder: 'Введите организацию или номер телефона' },
		{ view: 'Table', rect: '0 0 1000 1000', minSize: '0 200', anchors: 'left top right bottom', columns: [
					{ view: 'table.CustomColumn', label: '№', resizable: true, minWidth: 40, width: 40, formatter: formatterNum},
					{ view: 'table.CustomColumn', label: 'Телефон', resizable: true, minWidth: 100, width: 100, formatter: formatterPhone},
					{ view: 'table.CustomColumn', label: 'Организация', resizable: true, minWidth: 200, width: 350, formatter: formatterOrg},
					{ view: 'table.CustomColumn', label: 'Абонент', resizable: true, minWidth: 200, width: 350}
				], style: {fontSize: '11px', lineHeight: '11px'}}
				
				]).attachTo(results[0], '1000 1000');
						
	var table = uki('Table'),
		input = uki('TextField'),
		data = phonesData.city,
		headers = ['num', 'phone', 'org', 'abonent'],
		activeBase = new SimpleBase(data, headers);
	input.bind('keyup', function() {
		var value = this.value();
		value = $.trim(value).replace(/  */g, ' ');

		if (value.search(/[^\d\-]/) == -1) {
			value = value.replace(/-/g, '');
		}
        
        if (value) {
            value = escapeValue(value);
        }
		
		var data = activeBase.find(value, ['phone', 'org', 'abonent']);
		table.data(data).layout();
	});
	
	table.data(data).layout();
	
	var tabs = $('.tabs-phones .tab');
	tabs.click(function() {
		if ($(this).hasClass('active')) {
			return;
		}
		
		tabs.removeClass('active');
		$(this).addClass('active');
		
		var className = this.className,
			text = 'Отдел, цех',
			placeholder = 'Введите отдел, цех или номер телефона';
		if (className.search(/city/) != -1) {
			data = phonesData.city;
			placeholder = 'Введите организацию или номер телефона';
			text = 'Организация';
		}
		if (className.search(/kgres/) != -1) {
			data = phonesData.kgres;
		}
		if (className.search(/vrtz/) != -1) {
			data = phonesData.vrtz;
		}
		activeBase = new SimpleBase(data, headers);
		input.value('');
		input.placeholder(placeholder);
		table.data(data).layout();
	});
});
