// нобор скриптов для формы редактирования, проверки организаций

var cacheDistricts = {};
var cacheSubway = {};

//* ************************************************ *//
// отправляет форму
function submitForm() {
	if (!listOpen) {

		checkRubrics(true);

		var isPhoneValid = checkPhones();

		var resultValidation = $('#modForm').valid();

		if (resultValidation && isPhoneValid) {

			return !listOpen;

		} else {

			alert('Необходимо исправить все ошибки');

			return false;
		}

		return false;

	} else {
		return false;
	}
}


// проверяет телефоны ++
function checkPhones() {

	var result = true;

	for (i in phonesList){
		if (!phonesList[i].validate(true)) {
			result = false;
		}
	}

	return result;
}

// возвращает префикса id элементов контакта
function getPrefix(str) {

	var pattern = new RegExp( 'contacts\\[(\\d*)\\]', 'i' );

	if (result = str.match(pattern)) {
		return '#' + result[1] + '__';
	} else {
		return false;
	}
}

// инициализация js валидации
function initValidation() {

	$('#modForm').validate({

		ignore: '[class^=ignore]',

		onsubmit: false,

		rules: {

			title: {
				required: true, minlength: 2, maxlength: 255
			},

			email: {
				required: false, email: true
			},

			url: {
				required: false, url: true
			},

			descriptionShort: {
				required: false, minlength: 40, maxlength: 255
			},

			isSelectedRubrics: {
				required:true
			}
		},
		messages: {
			descriptionShort: {
				minlength: 'Не менее 40 символов.',
				maxlength: 'Не более 255 символов.',
				required: 'Не должно быть пустым.'
			},
			title: {
				minlength: 'Поле "Название", должно содержать не менее 2 символов.'
			},
			isSelectedRubrics: {
				required: 'Необходимо выбрать хотя бы одну рубрику.'
			}
		},
		// set this class to error-labels to indicate valid fields
		success: function(label) {
			// set &nbsp; as text for IE
			label.html("&nbsp;").addClass("checked");
		}
	});
}

// приверяет выбрана ли хоть одна рубрика
function checkRubrics(toValidate) {

	var isSelectedRubrics = [];

	$.each($('input[name="rubrics[]"]'), function() {
		isSelectedRubrics.push($(this).val());
	});

	$('input[name="isSelectedRubrics"]').val(isSelectedRubrics.join(':'));

	if (toValidate === true) {
		$('#modForm').validate().element('input[name="isSelectedRubrics"]');
	}
}

//* ************************************************ *//
// ++
function formatCompleteItem(row, i, num, q) {
	return row[0].replace(new RegExp( '(' + q + ')', 'gi' ), '<b>$1</b>');
}

// определяет id выбранного значения ++
function defineSelectedValue(li, $input) {

	var selectedValue = 0;

	if( li != null ) {
		if( !!li.extra ) {
			selectedValue = li.extra[0];
		} else {
			selectedValue = li.selectValue;
		}
	}

	return selectedValue;
}


function selectedCity(element) {

	var selectedValue = $(element).val();

	var containerPrefix = getPrefix($(element).attr('name'));

	if (selectedValue) {

		initDistricts(selectedValue, containerPrefix);

		initSubway(selectedValue, containerPrefix);

		$(containerPrefix + 'streetTitle').focus('');
	}

	flushLocationsInfo(containerPrefix);
}

function flushLocationsInfo(containerPrefix) {

	$(containerPrefix + 'streetId').val('');
	$(containerPrefix + 'streetTitle').val('');

	$(containerPrefix + 'house').val('');
	$('#modForm').validate().element(containerPrefix + 'streetId');
}

/** *************************************  **/

// автопоиск улиц
function initAutocompleteStreets(element, containerPrefix) {

$(element).autocompleteFormSearch( '/dictionary/searchstreets/', {
		delay:10,
		minChars:2,
		matchSubset:false,
		matchContains:1,
		maxItemsToShow:10,
		cacheLength: 1,
		isCache: false,
		selectFirst: true,
		onItemSelect:findStreetValue,
		onFindValue:findStreetValue,
		noFindValue:noFindStreetValue,
		setDefaultValue:setDefaultStreetValue,
		formatItem:formatCompleteItem,
		autoFill:true,
		dynExtraParams: [ {name: containerPrefix + 'cityId', variable: 'cityId' } ],
		extraParams:{isCustomAjaxAction:1}

	});
}

function findStreetValue(li, $input) {

	var selectedValue = defineSelectedValue(li, $input);

	var containerPrefix = getPrefix($input.attr('name'));

	if (selectedValue) {
		$(containerPrefix + 'streetId').val(selectedValue);
		$input.caret($input.val().length);


		$(containerPrefix + 'house').removeClass('error');
		$(containerPrefix + 'streetTitle').removeClass('error');
		$(containerPrefix + 'labelStreetId').hide();

		$(containerPrefix + 'house').val('').focus();

		///$(containerPrefix + 'streetDebug').text(selectedValue + '::' + $input.val());
	}
}

function setDefaultStreetValue($input, selectedValue) {

	var containerPrefix = getPrefix($input.attr('name'));

	$(containerPrefix + 'streetId').val(selectedValue);
	///$(containerPrefix + 'streetDebug').text(selectedValue + '::' + $input.val());
}


// если не выбрана улица
function noFindStreetValue($input) {
	var containerPrefix = getPrefix($input.attr('name'));
	$(containerPrefix + 'streetId').val('');
}




// инициализирует список районов
function initDistricts(cityId, containerPrefix) {

	if (!cacheDistricts[cityId]) {
		ajax_getDistricts(cityId, containerPrefix);
	} else {
		setDistricts(cityId, cacheDistricts[cityId], containerPrefix);
	}
}

// задает районы
function setDistricts(cityId, districtsData, containerPrefix) {

	cacheDistricts[cityId] = districtsData;

	districtsData = eval("(" + districtsData + ")");

	var objDistricts = $(containerPrefix + 'district')[0];

	var optionCount = objDistricts.options.length;

	for (i = optionCount; i > -1; i--) {
		objDistricts.options[i] = null;
	}

	if (districtsData.length) {

		objDistricts.options.add(new Option('-- Выбрать --', '', false, false));

		$.each(districtsData, function(i, item) {
			objDistricts.options.add(new Option(item['title'], item['id'], false, false));
		});
		$(containerPrefix + 'districtElements').show();
	} else {
		$(containerPrefix + 'districtElements').hide();
	}
}

// инициализирует список станций метро
function initSubway(cityId, containerPrefix) {

	if (!cacheSubway[cityId]) {
		ajax_getSubway(cityId, containerPrefix);
	} else {
		setSubway(cityId, cacheSubway[cityId], containerPrefix);
	}
}

// задает список станций метро
function setSubway(cityId, subwayData, containerPrefix) {

	cacheSubway[cityId] = subwayData;

	subwayData = eval("(" + subwayData + ")");

	var objSubway = $(containerPrefix + 'subway')[0];

	var optionCount = objSubway.options.length;

	if (optionCount > 1)  {
		for (i = optionCount; i > -1; i--) {
			objSubway.options[i] = null;
		}

		objSubway.options.add(new Option('-- Нет --', '', false, false));
	}

	if (subwayData.length) {

		$.each(subwayData, function(i, item) {
			objSubway.options.add(new Option(item['title'], item['id'], false, false));
		});

		$(containerPrefix + 'subwayElements').show();
	} else {
		$(containerPrefix + 'subwayElements').hide();
	}

	isHideFieldTimeToGet(containerPrefix, true)
}

function checkFieldTimeToGet(element, selectedValue) {

	var containerPrefix = getPrefix($(element).attr('name'));

	if (selectedValue == '') {
		isHideFieldTimeToGet(containerPrefix, true);
	} else {
		isHideFieldTimeToGet(containerPrefix, false);
	}
}

function isHideFieldTimeToGet(containerPrefix, isHide) {

	if (isHide === true) {
		$(containerPrefix + 'subwayForTimeToGet').hide();
	} else {
		$(containerPrefix + 'subwayForTimeToGet').show();
	}
}
/**   ***********************  **/
// удаляет логотип организации
function deleteImage(recordId, uploadId) {
	if (confirm('Вы действительно хотите удалить логотип организации ?')) {
		ajax_deleteImage(recordId, uploadId);
	}
}

// добавляет http префикс  в поле ввода сайта
function addHttpPrefix(element) {
	var url = $.trim($(element).val());
	if (url == '') {
		$(element).val('http://').caret(7);
	}
}