$(document).ready(function() {

	/**
	 * Вывод формы для отправки сообщений для пользователей
	 */
	$(".send-message").live('click', function() {
		var login = $(this).getUserLogin();
		faderIn();
		dialog(600, 380);
		$.post('/ajax/send_message_form.php', {'to' : login}, function(data){
			$("#dialog").append(data);
		});
		return false;
	});
	$(".cancel-btn").live('click', function() {
		faderOut();
		removeDialog();
		return false;
	});
	$(".submit-btn").live('click', function() {
		var vars = $("#send-message-form").serialize();
		$.post('/ajax/send_private_message.php', {'vars' : vars}, function(data) {
			switch(data)
			{
				case '1':
					notifier('Сообщение успешно отправлено!');
					break;
				case '-1':
					notifier('Получатель не найден.');
					break;
				case '-2':
					notifier('Возникла ошибка при отправке сообщения.');
					break;
				case '-3':
					notifier('Отсутствует сообщение.');
					break;
				default:
					notifier('Возникла ошибка при отправке сообщения. Пожалуйста используйте для связи другие контактные данные');
					break;
			}
		});
		faderOut();
		removeDialog();
		return false;
	});

	/** 
	 * Автозаполнение откуда и куда 
	 */
	$('input#from').autocomplete({
			appendTo: '#fromHelper',
			source: function(req, add) {  
				 $.get("/ajax/autocomplete_city1.php", req, function(data) {  
					add(data.split('###', 10));	   					
				 });
			}
	}); 
	$('input#to').autocomplete({
			appendTo: '#toHelper',
			source: function(req, add) {  
				 $.get("/ajax/autocomplete_city1.php", req, function(data) {  
					add(data.split('###', 10));	   					
				 });
			}
	});
	
	/** 
	 * Автозаполнение откуда и куда с отдельными странами и регионами
	 */
	$('input#fromS').autocomplete({
			appendTo: '#fromHelper',
			source: function(req, add) {  
				 $.get("/ajax/autocomplete_cityS.php", req, function(data) {  
					add(data.split('###', 10));	   					
				 });
			}
	}); 
	$('input#toS').autocomplete({
			appendTo: '#toHelper',
			source: function(req, add) {  
				 $.get("/ajax/autocomplete_cityS.php", req, function(data) {  
					add(data.split('###', 10));	   					
				 });
			}
	});
	
	/**
	 * Поиск машины и грузов
	 */
	$("#fast-search-load")
		.mouseenter(function() {
			$("#fast-search-form").get(0).setAttribute('action', '/index.php?mod=load&go=auto');
		})
		.click(function() {
			$("#fast-search-form").submit();
			return false;
		});
	$("#fast-search-auto")
		.mouseenter(function() {
			$("#fast-search-form").get(0).setAttribute('action', '/index.php?mod=auto&go=cargo');
		})
		.click(function() {
			$("#fast-search-form").submit();
			return false;
		});
	
	/** 
	 * Тип кузова 
	 */
	$("#body_types_wrapper")
		.click(function() {
			$("#body_types_selector").fadeIn();
		});
	$("#body_types_selector")
		.mouseleave(function() {
			$("#body_types_selector").fadeOut();
		});
	$(".body_types").change(function() {
		var val = $(this).val();
		var status = $(this).attr('checked');
			
			if(!status) {
				if(val == 1 || val == 2 || val == 5 || val == 6) {
					$('#body_type_34').removeAttr('checked');
				} else if(val == 8 || val == 11 || val == 14) {
					$('#body_type_35').removeAttr('checked');
				}
			}
		
			if(val == 34) {
				if(status) {
					$('#body_type_1').attr('checked', 'checked');
					$('#body_type_2').attr('checked', 'checked');
					$('#body_type_5').attr('checked', 'checked');
					$('#body_type_6').attr('checked', 'checked');
				} else {
					$('#body_type_1').removeAttr('checked');
					$('#body_type_2').removeAttr('checked');
					$('#body_type_5').removeAttr('checked');
					$('#body_type_6').removeAttr('checked');
				}
			}
			if(val == 35) {
				if(status) {
					$('#body_type_8').attr('checked', 'checked');
					$('#body_type_11').attr('checked', 'checked');
					$('#body_type_14').attr('checked', 'checked');
				} else {
					$('#body_type_8').removeAttr('checked');
					$('#body_type_11').removeAttr('checked');
					$('#body_type_14').removeAttr('checked');
				}					
			}
			
			var selectedOptions = new Array(); 
			
			$('.body_types:checked').each(function() {
				var selected_type_id = $(this).attr('id');
				var selected_type_text = $("label[for=" + selected_type_id + "]").text();
				var match = '';
				if(match = selected_type_text.match(/^\.\.\.\ (.+)$/)) {
					selected_type_text = match[1];
				}
				selectedOptions.push(selected_type_text);
			});
			
			$("#body_types").val(selectedOptions.join(', '));
	});
	
	/***
	 * Комментирование
	 */
	$("#add-comment-button").live('click', function() {
		addComment();
	});
	
	$('textarea[name=comment]').keydown(function(e)
	{
		if(e.ctrlKey && e.keyCode == 13)
		{
			addComment();
		}
	});
	$('.comment-block').live('mouseenter', function() {
		var comment_id = $(this).getID();
		$("#comment-management-" + comment_id).fadeIn('fast');
	}).live('mouseleave', function() {
		var comment_id = $(this).getID();
		$("#comment-management-" + comment_id).fadeOut('fast');
	});
	
	function addComment()
	{
		var vars = $("#add-comment-form").serialize();
		$.post('/ajax/add-comment.php', {'vars': vars}, function(data) {
			if(data)
			{
				if($("#no-comments").exists()) { $("#no-comments").remove(); }
				$("textarea[name=comment]").val('');
				$(data).insertBefore("#add-comment-block");
			}
		});
	}
	
	$(".edit-comment").live('click', function() {
		var comment_id = $(this).getID();
		faderIn();
		dialog(600, 380);
		$.post('/ajax/edit_comment_form.php', {'id' : comment_id}, function(data){
			$("#dialog").append(data);
		});
		return false;
	});
	$(".update-comment-btn").live('click', function() {
		var comment_id = $(this).getID();
		var vars = $("#edit-comment-form").serialize();
		$.post('/ajax/update_comment.php', {'id' : comment_id, 'vars': vars}, function(data){
			if(data)
			{
				$("#comment-text-" + comment_id).html(data);
			}
		});
		faderOut();
		removeDialog();
		return false;
	});
	$(".del-comment").live('click', function() {
		var comment_id = $(this).getID();
		if(confirm("Подтвердите удаление."))
		{
			$.post('/ajax/del_comment.php', {'id' : comment_id});
			$("#comment-" + comment_id).fadeOut('slow');
		}
		return false;
	});
	
	
	/***
	 * Форма поиска, значения по умолчанию
	 */
	if(!($('#from').val())) {
		$('#from').val('укажите нас. пункт');
	}
	if(!($('#to').val())) {
		$('#to').val('укажите нас. пункт');
	}
	$('#from').focusin(function() {
		if($(this).val() == 'укажите нас. пункт') {
			$(this).val('');
		}
	}).focusout(function() {
		if($(this).val() == '') {
			$(this).val('укажите нас. пункт');
		}
	});
	$('#to').focusin(function() {
		if($(this).val() == 'укажите нас. пункт') {
			$(this).val('');
		}
	}).focusout(function() {
		if($(this).val() == '') {
			$(this).val('укажите нас. пункт');
		}
	});
	
	/***
	 * Форма поиска, значения по умолчанию
	 */
	if(!($('#fromS').val())) {
		$('#fromS').val('укажите нас. пункт');
	}
	if(!($('#toS').val())) {
		$('#toS').val('укажите нас. пункт');
	}
	$('#fromS').focusin(function() {
		if($(this).val() == 'укажите нас. пункт') {
			$(this).val('');
		}
	}).focusout(function() {
		if($(this).val() == '') {
			$(this).val('укажите нас. пункт');
		}
	});
	$('#toS').focusin(function() {
		if($(this).val() == 'укажите нас. пункт') {
			$(this).val('');
		}
	}).focusout(function() {
		if($(this).val() == '') {
			$(this).val('укажите нас. пункт');
		}
	});
	
	

	$("#loginBtn").click(function() {
		$("#login_form").submit();
	});
	$("#loginInputFields input").css("color", "#ccc");
	
	/**
	 * Разворачиваем доп. информацию
	 */
	$(".more").live('mouseenter', function() {
						var more_info = $(this).next(".more_info");
						var more_html = more_info.text();
						var p = $(this).offset();
						$('body').append('<div id="more_info">' + more_html + '</div>');
						$("#more_info").hide();
						$("#more_info").css({	'position'	: 'absolute',
										'width'		: '300px',
										'padding'	: '10px',
										'margin'	: '5px',
										'background-color' : '#fff8e7',
										'border'	: 'solid 1px #ccc',
										'font-size'	: '11px',
										'text-align': 'left',
										'top'		: p.top + 12 + 'px',
										'left'		: p.left - 155 + 'px',
										'z-index'	: '1000'});
						$("#more_info").fadeIn('slow');
			 		})
			  .live('mouseleave', function() {
				  		$("#more_info").fadeOut('500').delay('1000').remove();
			  		});
	
	ODKL.init();
	
//Активизируем первую ссылку
$(".contentnav a:first").addClass("active");
//Ширина площади одной страницы
var contentwidth = $(".contentholder").width();
//Обще количество страниц
var totalcontent = $(".content").size();
//Общая ширина всего контента (всех страниц)
var allcontentwidth = contentwidth * totalcontent;
//Проскальзывание контента устанавливаем на ширину, которую получили выше
$(".contentslider").css({'width' : allcontentwidth});
//Теперь пишем новую функцию для проскальзывания и навигации
rotate = function(){
//Количество раз, на которое надо прокрутить контент
var slideid = $active.attr("rel") - 1;
//Устанавливаем дистанцию, на которую происходит единичная прокрутка
var slidedistance = slideid * contentwidth;
//Удаляем активный класс
$(".contentnav a").removeClass('active');
//Добавляем активный класс
$active.addClass('active');
//Анимация проскальзывания

$(".contentslider").animate({
        left: -slidedistance
    }, 1000 );

//});
	
	
};

 
//Устанавливаем время для проведения проскальзывания
rotation = function(){
play = setInterval(function(){
//Навигация следующего слайда
$active = $('.contentnav a.active').next();
if ( $active.length === 0) {
//Перемещаемся к первому слайду в навигации
$active = $('.contentnav a:first');
}
rotate();
//Таймер устанавливаем на 5 сек
}, 5000);
};
//Запускаем функцию вращения

rotation();


$(".contentnav a").click(function() {
$active = $(this);
clearInterval(play);
rotate();
rotation();
return false;
});
$(".contentslider").hover(function(){
		clearInterval(play);
	}, function(){
	rotation();
});
});


$.fn.getID = function() {
	var id = $(this).attr('id').match(/[^0-9]([0-9]+)$/);
	return id[1];
}

$.fn.exists = function(){return jQuery(this).length>0;}

$.fn.getUserLogin = function() {
	var login = $(this).attr('id').match(/^send\-to\-(.+)$/);
	return login[1];
}
function faderIn()
{
	$("body").append('<div id="fader"></div>');
	var height = document.documentElement.scrollHeight;
	var width = document.documentElement.scrollWidth;
	//alert(height);
	$("#fader").css({
					'position': 'absolute',
					'top' : 0,
					'left' : 0,
					'width' : width,
					'height' : height,
					'background-image' : 'url(/templates/Template/images/fader-bgr.gif)',
					'opacity' : '0',
					'z-index' : 1001})
				.animate({
					'opacity' : '0.40'
					}, 300);
}

function faderOut()
{
	$("#fader").animate({
					'opacity' : 0
					}, 300);
	setTimeout('$("#fader").remove()', 1000);
}

function notifier(string)
{
	if(!string) string = 'Действие выполнено';
	$("body").append('<div id="js-notifier">' + string + '</div>');
	var height = $("#js-notifier").height();
	$("#js-notifier").css({
					'position' : 'absolute',
					'width' : '400px',
					'background-color' : '#b4f7a0',
					'padding' : '10px',
					'border' : 'solid 1px black',
					'text-align' : 'center',
					'font-family' : 'Georgia, Times',
					'font-size' : '18px',
					'opacity' : '0',
					'z-index' : 1004,
					'left' : $(window).width()/2 - 400/2 + 'px',
					'top' : $(document).scrollTop() + $(window).height()/2 - height/2 - 30 + 'px'
					});
	$("#js-notifier").animate({
						'opacity' : 1,
						'top' : $(document).scrollTop() + $(window).height()/2 - height/2  + 'px'
						}, 300)
					 .delay(2000)
					 .animate({
						 'opacity' : 0,
						 'top' : $(document).scrollTop() + $(window).height()/2 - height/2 + 30  + 'px'
						}, 300);
	setTimeout('$("#js-notifier").remove()', 3000);
}

function dialog(width, height)
{
	if(!width) width = 600;
	if(!height) height = 400;
	if(!width.toString().match(/%/))
	{
		width = width + 'px';
	}
	$("body").append('<div id="dialog" style="width:' + width + '; height:' + height + 'px"></div>');
	width = $("#dialog").width();
	$("#dialog").css({
					'position' : 'fixed',
					//'background-color' : 'white',
					//'border' : 'solid 1px black',
					'top' : $(window).height()/2 - height/2 + 'px',
					'left' : $(window).width()/2 - width/2 + 'px',
					'z-index' : 1002})
				.html('<a href="#" class="close-btn cancel-btn" style="top:8px; left:' + (width - 28) + 'px;"></a>');
}

function removeDialog()
{
	$("#dialog").fadeOut(300);
	setTimeout('$("#dialog").remove()', 1000);
}

