﻿var divs;
var x;
var aaa;

var $imagesList; // улка в которой будут скрытые фото
var imgs = new Object(); // ассоциативный массив изображений

/** СТАРЬЁ **/ 
function cont_show_child(elem){
	if (aaa){clearTimeout(aaa); aaa = false;}
}

function show_child(elem) {
	if (aaa){clearTimeout(aaa); aaa = false;}
	divs = $('div#intro_navi div');
	for (var x=0; x<divs.length; x++){
		if (divs[x].className == "popup" && divs[x].style.display != "none"){divs[x].style.display = "none";}
	}
	divs = elem.parentNode.getElementsByTagName("div");
	for (var x=0; x<divs.length; x++){
		if (divs[x].className == "popup" && divs[x].style.display != "block"){
			divs[x].style.display = "block";
			iframes = elem.parentNode.getElementsByTagName("iframe");/*IE6*/
			tables = elem.parentNode.getElementsByTagName("table");/*IE6*/
			if (!tables[0].style.width){tables[0].style.width = divs[x].offsetWidth+15+'px';}/*IE6*/
			iframes[0].style.height = divs[x].offsetHeight-40+'px';/*IE6*/
			iframes[0].style.width = divs[x].offsetWidth-11+'px';/*IE6*/
		}
	}
	var spans = document.getElementsByTagName("span");
	for (var x = 0; x < spans.length; x++){
		if (spans[x].className == 'arrow-down'){
			if (spans[x].parentNode.parentNode.parentNode.parentNode.parentNode.className == "popup"){spans[x].style.marginLeft = elem.offsetWidth-17+'px';}
		}
	}
}

function hide_el(xx){
	divs = $('div#intro_navi div');
	divs[xx].style.display = "none";
}

function hide_child(elem) {
	
	divs = $('div#intro_navi div');
	for (var x=0; x<divs.length; x++){
		if (divs[x].className == "popup" && divs[x].style.display == "block"){
			aaa = setTimeout ("hide_el('"+x+"');", 500);}
	}
}

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

function toggleDisplay(elem) { // Переключает видимость элемента
	if(elem.css('display') == 'none') elem.css('display', 'block'); else elem.css('display', 'none');
}

$(function(){
    $("div.photo-item img").click(function() {
       var src = $(this).parent().attr('href');
              
       $("div.photo-main img").attr('src', src);
       $("div.photo-item").removeClass('select');
       $(this).parents('div.photo-item').addClass('select');
       return false;
    });
    
    $("span.write-email a").click(function() {
        $(".mail_send").toggle();
        return false;
    })
	
	$("img#close_mail").click(function() {
        $(".mail_send").toggle();
    })
    
    $("form#mail_send").submit(function() {
        var adr = $("input[name=mail_email]").val();
        var pattern=/[0-9a-z_]+@[0-9a-z_]+\.[a-z]{2,5}/i;
        var res=pattern.test(adr);
        
        if($("input[name=mail_name]").val() == ""){
            if($("form#mail_send span#error").length > 0) return false;
            $("input[name=mail_name]").after('<span id="error" style="color: red"><br/>Незаполнено поле ИМЯ.');   
            $("input[name=mail_name]").focus();
            return false;     
        }else{
            $("input[name=mail_name]").next("span").remove();
        }
        
        if($("input[name=mail_email]").val() == "") {
            if($("form#mail_send span#error").length > 0) return false;
            $("input[name=mail_email]").after('<span id="error" style="color: red"><br/>Незаполнено поле EMAIL.');
            $("input[name=mail_email]").focus();
            return false;    
        }else {
            $("input[name=mail_email]").next("span").remove();
        }
        
        if(res != true) {
            if($("form#mail_send span#error").length > 0) return false;
            $("input[name=mail_email]").after('<span id="error" style="color: red"><br/>Введен не корректный email.');
            $("input[name=mail_email]").focus();
            return false;    
        }else {
            $("input[name=mail_email]").next("span").remove();
        }
        
        if($("textarea[name=mail_text]").val() == "") {
            if($("form#mail_send span#error").length > 0) return false;
            $("textarea[name=mail_text]").after('<span id="error" style="color: red"><br/>Незаполнено поле СООБЩЕНИЕ.');
            $("textarea[name=mail_text]").focus();
            return false;    
        }else {
            $("textarea[name=mail_text]").next("span").remove();
        }
        
        return true;
    })
	
	function build_action(key, val)
	{
		var targetOb = this.window;
		for (var x in url_parts) {
			targetOb[x] = (x == key) ? val : url_parts[x];
		}
		
		return 'http://' + ((board_a != '') ? board_a + '-' : '') + 'board.animal.ru/' + ((board_b != '') ? board_b + '/' : '')  + ((brand != '') ? brand + '/' + ((pet != '') ? pet + '/' : '') : '') + par;
	}
	
	if ($('#form_filter').length > 0)
	{
		$('#pets_filter .link-item a').live('click', function() {
			if ($(this).hasClass('sel'))
			{
				$(this).attr('title', 'Добавить фильтр по виду').next().remove();
				$('#form_filter').attr("action", build_action('brand', ''));
			}
			else
			{
				$(this).attr('title', 'Убрать фильтр по виду');
				$('#form_filter').attr("action", build_action('brand', $(this).attr('rel')));
			}
			$(this).toggleClass('sel');
			
			$('#form_filter').submit();
			return false;
		});
		
		$('#pets_drop').live('click', function() {
			
			$('#pets_filter').removeClass('sel');
			
			$('#form_filter').attr('action', build_action('brand', ''));
			$('#breeds_filter .left a.sel').removeClass('sel').next().remove();
			
			$(this).parent().remove();
			$(this).remove();
			
			$('#ptyp_drop').parent().remove();
			$('#ptyp_drop').remove();
			$('#form_filter').submit();
			return false;
		});

		$('#ptyp_filter .left a').live('click', function() {
			if ($(this).hasClass('sel'))
			{
				$(this).next().remove();
				$('#form_filter').attr("action", build_action('pet', ''));
			}
			else
				$('#form_filter').attr("action", build_action('pet', $(this).attr('rel')));

			$(this).toggleClass('sel');
			$('#form_filter').submit();
			return false;
		});
		
		$('#ptyp_drop').live('click', function() {
			
			$('#pets_filter').removeClass('sel');
			$('#form_filter').attr("action", build_action('pet', ''));
			$('#ptyp_filter .left a.sel').removeClass('sel').next().remove();
			$(this).parent().remove();
			$(this).remove();
			$('#form_filter').submit();
			return false;
		});

		$('#breeds_drop').live('click', function() {
			$('#breeds_filter .left a.sel').removeClass('sel').next().remove();
			$(this).parent().remove();
			$('#form_filter').submit();
			return false;
		});
		
		$('#breeds_filter .left a').live('click', function() {
			if ($(this).hasClass('sel'))
			{
				$(this).next().remove();
				if ($('#breeds_filter .left a.sel').length < 2) $('#breeds_filter div.mini').remove();
			}
			else
			{
				$(this).after('<input type="hidden" name="breeds[]" value="' + $(this).attr('rel') + '">');
				if ($('#breeds_drop').length == 0)
					$('#breeds_filter').append('<div class="mini"><a id="breeds_drop" href="javascript:void(0);" title="Убрать фильтры по породам">отменить</a></div>');
			}
			
			$(this).toggleClass('sel');
			$('#form_filter').submit();
			return false;
		});
		
		$('#photo_drop').live('click', function() {
			
			$('#photo_filter').removeClass('sel').next().remove();
			
			$(this).parent().remove();
			$('#form_filter').submit();
			return false;
		});
		
		$('#photo_filter').live('click', function() {
			if ($(this).hasClass('sel'))
				$(this).attr('title', 'Добавить фильтр по наличию фотографий').next().remove();
			else
				$(this).attr('title', 'Убрать фильтр по наличию фотографий').after('<input type="hidden" name="photo" value="1">');

			$(this).toggleClass('sel');
			$('#form_filter').submit();
			return false;
		});
		/*
		$('#cats_drop').live('click', function() {
			$('#cats_filter .left a.sel').removeClass('sel').next().remove();
			$(this).parent().remove();
			$('#form_filter').submit();
			return false;
		});
		
		$('#cats_filter .left a').live('click', function() {
			if ($(this).hasClass('sel'))
			{
				$(this).next().remove();
				if ($('#cats_filter .left a.sel').length < 2) $('#cats_filter div.mini').remove();
			}
			else
			{
				$(this).after('<input type="hidden" name="cats[]" value="' + $(this).attr('rel') + '">');
				if ($('#cats_drop').length == 0)
					$('#cats_filter').append('<div class="mini"><a id="cats_drop" href="javascript:void(0);" title="Убрать фильтры по подразделам">отменить</a></div>');
			}
			
			$(this).toggleClass('sel');
			$('#form_filter').submit();
			return false;
		});*/
		
		$('#form_filter').submit(function() {
			$(this).find('[name=title], .price').each(function() { 
				str = $(this).val();
				if (jQuery.trim(str) == '')
					$(this).attr('disabled', 'disabled');
			});
			
		});
	}
});

// Отображает скрытые картинки при наведении на главную
function exposeImages($elem, images, url) {
	if(images.length == 1)
		return;
		
	$imagesList.empty();
	
	for(i=0; i<images.length; i++) {
		$imagesList.append($(imgs[images[i]]));
	}
	$('ul#imagesList>img').wrap('<li><a href="'+url+'"></a></li>');

	var position = $elem.offset();
	
	if(!$.browser.msie)
		$elem.parent().append($imagesList);
	
	$imagesList.show();
	$imagesList.offset({top: Math.round(position.top-6), left: Math.round(position.left-6)});
	$imagesList.offset({top: Math.round(position.top-6), left: Math.round(position.left-6)});
	
	if($.browser.msie)
		$imagesList.width(images.length*76+6); // в ие возникает перенос картинок, если явно не указать ширину улки
}

$(document).ready( function() {
	$imagesList = $('ul#imagesList');
	$imagesList.mouseleave(function() {
		$(this).hide();
	});
	
	$('img.expose_photos').each( function() {
		var images = $(this).attr('rel');
		images = jQuery.parseJSON(images);
		images = images.images;
		for (var i in images) 
			if (images[i] != '')
			{
				imgs[images[i]] = new Image();
				imgs[images[i]].src = 'http://animal.ru/i/board/th_' + images[i];
			}
		
		$(this).mouseover( function () {
			var images = $(this).attr('rel');
			images = jQuery.parseJSON(images);
			exposeImages($(this), images.images, images.url);
		});
	});
});

/* Форма редактирования объявления */
$(function() {
	if ($('#AddPost').length > 0)
	{
		var cities = {};
		var cities_loading = false;
		(function($){
		$.fn.clearSelect = function() {
			return this.each(function(){
				if(this.tagName == 'SELECT') {
					this.options.length = 0;
					$(this).attr('disabled','disabled');
				}
			});
		}
		$.fn.fillSelect = function(dataArray) {
			return this.clearSelect().each(function(){
				if(this.tagName == 'SELECT') {
					var currentSelect = this;

					$(currentSelect).append('<option value="0">Выберите категорию</option>');
					$.each(dataArray,function(index,data) {
						$(currentSelect).append('<option value="' + data.value + '" rel="' + data.rel + '" title="' + data.title + '">' + data.text + '</option>');
					});
				}
			});
		}
		})(jQuery); 


		$(document).ready(function() {
			
			$("#AddPost [name='breed']").autocomplete('/ajax/pets/breed/', { 
				extraParams: {pid: function() { return $("#AddPost [name='pet_id']").val(); }}, 
				formatItem: function (row) { return row[0] + " <small>" + row[2] +"</small>" }}).result( function(e, data){ $("#AddPost [name='breed_id']").val(data[1]);});
			
			$('#par_category').change(function() {
				var i = $(this).val();
				if (typeof(obj[i]) != 'undefined')
					$('#category').fillSelect(obj[i]).removeAttr('disabled');
			});
			
			$('#category').change(function() {
				
				if ($(this).val() > 0)
				{
					$("#Step1").attr('id', 'done');
					$(".inner-text:first").hide();
					$(".inner-text:first").after("<div class=inner-text id='steptext'><div>Категория: " + $('#par_category option:selected').html()  + "</div><div>Раздел: " + $('#category option:selected').html()  + "</div><div class=edit><a href='#' class='editCat'>Изменить</a> <span>(при изменении раздела, вся введенная информация может быть потеряна)</span></div></div>");
					
					$('#Step2,a.nextStep3').show();
					
					var opt = $('#category').find(':selected');

					if (opt.attr('rel') == '1')
						$('#Mypets').css('display', 'none');
					else
						$('#Mypets').css('display', '');
					
					if (opt.attr('title') == '')
						$('span.who').html('Выберите питомца');
					else
						$('span.who').html(opt.attr('title'));
					
					par_id = $('#par_category').val();
					if (typeof(obj_typ[par_id]) != 'undefined')
					{
						$('#PetFileds').show();
						$('#GoodsFileds').hide();
					}
					else
					{
						$('#PetFileds').hide();
						$('#GoodsFileds').show();
					}
					
					$('#Step3,#Step4').hide();
				}
				else
					$('#Step2,#Step3,#Step4,#PetFileds,#GoodsFileds').hide();
			});
			
			$('a.editCat').live('click', function() {
				$(".inner-text:first").show();
				$("#steptext").remove();
				
				$('#Step2,#Step3,#Step4,#PetFileds,#GoodsFileds').hide();
				$('#par_category').val(0);
				$('#category').val(0).attr('disabled','disabled');
				$("#done").attr('id', 'Step1');
				return false;
			});
			
			$("#AddPost [name='pet_id']").change(function() {
					$("#AddPost [name='breed_id'], #AddPost [name='breed']").val('');
					
					$('#Mypets').val(0);
					if ($(this).val() != 0){
						$('.sel_bh select, #sex, #no_breed, input[name=color], input[name=breed]').removeAttr('disabled');
						setTimeout('$("#AddPost [name=breed_id]").change();',250);
					}else
						$('.sel_bh select, #sex, #no_breed, input[name=color], input[name=breed]').attr('disabled', 'disabled');
						
					$("#no_breed").removeAttr('checked');
				});
				
			/* порода */
			$("#AddPost [name='breed_id']").change(function() {
					$("#AddPost [name='breed']").val('');
					
					$('#Mypets').val(0);
					var val = $(this).val();
					if (val != 0 && val != 'add' && val != 'search')
						$('.sel_bh select, #sex, #no_breed, input[name=color]').removeAttr('disabled');
					else
						$('.sel_bh select, #sex, #no_breed, input[name=color]').attr('disabled', 'disabled');
					
					if(val!='search')
						$("#AddPost #breedsel_search").hide();
					else
						$("#AddPost #breedsel_search").show().focus();

					if(val!='add')
						$("#AddPost [name='breed_another']").hide();
					else
						$("#AddPost [name='breed_another']").show().focus();

						
					$("#no_breed").removeAttr('checked');
				});
			/* другая порода */
			$("#AddPost [name='breed_another']").change(function() {
					var sel_val = $("#AddPost [name='breed_id']").val();
					if (sel_val == 'add'){
						var val = $(this).val();
						if(val=='')
							$('.sel_bh select, #sex, #no_breed, input[name=color]').attr('disabled', 'disabled');
						else
							$('.sel_bh select, #sex, #no_breed, input[name=color]').removeAttr('disabled', 'disabled');
					}else{
						$('.sel_bh select, #sex, #no_breed, input[name=color]').attr('disabled', 'disabled');
					}
				});
			
			
			$('a.nextStep3').click(function() {
				$('#Step3,#Step4').show();
				$(this).hide();
				return false;
			});
			
			$('[name=title],[name=descr]').keyup(function(){
				var lim = $(this).attr('rel');
				var str = $(this).val();
				if (str.length > lim)
				{
					str = str.substring(0, lim);
					$(this).val(str);
				}	
				var nam = $(this).attr('name');
				$('#count_' + nam).html('(' + (lim - str.length) + ' симв.)');
			});

			$('#Mypets').change(function(){ 
				var mypet = $('#Mypets').val();
				if(mypet.length == 0) 
				{
					$("#AddPost select[name='pet_id'] option[value='']").attr("selected", "selected");
					$("#AddPost select[name='sex'] option:first-child").attr("selected", "selected");
					$("#AddPost input[name='breed']").val('');
					$("#AddPost input[name='breed_id']").val('');        
					$("#AddPost input[name='color']").val('');
					$(".sel_bh select").val('');
					$('.sel_bh select, #sex, #no_breed, input[name=color]').attr('disabled', 'disabled');
				}
				else
				{
					$("#AddPost select[name='pet_id'] option[value=" + My_pets[mypet].pet_id + "]").attr("selected", "selected");
					$("#AddPost select[name='sex'] option[value=" + My_pets[mypet].sex + "]").attr("selected", "selected");
					$("#AddPost input[name='breed_id']").val(My_pets[mypet].breed_id);        
					if (My_pets[mypet].breed_id != 0)
					{
						$('#no_breed').removeAttr('checked');
						$("#AddPost input[name='breed']").removeAttr('disabled').val(My_pets[mypet].breed);
					}
					else
					{
						$('#no_breed').attr('checked', 'checked');
						$("#AddPost input[name='breed']").attr('disabled', 'disabled').val('');
					}
					$('.sel_bh select,#AddPost input[name=color],#AddPost input[name=bdate]').each(function() { $(this).val(My_pets[mypet][$(this).attr('name')]); });
					$('.sel_bh select, #sex, #no_breed, input[name=color]').removeAttr('disabled');
				} 
			});
		 
			$("div.photo-item a").click(function(){
				var namephoto = $(this).attr('rel');
				var bid = $("div.photo-items").attr('id');
				var par_id = $(this).parents('div.photo-item').attr('id');
				
				$.post('/ajax/board/photo/', {namephoto: namephoto, bd: bid }, function(data) {
					if(data.result != 1){
						alert(data.message);
					}else{
						$("div#"+par_id).remove();
						$("div#form_mul").append('<input type="file" name="photo[]"><br/>');
                        ASPhotos.instance().settings.maxSelect++;
					}
				}, "json");
					
				return false;
			}); 

			function check_form()
			{
				if ($('#par_category').length > 0)
				{
					var par_id = $('#par_category').val();
					if (typeof(obj_typ[par_id]) != 'undefined' && $('select[name=pet_id]').val() == 0)
					{
						if($('select[name=pet_id]').hasClass('red')) return false;
						$('select[name=pet_id]').addClass('red').after('<span style="color: red"><br/>Выберите животное</span>');
						$('select[name=pet_id]').focus();
						return false;
					}
					else
						$('select[name=pet_id]').removeClass('red').next('span').remove();
				}
				if($('input[name=title]').val() == '')
				{
					if($('input[name=title]').attr('id') == 'red') return false;
					$('input[name=title]').attr('id','red').after('<span style="color: red"><br/>Укажите заголовок</span>');
					$('input[name=title]').focus();
					return false;
				}
				else
					$('input[name=title]').attr('id','').next('span').remove();    
			  
				if($('textarea[name=descr]').val() == '') 
				{
					if($('textarea[name=descr]').attr('id') == 'red') return false;
					$('textarea[name=descr]').attr('id','red').after('<span style="color: red"><br/>Введите текст</span>');
					$('textarea[name=descr]').focus();
					return false;
				}
				else
					$('textarea[name=descr]').attr('id','').next('span').remove();    
			  
				if($('input[name=author]').val() == '')
				{
					if($('input[name=author]').attr('id') == 'red') return false;
					$('input[name=author]').attr('id','red').after('<span style="color: red"><br/>Укажите имя</span>');
					$('input[name=author]').focus();
					return false;
				}
				else
					$('input[name=author]').attr('id','').next('span').remove();    
			
				var phone = '';
				
				$('.phone input').each(function() { phone = phone + $(this).val(); });
				
				var ph_val = phone.match(/^\d{11,12}$/);
				
				if (ph_val == null)
				{
					if($('.phone input:first').hasClass('red')) return false;
					$('.phone input').addClass('red');
					$('.phone input:last').after('<span style="color: red"><br/>Укажите телефон</span>');
					$('.phone input:first').focus();
					return false;
				}
				else
				{
					$('.phone input').removeClass('red');
					$('.phone input:last').next('span').remove();    
				}
				
				if ($('#city_sel').length > 0)
				{
					var val = $('#city_sel').val();
					
					if (typeof(val) == 'object' || val == '0' || val == '')
					{
						if($('#city_sel').hasClass('red')) return false;
						$('#city_sel').addClass('red').after('<span style="color: red"><br/>Выберите город из списка</span>');
						$('#city_sel').focus();
						return false;
					}
					else
						$('#city_sel').removeClass('red').next('span').remove();    
				}
				
				$('#category').removeAttr('disabled');
				
				return true;
			}

			$("#AddPost").submit(function() { return check_form(); });
			
			$('#preview').show().click(function() { 
				if (check_form() == true)
				{
					arr = {};
					$('#AddPost').find('input[name], select[name], textarea[name]').each(function() { 
						if ($(this).is(':checked') || $(this).not(':checkbox'))
							arr[$(this).attr('name')] = $(this).val();
					});
					
					$.post('/ajax/board/preview/', arr, function(x) { 
						$('#board-post').html(x);
					}, 'html');
				}
					
				return false;
			});
			
			function load_cities()
			{
				$('#city_sel').removeAttr('disabled');
				
				if (cities_loading == false)
				{
					var x = $('#country_sel').val();
					var y = $('#region_sel').val();
					
					if (x != '160') y = '0';
					
					if (typeof(cities[x + '_' + y]) == 'undefined')
					{
						cities_loading = true;
						$('#city_loading').css('display', '');
						
						$.post('/ajax/cities/list/', { country: x, region: y }, function(json) { 
								cities_loading = false;
								$('#city_loading').css('display', 'none');
								if (json.ok == 1)
								{
									cities[x + '_' + y] = json.data;
									fill_cities(x + '_' + y);
								}
								else
									alert(json.msg);
							}, 'json');
					}
					else
						fill_cities(x + '_' + y);
				}
			}
		 
			function fill_cities(x)
			{
				var cont = $('#city_sel');
				cont.children().remove();
				if (typeof(cities[x]) != 'undefined')
				{
					$.each(cities[x], function(key, val) { cont.append('<option value="' + key + '">' + val + '</option>'); });
				}
			}
		 
			function unload_cities()
			{
				$('#city_sel').attr('disabled', 'disabled').children().remove();
			}
		 
			$('#country_sel').change(function() {
				var v = $(this).val();
				if (v != '160')
					$('#region_sel').parent().hide('fast');
				else
					$('#region_sel').parent().show('fast');
					
				if (v == '0')
					unload_cities();
				else
				{
					if ($('#region_sel').val() != '0' || v != '160')
						load_cities();
					else if ($('#region_sel').val() == '0')
						unload_cities();
				}
			});
			
			$('#region_sel').change(function() {
				var v = $(this).val();
				if (v != '0')
					load_cities();
				else
					unload_cities();
			});
			
			$('#no_breed').change(function() { 
				if ($(this).is(':checked'))
					$('[name=breed]').attr('disabled', 'disabled');
				else
					$('[name=breed]').removeAttr('disabled');
			});
			$('.phone input').keyup(function() {
				str = $(this).val();
				str = str.replace(/[^\d]/, '');
				$(this).val(str);
			});
		}); 
	}
});
