(function($){
	// очищаем select
	$.fn.clearSelect = function() {
		return this.each(function(){
			if(this.tagName=='SELECT') {
				this.options.length = 0;
			}
		});
 	}
	// заполняем select
	$.fn.fillSelect = function(dataArray) {
		return this.clearSelect().each(function(){
			if(this.tagName=='SELECT') {
				var currentSelect = this;
				$.each(dataArray, function(index, data){
					currentSelect.options[index] = new Option(data.text, data.value);				
				});
			}
		});
	}
})(jQuery);

jQuery(document).ready(function() {
	//$('.img_zoom').fancyzoom();
	$(".img_zoom").slimbox();
	$('.tips').each(function(){
		var item = $(this);
		var tip = item.attr('tip')
		var value = item.val();
		if (value == ''){
			item.val(tip);
			value = item.val();
		}
		item.focus(function(){
			if(value == tip){
				item.val('');
				value = item.val();				
			}
		});
		item.blur(function(){
			value = item.val();
			if(value == ''){
				item.val(tip);
				value = item.val();				
			}
		});
	});
	
	// Валидация формы отправки заявки
	$('#orderForm').live('submit', function(){
		if (!orderFormValidation()) {
			$('#orderFormError').show();
		} else {
			$('#orderFormError').hide();
			return true;
		}
		return false;
	});
});

function orderFormValidation(){
	var comment = $('textarea[name=comment]');
	var first_name = $('textarea[name=client_first_name]');
	var last_name = $('textarea[name=client_last_name]');
	var patr = $('textarea[name=client_patr_name]');
	var royalty = $('input[name=royalty]');
	
	var valid = true;
	
	if (comment.val() == comment.attr('tip')) {valid = false;}
	
	if (first_name.val() == '') {valid = false;}
	if (last_name.val() == '') {valid = false;}
	if (patr.val() == '') {valid = false;}
	if (royalty.val() == '') {valid = false;}
	
	return valid;
}

$(document).ready(function(){
//	$('.uploadify').uploadify({
//		'uploader'  : '/js/uploadify/uploadify.swf',
//		'script'    : '/js/uploadify/uploadify.php',
//		'cancelImg' : '/js/uploadify/cancel.png',
//		'auto'      : true,
//		'folder'    : '/files/upload',
//		'buttonText' : 'Browse'
//		});
	
	
	// =========================================================================
	// Выпадающий список в форме поиска (мультиселектор)
	// =========================================================================
	
	$('body').click(function(event){
		// По клику вне меню, скрываем все меню
		if ($(event.target).parents('.search-mselect').length == 0) {
			$('.search-mselect ul.drop').slideUp(0);
		}
	});
	
	$('.search-mselect a.show-drop').click(function(event){
		// Если меню не показано, то закрываем все меню и показываем текущее
		if ($(this).parent().children('ul.drop:visible').length == 0) {
			// Закрываем все остальные меню
			$('.search-mselect ul.drop').slideUp(0);
			// Показываем текущее меню
			$(this).parent().children('ul.drop').slideDown();
		}
		event.stopPropagation();
	});	
	//==========================================================================
	
	$('select[name=filial]').change(function(){
		data = new Object;
		data.action = 'agents';
		data.id = $(this).val();
		
		$.get('/ajax/ajax.php',data,function(d){
			$('select[name=agent]').html(d);
			$('select[name=agent]').parent().show();
		});
	});
	
	// =========================================================================
	// Открываем форму полного поиска
	// =========================================================================	
	$('#full-form-toggle').click(
		function (){
			$('#full-form').slideToggle('slow',function(){
				if ($(this).css('display') == 'block') {
					$('#full-form-toggle').html('Краткий поиск');
					
					$('#full-form input').removeAttr('disabled');
					$('#full-form select').removeAttr('disabled');
				}
				else {
					$('#full-form-toggle').html('Подробный поиск');
					$('#full-form input').attr('disabled','disabled');
					$('#full-form select').attr('disabled','disabled');
				}
			});
			
			//$(this).html('Краткий поиск');	
		}
	);
	$('#full-form-toggle-request').click(
			function (){
				$('#full-form').slideToggle('slow',function(){
					if ($(this).css('display') == 'block') {
						$('#full-form-toggle-request').html('Краткая информация об объекте');
						
						$('#full-form input').removeAttr('disabled');
						$('#full-form select').removeAttr('disabled');
					}
					else {
						$('#full-form-toggle-request').html('Подробная информация об объекте');
						$('#full-form input').attr('disabled','disabled');
						$('#full-form select').attr('disabled','disabled');
					}
				});
				
				//$(this).html('Краткий поиск');	
			}
		);
	
	// =========================================================================
	// Поля с подсказкой (autocomplete)
	// =========================================================================
	if (typeof(autocompleteBox) != 'undefined')
	{
		$(autocompleteBox).each(function(){
			field_id = this;
			
			//$('input[name="field['+ this +']"]').autocomplete({
			$('input[name="'+ this +'"]').autocomplete({
				minLength: 2,
				source :	function(request, response){
								// Берем последние две цифры в квадратных скобках
								fid = field_id.slice(field_id.lastIndexOf('[')+1,field_id.length-1);
								request.field = fid.toString();
								request.action = 'autocomplete';
								
								$.get('/ajax/ajax.php', request, function(d){response(d);},'json');
							}
			});
		});
	}
	
	// =========================================================================
	// Добавление поля для загрузки CSV файлов
	// =========================================================================
	$('#add-csv-input').click(function(){
		html = $('#csv-upload-input').html()
		$('#csv-inputs').append('<p>'+ html +'</p>');
	});
	
	// =========================================================================
	// Разворащивающийся список агентов
	// =========================================================================
	$('.filial-expand').click(function(){
		filial = $(this).attr('filial');
		agent_list = $('#filial-'+ filial + ' .agents');
		
		if (agent_list.html() == '')
		{
			progress_animation = '<img src="/i/progress.gif" style="margin:10px 10px 10px 300px;"/>';
			agent_list.append(progress_animation);
			agent_list.slideDown();
			$.get('/agency/manager/agents/'+ filial +'/', null,function(d){
				agent_list.hide();
				agent_list.html(d);
				agent_list.slideToggle();
				
			});
		}
		else{
			agent_list.slideToggle();
		}
	});
	
	// =========================================================================
	// Форма перемещения агента в другой филиал
	// =========================================================================
	$('.agent-move').click(function(){
		// родитель
		root = $(this).parent();
		
		// отобаржаем форму рядом
		root.append($('#agent-move-form form').clone());
		
		// Устанавливаем id агента
		$('input[name=agent]',root).val($(this).attr('agent'));
	});
	
	// =========================================================================
	// Фильтр заявок на объекты. Для администратора
	// =========================================================================
	// Обработка смены агенства
	$('.agency').change(function(){
		
		data = new Object;
		data.action = 'filials';
		data.agency = $(this).val();
		data.defaults = 1;
		root = $(this).parents('tr').attr('id');
		
		$.get('/ajax/ajax.php',data,function(d){
			$('#'+root + ' select.filial').html(d);
			$('#'+root + ' select.filial').change();
		});
	});
	
	// Обработка смены филиала
	$('.filial').change(function(){
		data = new Object;
		data.action = 'agents';
		data.id = $(this).val();
		data.defaults = 1;
		root = $(this).parents('tr').attr('id');
		
		$.get('/ajax/ajax.php',data,function(d){
			$('#'+root + ' select.agent').html(d);
		});
	});
	
	// По умолчанию локализация календаря - русская
	$.datepicker.setDefaults($.datepicker.regional['ru']);
	
	// Инициализируем все календари
	$('.datepick').datepicker();
	
	// =========================================================================
	// Фильтр заявок на объекты. Для агентства
	// =========================================================================
	// Обработка смены агенства
	
	$('.agency-views').change(function(){
		
		var data = {};
		data.action = 'agents_views';
		data.agency = $(this).val();
		data.defaults = 1;
		data.type = $(this).attr('vtype');
		var root = $(this).parents('tr').attr('id');
		
		// Производим включение и отключение поля агентства
		if ($(this).attr('vtype') == 'from') {
			var agency_id = $(this).attr('agency-id');
			var toSelect = $('select.agency-views[vtype=to]');
			if ($(this).val() != agency_id & $(this).val() != 0) {
				$('[value='+agency_id+']',toSelect).attr('selected','selected');
				toSelect.attr('disabled','disabled');
			} else {
				toSelect.removeAttr('disabled');
			}
		} else {
			var agency_id = $(this).attr('agency-id');
			var fromSelect = $('select.agency-views[vtype=from]');
			if ($(this).val() != agency_id & $(this).val() != 0) {
				$('[value='+agency_id+']',fromSelect).attr('selected','selected');
				
				fromSelect.attr('disabled','disabled');
			} else {
				fromSelect.removeAttr('disabled');
			}
		}
		
		// Обновляем селектор с агентами
		$.get('/ajax/ajax.php', data, function(d){
			$('#'+root + ' select.agent-views').html(d);
		});
	});
	
	// =========================================================================
	// Статистика посещений
	// =========================================================================
	$('.auth-agency').change(function(){
		$('.auth-filial').attr('disabled', 'disabled');
		data = new Object;
		data.action = 'filials';
		data.agency = $(this).val();
		data.defaults = 1;
		
		$.get('/ajax/ajax.php',data,function(d){
			$('.auth-filial').html(d);
			$('.auth-filial').removeAttr('disabled');
		});
	});
	
	// =========================================================================
	// Диалог перезаписи при ручном добавлении объекта
	// =========================================================================
	$('#set-rewrite').live('click', function(){
		$('input[name=rewrite]').val(1);
		$('#object-add-form').submit();
	});
	
	$('#object-change-code').live('click', function(){		
		newCode = $('#object-new-code').val();
		if (newCode == '' || newCode == 'укажите другой код объекта') {
			alert('Укажите коректный код объекта');
			return;
		};
		$('input[name=object_code]').val(newCode);
		$('#object-add-form').submit();
	});
	
	
	
});

//=========================================================================
// Динамический пересчет стоимости выгрузки
// =========================================================================
function publicationCostRecalc(){
	var el = $('#publication-objects');
	
	// Стоимость одного объекта
	var cost = parseFloat(el.attr('cost'));
	
	// Все объекты
	var allCount = $('input:checked', el).length;
	var total_cost = allCount * cost;
	
	// Объекты текущей выгрузки
	var currentCount = $('input.current-publication-object:checked', el).length;
	var current_cost = currentCount * cost;
	
	// Обновляем поля страницы
	$('#publication-total-cost').html(total_cost.toFixed(2).replace('.',','));
	$('#publication-current-cost').html(current_cost.toFixed(2).replace('.',','));
}
