var siteGenID = 0;
function genID(){
	return ++siteGenID;
}
 
function isValidEmail (email, strict){
	if ( !strict ) email = email.replace(/^\s+|\s+$/g, '');
	return (/^([a-z0-9_\-]+\.)*[a-z0-9_\-]+@([a-z0-9][a-z0-9\-]*[a-z0-9]\.)+[a-z]{2,4}$/i).test(email);
}
 
function shortIT(el){
	var str = $(el).children("b").html();
	$(el).children("b").html(str.substring(0, (str.length - 4)) + "...");
	if ($(el).width() < ($(el).children("b").width() - 2)) {
		shortIT($(el));
	}
}
 
function shortITa(el){
	var str = $(el).children().html();
	$(el).children().html(str.substring(0, (str.length - 4)) + "...");
	if ($(el).width() < ($(el).children().width() - 4)) {
		shortITa($(el));
	}
}
 
function addField(el){
	if ($(el).parent().find("input:hidden").length > 0) {
		$(el).parent().find("input:visible:last").after("<br />");
		$(el).parent().find("input:hidden:first").show();
	}
}
 
function toggleDisable(){
	if($("#firstStepComplete").attr("disabled") == true){
		$("#firstStepComplete").attr("disabled", false);
	}
	else{
		$("#firstStepComplete").attr("disabled", true);
	}
	return true;
}
 
function changeCityField(el){
	var code = $(el).parent().find("input").hide().attr("rel");
	$(el).parent().find("select").show().find("option:selected").attr("selected", "selected").parent().find("option[value="+code+"]").attr("selected", "selected");
}
function bindReplyButton(id){
	$("body").find("#replyButton").unbind().click(function(e){
		e.preventDefault();
		$.post(
			'http://' + window.location.host + '/index.php',
			{
				id: id,
				action: 'replyRE',
				text: $(this).parent().children('#replyText').val()
			},
			function(){
				alert("Ваше сообщение отправлено");
			}
		);
	});
}
 
function deleteMessage(id, el){
	if(confirm("Удалить сообщение?")){
		$(el).parent().parent().fadeOut("slow",function(){$(this).remove()});
		$.post(
			'http://' + window.location.host + '/index.php',
			{
				id: id,
				action: 'deleteMessage'
			},
			function(data){
			}
		);
	}
}
 
function showFullMessage(id, el){
	$(el).parent().parent().parent().find(".f-yellow2").removeClass("f-yellow2");
	$(el).parent().parent().addClass("f-yellow2");
	$.post(
		'http://' + window.location.host + '/index.php',
		{
			id: id,
			action: 'getMessage'
		},
		function(data){
			$('#fullMessage').html(data);
			bindReplyButton(id);
		}
	);
}
function submitValues(el, id){
	$.post(
		'http://' + window.location.host + '/index.php',
		{
			action: 'torg',
			id: id,
			text: $(el).parent().find('textarea').val(),
			act: $(el).parent().find('input[name=imreq]:checked').val(),
			price: $(el).parent().find('input[name=imreq_price]').val() 
		},
		function(){
			alert("Ваше предложение отправлено");
		}
	);
}
function bindAHREFs(tempID){
	$("tr[rel=" + tempID + "] ul.advert-nav > li > a").unbind().click(function(event){
		event.preventDefault();
		if($(this).attr("rel") != "0"){
			$(this).parent().parent().children("li").children("span").map(function(){
				$(this).replaceWith("<a href='" + $(this).attr("rel") + "' class='" + $(this).attr("cls") + "'>" + $(this).text() + "</a>");
				bindAHREFs(tempID);
			});
			$(this).replaceWith("<span rel='" + $(this).attr("href") + "' cls= '" + $(this).attr("class") + "'>" + $(this).text() + "</span>");
			var href = $(this).attr("href");
			$("tr[rel=" + tempID + "]").children("td").children(".greencont").children(".whitecont").children("div").map(function(){
				if(!$(this).hasClass("advert-sys")){
					if($(this).attr("rel") == href){
						$(this).show();
					}
					else{
						$(this).hide();
					}
				}
			});
			delete href;
		}
	});
}
function GoTo(el){
	$(el).parents().map(function(){
		if(this.tagName == "TR"){
			$(this).find("ul.advert-nav > li > a[href='" + $(el).attr("href") + "']").click();
		}
	});
}
function showEdit(ID, row){
	if($(row).attr("opened") != "1"){
		$(row).unbind("click");
		$(row).attr("opened", "1").addClass("hoverez");
		$("*").addClass("progress");
		$.post(
			document.location.href,
			{
				ID: ID,
				action: 'showEdit'
			},
			function(data){
				$(".progress").removeClass("progress");
				tempID = genID();
				
				$(row).after("<tr class=\"description\" rel=\"" + tempID + "\">" + data + "</tr>");
				
				bindAHREFs(tempID);
				
				$("tr[rel=" + tempID + "] textarea[maxlength]").keypress(function(event){
					var key = event.which;
					if(key >= 32 || key == 13) {
						var maxLength = $(this).attr("maxlength");
						var length = this.value.length;
						if(length >= maxLength) {
							event.preventDefault();
						}
					}
				});
				var SI = "";
				$("tr[rel=" + tempID + "] input[name='short_text']").focus(function(){
					var input = $(this);
					if(SI == ""){
						SI = window.setInterval(function(){
							var val = $(input).val();
							var len = 51 - val.length;
							$("tr[rel=" + tempID + "] .remain").html(len);
							delete len;
							delete val;
						}, 20);
					}
					delete input;
				}).blur(function(){
					if(SI != ""){
						window.clearInterval(SI);
						SI = "";
					}
				});
				delete SI;
				$("tr[rel=" + tempID + "] .plugin_numeric").numeric();
				$("tr[rel=" + tempID + "] .redfoto td a").fancybox({
					'zoomSpeedIn':300, 
					'zoomSpeedOut':300, 
					'overlayShow':true
				}).parent().parent()
				.find(".delimg strong").click(function(event){
					event.preventDefault();
					if(confirm("Вы уверены что хотите удалить изображение?")){
						var rel = $(this).parent().children("a").attr("rel");
						var parent = $(this).parent();
						delete rel;
						$(parent).before("<input type='file' name='foto" + rel + "' />");
						$(parent).remove();
						delete parent;
					}
				});
				
				/*$("tr[rel=" + tempID + "] div[rel=#fixator] .redprice input[name=cost]").change(function(){
					$(this).parent().parent().find(".canDisable").addClass("disabled").find("input").attr("disabled", true).attr("checked", false);
					$(this).parent().next().removeClass("disabled").find("input").attr("disabled", false);
				});*/
			}
		);
	}
	else{
		$(row).attr("opened", "0").removeClass("hoverez");
		$(row).next("tr.description").remove();
	}
}
function showMore(ID, row){
	if($(row).attr("opened") != "1"){
		$(row).unbind("click");
		$(row).attr("opened", "1").addClass("hoverez");
		$("*").addClass("progress");
		//$("body").addClass("progress");
		$.post(
			document.location.href,
			{
				ID: ID,
				ajax: 'true'
			},
			function(data){
				$(".progress").removeClass("progress");
				tempID = genID();
				var ViewCountTD = $(row).children("td:last");
				ViewCountTD.html(parseInt(ViewCountTD.html()) + 1);
				delete ViewCountTD
				$(row).after("<tr class=\"description\" rel=\"" + tempID + "\">" + data + "</tr>");
				$("tr[rel=" + tempID + "] div.hidden").hide();
				$("tr[rel=" + tempID + "] div.hidden:first").show(-1, function(){
					$("tr[rel=" + tempID + "]").find("a[href=" + $(this).attr("rel") + "]").map(function(){
						$(this).replaceWith("<span rel='" + $(this).attr("href") + "'>" + $(this).text() + "</span>");
					});
				});
				bindAHREFs(tempID);
				var bigPhoto = $("tr[rel=" + tempID + "] table.advert-img td:eq(0)").children("img");
				$("tr[rel=" + tempID + "] table.advert-img td:eq(1)").children("a").map(function(id){
					var link = $(this);
					$(this).click(function(event){
						event.preventDefault();
						$(bigPhoto).attr("src",$(link).attr("href"));
					});
					delete link;
				});
				delete bigPhoto;
				$("textarea[name='reply_text']").keypress(function(event){
					var key = event.which;
					if(key >= 32 || key == 13) {
						var maxLength = $(this).attr("maxlength");
						var length = this.value.length;
						if(length >= maxLength) {
							event.preventDefault();
						}
						delete length;
						delete maxLength;
					}
					delete key;
				});
				var SI = "";
				$("textarea[name='reply_text']").unbind("focus").focus(function(){
					if(SI == ""){
						SI = window.setInterval(function(){
							var val = $("textarea[name='reply_text']").val();
							var len = 120 - val.length;
							$("input[name='obyav_reply_left']").val(len);
							delete len;
							delete val;
						}, 20);
					}
				}).unbind("blur").blur(function(){
					if(SI != ""){
						window.clearInterval(SI);
						SI = "";
					}
				});
				delete SI;
				$(".plugin_numeric").numeric();
			}
		);
	}
	else{
		$(row).attr("opened", "0").removeClass("hoverez");
		$(row).next("tr.description").remove();
	}
}
function showMoreGal(ID, li){
	$(li).unbind("click");
	if ($(li).attr("opened") != "1") {
		$(li).parent().children(".hoverez").removeClass("hoverez");
		$(li).parent().children("li[opened=1]").attr("opened", "0");
		$(li).attr("opened", "1").addClass("hoverez");
		$.post(document.location.href, {
			ID: ID,
			fullTable: 'true',
			ajax: 'true'
		}, function(data){
			tempID = genID();
			$(li).parent().next("table").remove();
			$(li).parent().after("<table>" + data + "</table>");
			$(li).parent().next("table").children("tbody").children("tr:eq(1)").attr("rel", tempID);
			$("tr[rel=" + tempID + "] div.hidden").hide();
			$("tr[rel=" + tempID + "] div.hidden:first").show(-1, function(){
				$("tr[rel=" + tempID + "]").find("a[href=" + $(this).attr("rel") + "]").map(function(){
					$(this).replaceWith("<span rel='" + $(this).attr("href") + "'>" + $(this).text() + "</span>");
				});
			});
			bindAHREFs(tempID);
			$(".briefly .city").each(function(){
				if ($(this).width() < ($(this).children("b").width() - 4)) {
					$(this).children("b").html($(this).children("b").html() + "...");
					shortIT($(this));
				}
			});
			
			var bigPhoto = $("tr[rel=" + tempID + "] table.advert-img td:eq(0)").children("img");
			$("tr[rel=" + tempID + "] table.advert-img td:eq(1)").children("a").map(function(id){
				var link = $(this);
				$(this).click(function(event){
					event.preventDefault();
					$(bigPhoto).attr("src", $(link).attr("href"));
				});
			});
			delete bigPhoto;
			$("textarea[name='reply_text']").unbind("keypress").keypress(function(event){
				var key = event.which;
				if (key >= 32 || key == 13) {
					var maxLength = $(this).attr("maxlength");
					var length = this.value.length;
					if (length >= maxLength) {
						event.preventDefault();
					}
					delete length;
					delete maxLength;
				}
				delete key;
			});
			var SI = "";
			$("textarea[name='reply_text']").unbind("focus").focus(function(){
				if (SI == "") {
					SI = window.setInterval(function(){
						var val = $("textarea[name='reply_text']").val();
						var len = 120 - val.length;
						$("input[name='obyav_reply_left']").val(len);
						delete len;
						delete val;
					}, 20);
				}
			}).unbind("blur").blur(function(){
				if (SI != "") {
					window.clearInterval(SI);
					SI = "";
				}
			});
			delete SI;
			$(".plugin_numeric").numeric();
		});
	}
	else{
		$(li).attr("opened", "0").removeClass("hoverez");
		$(li).parent().next("table").remove();
	}
}
function addToFavorites(id, a){
	$.post(
		document.location.href,
		{
			action: 'toFavorites',
			ID: id,
			ajax: 'true'
		},
		function(data){
			if(data == '1'){
				$(a).html("Удалить объявление из избранного");
				if($("tr.briefly[rel=" + id + "]").children("td").eq(2).html() == "&nbsp;"){
					$("tr.briefly[rel=" + id + "]").children("td").eq(2).html("<img src='/images/ic/star.png' alt='фото " + $("tr.briefly[rel=" + id + "]").children("td").eq(3).html() + "' />");
				}
			}
			else if(data == '0'){
				$(a).html("Добавить объявление в избранное");
				$("tr.briefly[rel=" + id + "]").children("td").eq(2).html("&nbsp;");
			}
			else if(data == '3'){
				alert('Внимание, Достигнут лимит добавления в избранное!');
			}
			else{
				alert('Ошибка при добавлении!');
				//$(a).html("Ошибка при добавлении");
			}
		}
	);
}
function submitBestService(el){
	$(el).parent().parent().append("<input type='hidden' value='bestservice' name='action' />");
	$(el).parent().parent().attr("action", "/").submit();
}
 
$(function(){
 
	/* Круглые уголки */
	$(".container").after("<div class='shadow'><b></b><em></em></div>");
	$(".container").before("<div class='top'><b class='b4'><em></em></b><b class='b3'><em></em></b><b class='b2'><em></em></b><b class='b1'><em></em></b></div>");
	$(".container").after("<div class='bottom'><b class='b1'><em></em></b><b class='b2'><em></em></b><b class='b3'><em></em></b><b class='b4'><em></em></b></div>");
	/* $(".sitem-bar .tabs div a, .sitem-bar .tabs div span").before("<u></u>");
	$(".sitem-bar .tabs div span").before("<u></u><i></i>"); */
	$(".advert-nav a, .advert-nav span, .advert-nav b").before("<em></em>");
 
	/* AJAX селекторы */
	$("select[rel=selLvl1]").change(function(){
		if (window.location.href != "http://" + window.location.host + "/moi_obyavleniya/add/" && window.location.href != "http://" + window.location.host + "/add_obyavleniya/" && window.location.href != "http://" + window.location.host + "/sdelaem_servis_luchshe/") {
			if ($(this).children("option:selected").attr("rel") != undefined) {
				//window.location.href = "http://" + $(this).children("option:selected").attr("rel") + ".proforum.ru/";
				window.location.href = "http://" + window.location.host + "/catalog/" + $(this).children("option:selected").attr("rel") + "/";
			}
			else{
				window.location.href = "/";
			}
		}
		else {
			var loc = window.location;
			$.post("http://" + window.location.host + "/index.php", {
				a: "requestOption",
				id: $(this).val()
			}, function(data){
				$("select[rel=selLvl2]").html("<option value='0'>Подкатегория:</option>" + data);
				$("select[rel=selLvl3]").html("<option value='0'>Раздел:</option>");
			});
		}
	});
	$("select[rel=selLvl2]").change(function(){
		if (window.location.href != "http://" + window.location.host + "/moi_obyavleniya/add/" && window.location.href != "http://" + window.location.host + "/add_obyavleniya/" && window.location.href != "http://" + window.location.host + "/sdelaem_servis_luchshe/") {
			if ($(this).children("option:selected").attr("rel") != undefined) {
				window.location.href = "http://" + window.location.host + "/catalog/" + $("select[rel=selLvl1] > option:selected").attr("rel") + "/" + $(this).children("option:selected").attr("rel") + "/";
			}
			else {
				window.location.href = "http://" + window.location.host + "/catalog/" + $("select[rel=selLvl1] > option:selected").attr("rel") + "/";
			}
		}
		else {
			$.post("http://" + window.location.host + "/index.php", {
				a: "requestOption",
				id: $(this).val()
			}, function(data){
				$("select[rel=selLvl3]").html("<option value='0'>Раздел:</option>" + data);
			});
		}
	});
	$("select[rel=selLvl3]").change(function(){
		if (window.location.href != "http://" + window.location.host + "/moi_obyavleniya/add/" && window.location.href != "http://" + window.location.host + "/add_obyavleniya/" && window.location.href != "http://" + window.location.host + "/sdelaem_servis_luchshe/") {
			if ($(this).children("option:selected").attr("rel") != undefined) {
				window.location.href = "http://" + window.location.host + "/catalog/" + $("select[rel=selLvl1] > option:selected").attr("rel") + "/" + $("select[rel=selLvl2] > option:selected").attr("rel") + "/" + $(this).children("option:selected").attr("rel") + "/";
			}
			else {
				window.location.href = "http://" + window.location.host + "/catalog/" + $("select[rel=selLvl1] > option:selected").attr("rel") + "/" + $("select[rel=selLvl2] > option:selected").attr("rel") + "/";
			}
		}
	});
 
	/* Убираем длинные названия городов */
	$(".briefly .city").each(function(){
		if($(this).width() < ($(this).children("b").width() - 2)){
			$(this).children("b").html($(this).children("b").html() + "...");
			shortIT($(this));
		}
	});
	
	$(".briefly .shortit").each(function(){
		if($(this).width() < ($(this).children().width() - 4)){
			$(this).children().html($(this).children().html() + "...");
			shortITa($(this));
		}
	});
 
 
	/* Расширенное объявление */
	$(".briefly")/*.click(function(){
		if($(this).attr("rel") != "" && $(this).attr("rel") != undefined){
			showMore($(this));
		}
	})*/.mouseover(function(){
		$(this).addClass("hover");
	}).mouseout(function(){
		$(this).removeClass("hover");
	});
	$("a[rel='obyavLink']").map(function(){
		$(this).replaceWith("<span>" + $(this).html() + "</span>")
	});/*click(function(event){
		event.preventDefault();
	});*/
 
	$(".listprod > li").click(function(){
		showMoreGal($(this));
	}).mouseover(function(){
		$(this).addClass("hover");
	}).mouseout(function(){
		$(this).removeClass("hover");
	});
	
	/* Регистрация */
	$("#firstStepComplete").click(function(event){
		event.preventDefault();
		if($("#licensetext").val() == "on"){
			$(this).parent().submit();
		}
	});
	$("#secondStepComplete").click(function(event){
		event.preventDefault();
		$("input[name='email']").css({"border-color":"#000"});
		if(!isValidEmail($("input[name='email']").val())){
			$("input[name='email']").css({"border-color":"#f00"});
		}
		else{
			$(this).parent().append("<input type='hidden' name='nickname' value='"+$("input[name='nickname']").val()+"' />");
			$(this).parent().append("<input type='hidden' name='first_name' value='"+$("input[name='first_name']").val()+"' />");
			$(this).parent().append("<input type='hidden' name='last_name' value='"+$("input[name='last_name']").val()+"' />");
			$(this).parent().append("<input type='hidden' name='country' value='"+$("select[name='country']").val()+"' />");
			$(this).parent().append("<input type='hidden' name='city' value='"+$("select[name='city']").val()+"' />");
			$(this).parent().append("<input type='hidden' name='email' value='"+$("input[name='email']").val()+"' />");
			$(this).parent().append("<input type='hidden' name='cell' value='"+$("input[name='cell']").val()+"' />");
			$(this).parent().append("<input type='hidden' name='phone' value='"+$("input[name='phone']").val()+"' />");
			$(this).parent().append("<input type='hidden' name='password' value='"+$("input[name='password']").val()+"' />");
			$(this).parent().append("<input type='hidden' name='repassword' value='"+$("input[name='repassword']").val()+"' />");
			$(this).parent().submit();
		}
	});
	$("#thirdStepComplete").click(function(event){
		event.preventDefault();
		var mobile = $(this).parent().parent().find("input[name=mobile]").val();
		var remobile = $(this).parent().parent().find("input[name=mobile_re]").val();
		var code = $(this).parent().parent().find("input[name=code]").val();
		var reply_code = $(this).parent().parent().find("input[name=reply_code]").val();
		
		if ($(this).parent().parent().find("input[name=mobile_re]").val() == mobile && mobile != "") {
			$(this).parent().append("<input type='hidden' name='mobile' value='" + mobile + "' />");
			$(this).parent().append("<input type='hidden' name='code' value='" + code + "' />");
			$(this).parent().append("<input type='hidden' name='reply_code' value='" + reply_code + "' />");
			
			$(this).parent().append("<input type='hidden' name='checked' value='true' />");
			$(this).parent().submit();
		}
		else{
			alert('Пожалуйста введите номер Вашего мобильного телефона!');
		}
	});
	
 
	$(".plugin_numeric").numeric();
 
	$("input[name='price']").numeric();
	$("textarea[maxlength]").keypress(function(event){
		var key = event.which;
		if(key >= 32 || key == 13) {
			var maxLength = $(this).attr("maxlength");
			var length = this.value.length;
			if(length >= maxLength) {
				event.preventDefault();
			}
			delete maxLength;
			delete length;
		}
		delete key;
	});
	var SI = "";
	$("input[name='short_text']").focus(function(){
		if(SI == ""){
			SI = window.setInterval(function(){
				var val = $("input[name='short_text']").val();
				var len = 51 - val.length;
				$("input[name='short_text_left']").val(len);
				delete len;
				delete val;
			}, 20);
		}
	}).blur(function(){
		if(SI != ""){
			window.clearInterval(SI);
			SI = "";
		}
	});	
	delete SI;
	$("#add_bullet").submit(function(event){
		if($(this).children("input[name='notbot']").val() != "yes"){
			event.preventDefault();
			$(this).find("select").css({"border-color":"#000"});
			var isError = 0;
			if($(this).find("select[name='category_lv3']").val() == "0"){
				$(this).find("select[name='category_lv3']").css({"border-color":"#f00"});
				isError++;
				if($(this).find("select[name='category_lv2']").val() == "0"){
					$(this).find("select[name='category_lv2']").css({"border-color":"#f00"});
					isError++;
					if($(this).find("select[name='category_lv1']").val() == "0"){
						$(this).find("select[name='category_lv1']").css({"border-color":"#f00"});
						isError++;
					}
				}
			}
			if($(this).find("input[name=short_text]").val() == ""){
				alert("Пожалуйста, заполните основные поля: \"Основное краткое описание\" и \"Полный текст объявления\"");
				isError++;
			}
			if($(this).find("input[name=full_text]").val() == ""){
				alert("Пожалуйста, заполните основные поля: \"Основное краткое описание\" и \"Полный текст объявления\"");
				isError++;
			}
			if(isError == 0){
				$(this).attr("action","/moi_obyavleniya/add/").attr("method","POST").append("<input type='hidden' value='yes' name='notbot' />");
				$(this).submit();
			}
		}
		else{
		}
	});
	$("#add_bullet_temp").submit(function(event){
		if($(this).children("input[name='notbot']").val() != "yes"){
			event.preventDefault();
			$(this).find("select").css({"border-color":"#000"});
			var isError = 0;
			if($(this).find("select[name='category_lv3']").val() == "0"){
				$(this).find("select[name='category_lv3']").css({"border-color":"#f00"});
				isError++;
				if($(this).find("select[name='category_lv2']").val() == "0"){
					$(this).find("select[name='category_lv2']").css({"border-color":"#f00"});
					isError++;
					if($(this).find("select[name='category_lv1']").val() == "0"){
						$(this).find("select[name='category_lv1']").css({"border-color":"#f00"});
						isError++;
					}
				}
			}
			if(isError == 0){
				$(this).attr("action","/add_obyavleniya/").attr("method","POST").append("<input type='hidden' value='yes' name='notbot' />").submit();
			}
		}
	});
	
	
	$("#nav_places li a").click(function(e){
		e.preventDefault();
		$(this).parent().parent().find(".active").removeClass("active");
		$(this).parent().addClass("active");
		$(this).parent().parent().parent().children("div").hide();
		$(this).parent().parent().parent().children("div[rel=" + $(this).attr("href") + "]").show();
	});
	
	
	/* Ровное построение блоков каталога на главной */
	$('.wrap').masonry(); 
	$(window).resize(function() {
		$('.wrap').masonry();
	});
	
	$("input[name=nickname]").blur(function(){
		
	});
	
	$("#nastroyka_form").find("input[value!='']:hidden").map(function(){
		$(this).show();
		$(this).before("<br />");
	})
});
