$(function() {
	$.fn.dropDown = function(dtslct) {
		
		return this.each(function(){
			var $selectAct = $('.select_act', this),
				$selectActName = $('.select_act .bg_r a', this),
				$selectDiv = $('.select', this),
				$select = $('.select select', this);

			$selectAct.click(function(){

				$selectDiv.show();

				$select.unbind();

				$select.bind('mouseleave', function(){
					$selectDiv.hide();
				});

				$select.click(function(){
					if (dtslct) {
						var days = $(this).val();
						if (days == -1) {
							$('input[name=fr_d]').val('');
							$('input[name=fr_m]').val('');
							$('input[name=fr_y]').val('');
						} else {
							var offset = days * 24 * 60 * 60 * 1000;
							var date = new Date();
							var ndate = new Date(date.getTime() - offset);
							var fr_d = ndate.getDate();
							var fr_m = ndate.getMonth()+1;
							var fr_y = ndate.getFullYear();
							if (fr_d < 10) {
								fr_d = '0'+fr_d;
							}
							if (fr_m < 10) {
								fr_m = '0'+fr_m;
							}
							$('input[name=fr_d]').val(fr_d);
							$('input[name=fr_m]').val(fr_m);
							$('input[name=fr_y]').val(fr_y);
						}
					}
					$selectActName.html("<span>"+$(this).find('option[value='+$(this).val()+']').text()+"</span>");
					$selectDiv.hide();
				});

			});

		});
	}

	var self=this;

	var $linkSearch = $('.search .link'),
		$photoContainer = $('.search_res_block');
	//	$buttonControls2 = $('.search_res_block .search_res .but_controls2');

	/*открытие/закрытие поиска*/
	$linkSearch.click(function(){

		var $this=$(this);

		if($this.hasClass('param')){
			$('.dop_param').slideDown(800, function(){
				$('.dop_param .rubric').fadeIn(500);
			});
			$('input[name=type]').val('1');
			$this.removeClass('param').addClass('simple');
			$this.html("<span>простой поиск</span>");
		} else {
			$('.dop_param').slideUp(800);
			$('.dop_param .rubric').hide();
			$('input[name=type]').val('0');
			$this.removeClass('simple').addClass('param');
			$this.html("<span>поиск по параметрам</span>");
		}

		return false;
	});

	/*select период создания*/
	$('.dop_param .date').dropDown(1);

	/*select ориентация*/
	$('.dop_param .orientation').dropDown();

	/*select размер*/
	$('.dop_param .sizer').dropDown();

	/*показ иконок (корзина, избранное) в списке фоток
	$('.search_res_block div').each(function(){
		$(this).hover(function(){
			$(this).find('.but_controls2').show();
		}, function(){
			$(this).find('.but_controls2').hide();
		});
	});*/

	// select/deselect all rubrics
	$('input[name=all_rubrics]').change(function() {
		if ($(this).attr('checked')) {
			$('input.rubric_cb').attr('checked', 'checked');
		} else {
			$('input.rubric_cb').removeAttr('checked');
		}
	});
	// мониторинг выбора всех рубрик
	$('input.rubric_cb').change(function() {
		if ($(this).attr('checked')) {
			if ($('input.rubric_cb').length == $('input.rubric_cb:checked').length) {
				$('input[name=all_rubrics]').attr('checked', 'checked');
			}
		} else {
			$('input[name=all_rubrics]').removeAttr('checked');
		}
	});
	
	// ввод поиска
	$('input[name=query]').focus(function() {
		if ($(this).val() == 'Поиск') {
			$(this).val('');
		}
	}).blur(function() {
		if ($(this).val() == '') {
			$(this).val('Поиск');
		}
	}).keydown(function(e) {
		if (e.keyCode == 13) {
			$('#fsearch').submit();
		}
	});
	
	
	
	// закрытие форм логина и входа
	$('.darkening, #loginForm .tit, #loginForm .tit_r, #regForm .tit, #regForm .tit_r').click(function() {
		$('.darkening, #loginForm, #regForm').hide();
	});
	
	// открытие формы логина
	$('#btnLoginForm').click(function() {
		$('.darkening, #loginForm').fadeIn('fast');
	});
	
	// открытие формы регистрации
	$('#btnRegForm').click(function() {
		$('.darkening, #regForm').fadeIn('fast');
	});
	
	// лейблы форм логина и регистрации
	$('#loginForm input, #regForm input').focus(function() {
		$(this).next('label').hide();
	}).blur(function() {
		if ($(this).val() == '') {
			$(this).next('label').show();
		}
	}).keydown(function(e) {
		if (e.keyCode == 13) {
			$(this).parent().parent().parent().find('a.button').click();
		}
	});
	
	// скроем лейблы для заполненных полей
	$('#loginForm input, #regForm input').each(function() {
		if ($(this).val()) {
			$(this).next('label').hide();
		}
	});
	
	// фикс для лейблов, по клику скрывать лейбл и фокусить поле
	$('#loginForm .label, #regForm .label').click(function() {
		$(this).hide().prev().focus();
	});

	// сабмит поиска
	$('#fsearch_submit').click(function() {
		if ($('input[name=query]').val() == 'Поиск') {
			$('input[name=query]').val('');
		}
	});

	// переключатели для главной - новые/лучшие
	$('#btn_new_photos').click(function() {
		$(this).parent().attr('class', 'act').next().attr('class', '');
		$('#new_photos').show();
		$('#best_photos').hide();
	});
	$('#btn_best_photos').click(function() {
		$(this).parent().attr('class', 'act').prev().attr('class', '');
		$('#best_photos').show();
		$('#new_photos').hide();
	});

	$('#loginForm form').submit(function(){
		ajaxLogin();
		return false;
	});

	$('#regForm form').submit(function(){
		ajaxReg();
		return false;
	});

	//изменение пароля в профиле показать / скрыть 
	$('.fprofile .edit_pass').click(function(){
		$('.fprofile .password').toggle();
	});

	/**
	 * Инициализация большого слайдера
	 */
	$.big_foto_count = 1;
	$.big_foto_timer = setInterval(function() {
		$('.big_foto .num_foto li').removeClass('act');
		$('.big_foto .num_foto li:eq('+($.big_foto_count - 1)+')').addClass('act');
		$('.big_foto img:not(.big_foto_'+$.big_foto_count+')').animate({opacity: 0}, 2000);
		$('.big_foto img.big_foto_'+$.big_foto_count).animate({opacity: 1}, 2000);
		$.big_foto_count++;
		if ($.big_foto_count > $('.big_foto img').length) {
			$.big_foto_count = 1;
		}
	}, 7000);

	/**
	 * Слайдер больших фоток
	 */
	$('.big_foto .num_foto li').click(function() {
		clearInterval($.big_foto_timer);
		$(this).parent().find('li').removeClass('act');
		$(this).addClass('act');
		$(this).parent().parent().find('img:not(.'+$(this).text()+')').animate({opacity: 0});
		$(this).parent().parent().find('img.'+$(this).text()).animate({opacity: 1});
	});

	/**
	 * Слайдер фоток - Назад
	 */
	$('.slide .prev').click(function() {
		var ul = $(this).parent().find('ul');
		var ulml = parseInt(ul.css('margin-left'));
		if (ulml < 0) {
			$(this).parent().find('ul').animate({marginLeft: '+=70px'});
		}
	});

	/**
	 * Слайдер фоток - Вперед
	 */
	$('.slide .next').click(function() {
		var ul = $(this).parent().find('ul');
		var ulml = parseInt(ul.css('margin-left'));
		var ulln = ul.find('li').length;
		if (ulml > (ulln - 7) * -70) {
			$(this).parent().find('ul').animate({marginLeft: '-=70px'});
		}
	});

	/**
	 * Обработка нажатия на кнопку загрузки новой фотографии
	 */
	 $('#btnUploadNewFoto').click(function() {
		 // т.к. у нас может быть выбрано несколько рубрик, то проверяем пуст-ли массив rubric
	 	if (! $('#faddfoto input[@name="rubric[]"]:checked').size() ) {
			return alert('Выберите рубрику.');
		}
		if (! $('#faddfoto input[name=foto]').val()) {
			return alert('Выберите фотографию.');
		}
		if (! $('#faddfoto input[name=name]').val()) {
			return alert('Укажите название фотографии.');
		}
		if (! $('#faddfoto input[name=agree]').attr('checked')) {
			return alert('Не принято пользовательское соглашение.');
		}
		$('#faddfoto').submit();
	 });
	 
	 
	/**
	 * флажок выбора "только для некоммерческого использования"
	 */
	$('input[@name=purpose]').change(function() {
		if (! $(this).attr('checked')) {
			$('#orig_price_com').css('display', 'block');
		} else {
			$('#orig_price_com').css('display', 'none');
		}
	})

	var $chL = $('label[@for=check_all_photos]'),
		$chI = $('#check_all_photos');

	this.checkAll = function(){
		var $photos = $('input[@name="cb_photos[]"]');
		if ($chI.attr('checked')) {
			$photos.attr('checked', 'checked');
		} else {
			$photos.removeAttr('checked');
		}
	}

	$chI.change(function() {
		self.checkAll();
	});
	$chI.click(function() {
		self.checkAll();
	});
	$chL.click(function() {
		self.checkAll();
	});
});

function isNumber(x) {
  return ( (typeof x === typeof 1) && (null !== x) && isFinite(x) );
}
