﻿$(function () {
	bShadowBox = Shadowbox.init();
})


/* Submit logon form */
function logon(jsFormLogon){
	$(jsFormLogon.logon_submit).attr('disabled', 'true');
	var email = jsFormLogon.email.value;
	var pswd = jsFormLogon.pswd.value;
	
	$.post( '/community/login/logon.html', {email: email, pswd: pswd, ajax: 'true'}, function(data) {
		if (data == 'ok'){
			window.location.reload();
		} else if (data == 'error') {
			alert('Неправильная пара логин/пароль. Попробуйте еще раз.');
		} else {
			alert('Ошибка на сервере. Свяжитесь с администратором.');
		}
		$(jsFormLogon.logon_submit).removeAttr('disabled');
	});
	
	return false;
}
/* Logout */
function logout(){
	$.post( '/community/login/logout.html', {ajax: 'true'}, function(data) {
		window.location.href = 'http://' + window.location.hostname;
	});
	return false;
}


//Работа с полями ввода файлов для галерей
$(function () {
	var jInputsGallery = $('input.inputgalleryphoto');
	if (jInputsGallery.length == 0) {
		return;
	}
	
	jInputsGallery.after('<img class="gallerylink_remove" src="/_img/delete.png" onclick="removeInputPhotoGallery(this)" >');
	
	jInputsGallery.filter(':last').next('img.gallerylink_remove').next('br').after('<img class="gallerylink_add" src="/_img/add.png" onclick="addInputPhotoGallery(this)" >');
})

function removeInputPhotoGallery (thisLink) {
	$(thisLink).prev('input.inputgalleryphoto').remove();
	$(thisLink).next('br').remove();
	$(thisLink).remove();
};

function addInputPhotoGallery (thisLink) {
	$(thisLink).before('<input type="file" name="photogallery" class="inputgalleryphoto" ><img class="gallerylink_remove" src="/_img/delete.png" onclick="removeInputPhotoGallery(this)" ><br>');
};


var jComments;

$(function(){
	jComments = $('#comments');
	var iLastComment = $('div[comment_number]:last', jComments).attr('comment_number');

	for (var i = 0; i <= iLastComment; i++) {

//	Добавляем к каждому ответу ссылки для навигации
		var sNavigation = '<div id="navigation_comment_number_' + i + '" style="display:none;">';
		if (i != 0) {
			sNavigation += '<a class="navigationPrev" href="#" onclick="return toggleComment(' + i + ',' + (i-1) + ')">&larr; Предыдущий</a>';
		}
		if (i != iLastComment) {
			sNavigation += '<a class="navigationNext" href="#" onclick="return toggleComment(' + i + ',' + (i+1) + ')">Следующий &rarr;</a>';
		}
		sNavigation += '</div>';
		$('#navigation', jComments).append(sNavigation);
//	END Добавляем к каждому ответу ссылки для навигации

//	Режем длинные сообщения

		var jAC = $('#comment_number_' + i + ' div.c_text', jComments);
		var sAC = $(jAC).text();
		if (sAC.length > 300) {
			$(jAC).append('<div class="toggleView"><a href="#" onclick="$(\'#comment_number_' + i + ' div.c_text\', jComments).toggle(); return false;">Свернуть комментарий</a></div>');
			$(jAC).after('<div class="c_text">' + sAC.substr(0,300) + '...<div class="toggleView"><a href="#" onclick="$(\'#comment_number_' + i + ' div.c_text\', jComments).toggle(); return false;">Развернуть комментарий</a></div></div>');
			$(jAC).hide();
		}

//	END Режем длинные сообщения


	}
	
//	Прячем все ответы кроме первого
	$('div[comment_number]', jComments).hide();
	toggleComment(1, 0);
//	Включаем счетчик ответов
	$('div.count_comment', jComments).toggle();
})

//Переключает видимость ответов. Первый номер - номер ответа который надо спрятать. Втойро - номер ответа который надо показать.
function toggleComment(iHide, iShow) {
	$('#comment_number_' + iHide, jComments).hide();
	$('#comment_number_' + iShow, jComments).show();

	$('#navigation_comment_number_' + iHide, jComments).hide();
	$('#navigation_comment_number_' + iShow, jComments).show();
	
//	Меняем номер ответа
	$('#c_number', jComments).html(iShow + 1);
	return false;
}


$(function () {
	$('#main_sc, #login_email').each(function () {
		$(this)
			.click(function () {
				var $this = $(this);
				if ($this.is('.example')) {
					$this.data('oldVal', $this.val()).val('').removeClass('example');
				}
			})
			.blur(function () {
				var $this = $(this);
				if ( $this.val().replace(/\s*/, '') == '' ) {
					$this.addClass('example').val($this.data('oldVal'));
				}
			});
	});
	
})

$(function () {
	var $searchForm = $('#main_sf');
	$searchForm.submit(function () {
		if ($('#main_sc').is('.example')) {
			return false;
		}

		switch ( $('select[name="search_field"]', $searchForm).val() ) {
			case '1':
				$searchForm.attr('action', '/msgboard/search.html');
				break;
			case '2':
				$searchForm.attr('action', '/community/members/search_results.html');
				break;
			case '3':
				$searchForm.attr('action', '/forum/search/');
				break;
			default:
				return false;
		}
	});
})

$(function () {
	if ($.browser.msie && parseInt(jQuery.browser.version) < 7) {
		$('#filter_company').find('div.bf_choose').hover(
			function () {
				$(this).css('color', '#da7000').children('div.bf_choose_popup').show();
			},
			function () {
				$(this).css('color', '#057ec3').children('div.bf_choose_popup').hide();
			}
		);
	}
})


$(function () {
	var sFeedbackData = '';
	$.post('/feedback/', {'ajax': 'true'}, function (data) {
		sFeedbackData = data;
		if (sFeedbackData == '') {
			return;
		}
		$('a.ajax_feedback').click(function () {
			Shadowbox.open({
				options: {enableKeys:	false, displayNav:	false},
				content:	'<div style="background-color:#fff;height:100%"><div id="feedback_form"><a href="#" class="close" onclick="Shadowbox.close(); return false;">закрыть</a><h2>Обратная связь</h2>' + sFeedbackData + '</div></div>',
				player:	'html',
				width:	600,
				height:	525
			});
			return false;
		})
	})
//	function processFeedbackForm() {
//		console.info($('#feedback_form form'));
		$('#sb-body-inner form').live('submit', function () {
			var thisForm = this;
			$('input[name="add"]', thisForm).attr('disabled', 'true');
		
			var sName = $('input[name="name"]', thisForm).val();
			var sEmail = $('input[name="email"]', thisForm).val();
			var sInfo = $('textarea[name="info"]', thisForm).val();
			var sMsg = $('textarea[name="msg"]', thisForm).val();
			
			if (sName.replace(/\s/g, '') == '' || sEmail.replace(/\s/g, '') == '' || sInfo.replace(/\s/g, '') == '' || sMsg.replace(/\s/g, '') == '') {
				alert('Не все обязательные поля заполнены.');
				$('input[name="add"]', thisForm).removeAttr('disabled');
				return false;
			}
			
			$.post('/feedback/', {ajax: 'true', add: 'send', name: sName, email: sEmail, info: sInfo, msg: sMsg}, function (data) {
				if (data == 'ok') {
					alert('Ваше сообщение успешно отправлено.');
					Shadowbox.close();
				} else {
					alert(data);
					$('input[name="add"]', thisForm).removeAttr('disabled');
				}
			});
			return false;
			
		});
//	}
	
})
