var arCCAddParams = {},
	mode = "";

function  mark_form(n,elem)
{
	if (n == 1)
		elem.style.background="#fbe5e5"; else elem.style.background="#FFF";
};

function checkform(formid)
{
	var required_arr = as.$(".required");
	var required_flag = 0;


	for (var i = 0; i < required_arr.length; i++)
	{
		switch(required_arr[i].type)
		{
			default:
				if (required_arr[i].value == '')
				{
					required_flag = 1;
					mark_form(1, required_arr[i]);
				}
				else
					mark_form(0,required_arr[i]);

				break;
			case("checkbox"):
				if (required_arr[i].checked == false)
				{
					required_flag = 1;
					mark_form(1, required_arr[i]);
				}
				else
					mark_form(0, required_arr[i]);

				break;
		}
	}

	if (required_flag)
		alert("Необходимо заполнить обязательные поля");
	else
		document.getElementById(formid).submit();
};



function getXmlHttp()
{
	var xmlhttp;
	try
	{
		xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
	}
	catch (e)
	{
		try
		{
			xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
		}
		catch (E)
		{
			xmlhttp = false;
		}
	}
	if (!xmlhttp && typeof XMLHttpRequest!='undefined')
		xmlhttp = new XMLHttpRequest();

	return xmlhttp;
}

function voteitem(itemid,f,act)
{
	var xmlhttp = getXmlHttp()

	var url = "/vote/" + itemid + "/" + f + "/" + act + "/" + Math.random();

	if (document.getElementById("itemrating" + itemid + "f" + f))
	{
		xmlhttp.open("GET", url, true);
		xmlhttp.onreadystatechange = function()
		{
			if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
			{
				document.getElementById("itemrating" + itemid + "f" + f).innerHTML = xmlhttp.responseText;
				document.getElementById("itemmark" + itemid + "f" + f).style.display = "none";
			}
		}
		xmlhttp.send(null);
	}
}

function ask_photo_delete()
{
	var h = document.getElementById("pica").offsetHeight;

	document.getElementById("askshadow").style.height = h + "px";
	document.getElementById("asktable").style.height = h + "px";

	if (document.getElementById("askdelete").style.display == "block")
		document.getElementById("askdelete").style.display = "none";
	else
		document.getElementById("askdelete").style.display = "block";
}


function voteresponse(itemid, act, current_sum, current_total)
{
	var xmlhttp = getXmlHttp()
	var url = "/vote/" + itemid + "/31/" + act + "/" + Math.random();

	if (document.getElementById("itemrating" + itemid))
	{
		xmlhttp.open("GET", url, true);
		xmlhttp.onreadystatechange = function()
		{
			if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
			{
				if (act == 1)
					current_sum = current_sum + 1;
				else
					current_sum = current_sum - 1;

				current_total = current_total + 1;

				var new_res = (current_total + current_sum) / 2;
				document.getElementById("itemrating" + itemid).innerHTML = '<b>' + new_res + '</b> из <b>' + current_total + '</b> сочли отзыв полезным.';
				document.getElementById("itemmark" + itemid + "f31").style.display = "none";
			}
		}
		xmlhttp.send(null);
	}
}

function switch_nav()
{
	document.getElementById("pagesline1").style.display="none";
	document.getElementById("pagesline2").style.display="block";
}

function num_form(n, forms)
{
	return (((n%10) == 1 && (n%100) != 11) ? forms[0] : ((n%10) >= 2 && (n%10) <= 4 && ((n%100) < 10 || (n%100) >= 20) ? forms[1] : forms[2]));
}

function trim(s)
{
	s = s.replace( /^\s+/g, "");
	return s.replace( /\s+$/g, "");
}

function joinClubResp(data)
{
	var oResp = eval("(" + data + ")");
	//console.log(oResp);
	switch(oResp.status)
	{
		case(0):
			alert("Не корректные данные");
		break;
		case(1):
			alert("Вы уже состоите в данном клубе");
		break;
		case(2):
			alert("Вы пытаетесь вступить в не существующий клуб");
		break;
		case(3):
			alert("Вступать в клуб могут только авторизованные пользователи");
		break;
		case(5):
			if ((oResp.visitors * 1) == 1)
			{
				as.$$("#cnt_club_visitors").innerHTML = '<span id="club_visitors_'+oResp.id+'" class="visitors">'+oResp.visitors+'</span><a href="/clubs/'+oResp.id+'/visitors/">посетителей</a> ';
				as.$$("#do_"+oResp.id).innerHTML = 'Присоединиться';
			}
			as.$$("#club_visitors_" + oResp.id).innerHTML = oResp.visitors;
			//$("do_" + oResp.id).innerHTML = "выйти";
		break;
	}
}

function joinClubReq(id, action)
{
	var url = "/" + city + "/clubs/join/" + id + "/" + action;
	//console.log(url);
	as.ajax(url, joinClubResp);
}

function cc_show_form_add_product2diary(id, name, c)
{	arCCAddParams["id"] = id;
	arCCAddParams["name"] = name;
	arCCAddParams["c"] = c;
	$("div.btn_add2diary_diet ul.cat li").removeClass("active");
	$("div.btn_add2diary_diet div.cat_content div.content").hide();

	$("#content_4 div.add_wrap input").val("");
	$("div.btn_add2diary_diet div.cat_content div#content_4 h3").html(name);
	$("div.btn_add2diary_diet div.cat_content div#content_4 div.caloric_content").html((mode == "diet" ? "Калорийность на 100г продукта: " : "Расход калорий в час: ") + c + " Ккал");
	$("div.btn_add2diary_diet div.cat_content div#content_4").show();
}

function photo_show(img)
{
	var ar_src2 = as.$$("#photo_1").src.split("/");
	var ar_src = img.src.split("/");
	var cn2 = ar_src2.length;
	var cn = ar_src.length;

	as.$$("#photo_1").src = "/" + ar_src[(cn - 3)] + "/400_400_80/" + ar_src[(cn - 1)];
	img.src = "/" + ar_src2[(cn2 - 3)] + "/400_80_95/" + ar_src2[(cn2 - 1)];
}

function show_form_auth()
{
	as.$$("#form_login_div").style.left = "50%";
	as.$$("#form_login_div_bg").style.left = "50%";
}

function reg_user_in_social()
{

}

function constructUrl()
{
}

function ConfirmBox(){}
ConfirmBox.prototype = {
	show: function() {
		//this.wrapper.toggleClass("hidden");
		//as.w("div.darkening").toggleClass("hidden");
		this.wrapper.removeClass("hidden");
		$("div.darkening").removeClass("hidden");
	},
	hide: function() {
		//this.wrapper.toggleClass("hidden");
		//as.w("div.darkening").toggleClass("hidden");
		this.wrapper.remove();
		$("div.darkening").remove();
	},
	init: function(oParm) {		if (!$("div.confirm_box").length)
			$("body").append('<div class="confirm_box"><div class="confirm_bg"></div><div class="confirm"><div id="confirm_msg"></div><div class="confirm_btn"><div class="button_pink_bg"><span id="btn_msg_ok"></span><div class="button_pink_bg_right"></div></div><div id="cancel"></div></div></div></div><div class="darkening"></div>');
		this.wrapper = $("div.confirm_box");
		this.fn = oParm.fn;
		this.msg = oParm.msg;
		this.btnOkText = oParm.btnOkText || "Да";
		this.btnCancelText = oParm.btnCancelText || "отменить";

		$("span#btn_msg_ok", this.wrapper).html(this.btnOkText);
		$("div#cancel", this.wrapper).html(this.btnCancelText);
		$("div#confirm_msg", this.wrapper).html(this.msg);
		setTimeout(function(){			$("div.confirm_bg, div.confirm").height(105 + $("div.confirm div#confirm_msg").height());
		}, 10);
		this.show();

		var self = this;
		$("div.button_pink_bg", this.wrapper).click(function() {
			try {
				self.fn && self.fn();
			}
			catch(e) {}
			self.hide();
		});

		$("div#cancel", this.wrapper).click(function() {
			self.hide();
		});
	}
}

$(function(){
	var bIsCCSearch = null,
		sCCSearch = "";

	oConfirmBox = new ConfirmBox();
	//oConfirmBox.init({msg:"Закрыть?", fn:function(){}, btnOkText:"Да", btnCancelText:"отменить"});

	$("a#text_about_view").click(function(){
		$("#text_about").show();
		$("#text_about_view").remove();
	});

	$(".header .userinfo .enter .exit, div.head div.user_info a.exit").click(function(){
		try {
			doLogout();
			mailru.connect.logout();
			FB.logout(function(response) {
				// user is now logged out
			});
		} catch(e) {

		}

		setTimeout('window.location="http://www.fittrends.ru/exit"', 1000);

		return false;
	});

	$("div.calc_calories div.period span").click(function(){
		var id = this.id.replace("calc_calories_period_", "") * 1,
			uid = as.$$("div.calc_calories div.charts").id.replace("charts_calc_calories_profile_", "") * 1,
			date = new Date(),
			r = date.getTime();

		as.w("div.calc_calories div.period span").each(function(){
			this.className = this.className.replace("active", "");
		});

		as.$$("div.calc_calories div.period span#calc_calories_period_" + id).className = "active";
		as.$$("div.calc_calories div.charts img.weigth").src = "/calculator-calories/chart/" + uid + "/" + id + "/weigth/" + r;
		as.$$("div.calc_calories div.charts img.calories").src = "/calculator-calories/chart/" + uid + "/" + id + "/" + r;
	});

	$("a.available_services_show_hide").click(function(){
		/*
		var bHasClass = /show_all/.test(as.$$("div.available_services_wrap").className);

		if (bHasClass)
		{
			as.$$("div.available_services_wrap").style.maxHeight = "470px";
			as.w("div.available_services_wrap").removeClass("show_all");
			as.w("a.available_services_show_hide").html("Больше параметров &rarr;");
		}
		else
		{
			as.$$("div.available_services_wrap").style.maxHeight = "2000px";
			as.w("div.available_services_wrap").addClass("show_all");
			as.w("a.available_services_show_hide").html("&larr; Меньше параметров");
		}
		*/

		var s = $("#frm_clubs_filter").attr("action").split("/");
		s = s[3].replace(/S/, "").split("-");
		//console.log(s);
		$(".filter_short").toggle();
		$(".filter_full").toggle();

		$(".available_services_checkbox").each(function(){
			var id = $(this).attr("id").replace(/available_services_short\[/, "").replace(/available_services_full\[/, "").replace("]", "");

			$(this).attr("checked", false);

			for (var key in s)
			{
				//console.log(id + " " +s[key]);
				if (id == s[key])
					$(this).attr("checked", true);
			}

			//alert($(this).attr("checked"));
		});
	});

	as.w("div#form_login_div div.btn").click(function(){
		var login = trim(as.$$("div#form_login_div #login2").value),
			pwd = trim(as.$$("div#form_login_div #pwd2").value),
			remember = as.$$("div#form_login_div #remember").checked,
			date = new Date(),
			r = date.getTime();

		as.ajax_new({
			url:"/register/auth/enter/"+r,
			callback:function(json) {
				var oJson = eval("(" + json + ")");

				if (oJson.status == 1)
				{
					window.location.assign(oJson.url);
				}
				else
				{
					switch(oJson.err)
					{
						case 30001:
							alert("Не верная комбинация логин/пароль");
							break;
						case 30003:
							alert("Учетная запись была заблокирована администратором");
							break;
						case 30002:
							alert("Регистрация не подтверждена");
							break;
						case 30004:
							alert("Не указан логин или пароль");
							break;
						default:
							alert("Ошибка");
							break;
					}
				}
			},
			type:"POST",
			data:"login="+login+"&password="+pwd+"&remember="+remember+"&ajax=y"
		});
	});

	as.w("div#form_login_div div.close").click(function(){
		as.$$("#form_login_div").style.left = "-2000px";
		as.$$("#form_login_div_bg").style.left = "-2000px";

		as.$$("div#form_login_div #login2").value = "";
		as.$$("div#form_login_div #pwd2").value = "";
	});

	as.w("div#form_login_div .social_network .vk").click(function(){
		doLogin();
	});

	if ($("input.attached_select").length)
	{
		$("input.attached_select").click(function(){
			var p = $(this).val();

			$("tr.attached_tr").hide();
			$("tr#attached_" + p).show();
		});

		$("tr.attached_tr").hide();
	}

	$("div.btn_add2diary_diet ul.tabs li").click(function(){		var title = $(this).html().replace(/<div><\/div>/, "").toLowerCase();
			btn_title = title == "другое" || mode == "activity" ? "Добавить" : "Добавить к " + title + "у";
		$("div.btn_add2diary_diet ul.tabs li").removeClass("active");
		$("div.btn_add2diary_diet ul.cat li:eq(0)").click();

		arCCAddParams["type"] = $("div.btn_add2diary_diet ul.tabs li").index($(this));

		$(this).addClass("active");
		$("div.btn_add2diary_diet div.panel_wrap div.head label").html($(this).attr("title") + ":");
		$("#content_4 div.add_wrap div.btn_blue span").html(btn_title)

		if (!$("div.btn_add2diary_diet div.panel_wrap").hasClass("open"))
		{
			$("div.btn_add2diary_diet div.panel_wrap").addClass("open").show("blind", {direction:"vertical"});
			if ($("table.diary4day").length)
				$("div.separator_height").animate({"height": "395px"}, 500);
		}

		$("div.panel_wrap div.panel div.head div#calories_search_res").css({
			"left": ($("div.panel_wrap div.panel div.head input").offset().left - $("div.panel_wrap div.panel div.head").offset().left) + "px"
		});

	});

	$("div.btn_add2diary_diet ul.cat_items").each(function(){
		 $("li:last", $(this)).addClass("last");
	});

	$("div.btn_add2diary_diet ul.products li.cat_rwap").click(function(){
		$("ul", $(this)).toggle("slider");
	});

	$("div.btn_add2diary_diet ul.products li.cat_rwap ul li, ul.products_last li").click(function(){		var id = ($(this).attr("id").replace(/product_/, "") * 1),
			caloric_content = $("span", $(this)).html(),
			reg = new RegExp("<span>"+caloric_content+"<\/span>", "i"),
			name = $(this).html().replace(reg, "");

		cc_show_form_add_product2diary(id, name, caloric_content);	});

	$("div.panel_wrap div.panel div.head input").keyup(function(){		sCCSearch = $(this).val();
		if (typeof bIsCCSearch != "undefined")			clearInterval(bIsCCSearch);

		bIsCCSearch = setInterval(function(){			//console.log(sCCSearch);			$.ajax({
				type: "POST",
				url: "/calculator-calories/search",
				data: "search=" + sCCSearch + "&mode=" + mode,
				success: function(html){
					$("div#calories_search_res").html(html);
					if ($.trim(html).length)
						$("div#calories_search_res").show();
					else
						$("div#calories_search_res").hide();

					$("div#calories_search_res li").click(function(){						var id = ($(this).attr("id").replace(/product_/, "") * 1),
							caloric_content = $("span", $(this)).html(),
							reg = new RegExp("<span>"+caloric_content+"<\/span>", "i"),
							name = $(this).html().replace(reg, "");
						cc_show_form_add_product2diary(id, name, caloric_content);						$(this).parent().parent().hide();
						$("div.panel_wrap div.panel div.head input").val("");					});
				}
			});
			clearInterval(bIsCCSearch);
		}, 500);
	});

	$("div.btn_add2diary_diet ul.cat li").click(function(){
		$("div.btn_add2diary_diet ul.cat li").removeClass("active");
		$("div.btn_add2diary_diet div.cat_content div.content").hide();
		$("div.btn_add2diary_diet ul.products li.cat_rwap ul").hide();

		$(this).addClass("active");
		$("div.btn_add2diary_diet div.cat_content div#content_" + $("div.btn_add2diary_diet ul.cat li").index($(this))).show();
	});

	$("div.wrap_add_item_new div.btn_blue").click(function(){		var arPost = {};
		arPost["mode"] = mode;
		arPost["name"] = $("#item_new_name").val();
		arPost["cc"] = $("#item_new_cc").val();
		arPost["cat"] = $("#item_new_cat").val();

		$.ajax({
			type: "POST",
			url: "/calculator-calories/add-item-new",
			data: arPost,
			dataType: "html",
			success: function(html){				$("#item_new_name").val("");
				$("#item_new_cc").val("");
				$("#item_new_cat").val("");
				$("div.btn_add2diary_diet ul.cat li:eq(0)").click();
				alert("Спасибо, после проверки будет доступен в списке");
			}
		});	});

	$("#content_4 div.to_favorites").click(function(){		arCCAddParams["mode"] = mode;

		$.ajax({
			type: "POST",
			url: "/calculator-calories/to_favorites",
			data: arCCAddParams,
			dataType: "html",
			success: function(html){				if ($.trim(html).length)
				{
					$("div#content_1").html(html);

					$("div#content_1 ul.products_last li").click(function(){
						var id = ($(this).attr("id").replace(/product_/, "") * 1),
							caloric_content = $("span", $(this)).html(),
							reg = new RegExp("<span>"+caloric_content+"<\/span>", "i"),
							name = $(this).html().replace(reg, "");

						cc_show_form_add_product2diary(id, name, caloric_content);
					});
				}
			}
		});	});

	$("#content_4 div.add_wrap div.btn_blue").click(function(){		arCCAddParams["mode"] = mode;		if (mode == "diet")
		{			arCCAddParams["weight"] = ($("#content_4 div.add_wrap input#weight").val().replace(/,/, ".") * 1);
			arCCAddParams["time_h"] = ($("#content_4 div.add_wrap input#time_h").val() * 1);
			arCCAddParams["time_m"] = ($("#content_4 div.add_wrap input#time_m").val() * 1);
		}
		else
		{
			arCCAddParams["duration_h"] = ($("#content_4 div.add_wrap input#duration_h").val() * 1);
			arCCAddParams["duration_m"] = ($("#content_4 div.add_wrap input#duration_m").val() * 1);
		}
		//console.log(arCCAddParams);

		$.ajax({
			type: "POST",
			url: "/calculator-calories/add",
			data: arCCAddParams,
			dataType: "json",
			success: function(json){				var status = (json.status * 1);

				if (status == 1)
				{					$("div.contentleft table.t1 td.vtp div.cnt_wrap").html(json.html);
					$("div.btn_add2diary_diet ul.cat li:eq(0)").click();

					if (mode == "diet")
					{						cc_diary_diet_del_init();
						cc_diary_diet_edit_init();
					}
					else
					{
						cc_diary_activity_del_init();
						cc_diary_activity_edit_init();
					}
				}
				else
				{					oConfirmBox.init({msg:json.msg, fn:function(){
						document.location.replace(json.url);
					}, btnOkText:"Ввести вес", btnCancelText:"отменить"});
				}			}
		});	});

	$("div#get_code_to_blog").click(function(){
		if ($(this).hasClass("show"))
			return;

		$("#get_code_to_blog").addClass("show");
		$.ajax({
			type: "POST",
			url: "/calculator-calories/code2blog",
			data: arCCAddParams,
			dataType: "json",
			success: function(json){
				var status = json.status * 1;

				if (status == 1)
				{
					$("#html_code_img").attr("src", json.src);
					$("#html_code_out").html('&lt;a href="http://www.fittrends.ru/"&gt;&lt;img src="' + json.src + '" alt="FitTrends.ru - Всё об активной и здоровой жизни" title="FitTrends.ru - Всё об активной и здоровой жизни" /&gt;&lt;/a&gt;');
					$("#html_code_in").html(json.code_in_our_blog);
					$("#html_code").show();
				}
				else
				{
					oConfirmBox.init({msg:"Не заполнены данные на текущий день", fn:function(){
					}, btnOkText:"OK", btnCancelText:"закрыть"});
				}
				$("#get_code_to_blog").removeClass("show");
			}
		});
	});

	$("div.btn_add2diary_weight div.btn_blue").click(function(){		if (!($("div.btn_add2diary_weight input#weight").val() * 1))
		{			alert("Не указан вес!");			return;
		}

		arCCAddParams["weight"] = $("div.btn_add2diary_weight input#weight").val() * 1;
		arCCAddParams["comment"] = $("div.btn_add2diary_weight input#comment").val();

		$.ajax({
			type: "POST",
			url: "/calculator-calories/add-weight",
			data: arCCAddParams,
			dataType: "html",
			success: function(html){
				$("td.add2diary_weight").html(html);
				$("div.btn_add2diary_weight input#weight").val("");
				$("div.btn_add2diary_weight input#comment").val("");

				cc_diary_weight_del_init();
			}
		});	});

	function cc_diary_diet_del_init()
	{
		$("table.diary4day td.del img").click(function(){
			var id = $(this).attr("id").replace(/del_/, "") * 1;

			oConfirmBox.init({msg:"Удалить?", fn:function(){
				arCCAddParams["id"] = id;
				$.ajax({
					type: "POST",
					url: "/calculator-calories/del-diet",
					data: arCCAddParams,
					dataType: "html",
					success: function(html){
						if ($.trim(html).length)
						{
							$("div.cnt_wrap").html(html);
							if (!$("div.btn_add2diary_diet ul.tabs li.active").length)
								$("div.separator_height").height(0);
							cc_diary_diet_del_init();
							cc_diary_diet_edit_init();
						}
					}
				});
			}, btnOkText:"Да", btnCancelText:"отменить"});
		});
	}

	function cc_diary_diet_edit_init()
	{
		$("table.diary4day td.edit img").click(function(){
			var id = $(this).attr("id").replace(/edit_/, "") * 1,
				weight = $(this).parent().parent().find("td.weight").html(),
				time = $(this).parent().parent().find("td.time").html(),
				arTime = time.split(":"),
				h = arTime[0],
				m = arTime[1];

			oConfirmBox.init({msg:'<table id="diary_activity_edit' + id + '" class="diary_weight_edit"><tr><td colspan="2"></td></tr><tr><td><input type="text" name="w_' + id + '" id="w_' + id + '" value="' + weight + '" size="3" maxlength="3" /> грамм в <input type="text" name="h_' + id + '" id="h_' + id + '" value="' + h + '" size="3" maxlength="3" /> ч <input type="text" name="m_' + id + '" id="m_' + id + '" value="' + m + '" size="3" maxlength="3" /> м</td></tr></table>', fn:function(){
				var weight = $("input#w_" + id).val() * 1,
					h = $("input#h_" + id).val() * 1,
					m = $("input#m_" + id).val() * 1;

				arCCAddParams["id"] = id;
				arCCAddParams["weight"] = weight;
				arCCAddParams["h"] = h;
				arCCAddParams["m"] = m;

				$.ajax({
					type: "POST",
					url: "/calculator-calories/edit-diet",
					data: arCCAddParams,
					dataType: "html",
					success: function(html){
						if ($.trim(html).length)
						{
							$("div.cnt_wrap").html(html);
							if (!$("div.btn_add2diary_diet ul.tabs li.active").length)
								$("div.separator_height").height(0);
							cc_diary_diet_del_init();
							cc_diary_diet_edit_init();
						}
					}
				});
			}, btnOkText:"Изменить", btnCancelText:"отменить"});
		});
	}

	function cc_diary_activity_del_init()
	{
		$("table.diary4day td.del img").click(function(){
			var id = $(this).attr("id").replace(/del_/, "") * 1;

			oConfirmBox.init({msg:"Удалить?", fn:function(){				arCCAddParams["id"] = id;
				$.ajax({
					type: "POST",
					url: "/calculator-calories/del-activity",
					data: arCCAddParams,
					dataType: "html",
					success: function(html){
						if ($.trim(html).length)
						{
							$("div.cnt_wrap").html(html);
							cc_diary_activity_del_init();
							cc_diary_activity_edit_init();
						}
					}
				});
			}, btnOkText:"Да", btnCancelText:"отменить"});
		});
	}

	function cc_diary_activity_edit_init()
	{
		$("table.diary4day td.edit img").click(function(){			var id = $(this).attr("id").replace(/edit_/, "") * 1,
				duration = $(this).parent().parent().find("td.duration").html(),
				h = Math.floor(duration / 60),
				m = duration - h * 60;

			oConfirmBox.init({msg:'<table id="diary_activity_edit' + id + '" class="diary_weight_edit"><tr><td colspan="2"></td></tr><tr><td class="label">Длительность </td><td> <input type="text" name="h_' + id + '" id="h_' + id + '" value="' + h + '" size="3" maxlength="3" /> ч <input type="text" name="m_' + id + '" id="m_' + id + '" value="' + m + '" size="3" maxlength="3" /> м</td></tr></table>', fn:function(){				var h = $("input#h_" + id).val() * 1,
					m = $("input#m_" + id).val() * 1;

				arCCAddParams["id"] = id;
				arCCAddParams["duration"] = h * 60 + m;

				$.ajax({
					type: "POST",
					url: "/calculator-calories/edit-activity",
					data: arCCAddParams,
					dataType: "html",
					success: function(html){
						if ($.trim(html).length)
						{
							$("div.cnt_wrap").html(html);
							cc_diary_activity_del_init();
							cc_diary_activity_edit_init();
						}
					}
				});
			}, btnOkText:"Изменить", btnCancelText:"отменить"});
		});
	}

	function cc_diary_weight_del_init()
	{		$("table.diary_weight td.del img").click(function(){			var id = $(this).attr("id").replace(/del_/, "") * 1;
			oConfirmBox.init({msg:"Удалить?", fn:function(){
				$.ajax({
					type: "POST",
					url: "/calculator-calories/del-weight",
					data: "id=" + id,
					dataType: "html",
					success: function(html){						if ($.trim(html).length)
						{
							//$("div.contentleft table.t1 td.vtp div.cnt_wrap").html(html);
							$("td.add2diary_weight").html(html);
							cc_diary_weight_del_init();
							cc_diary_weight_edit_init();
						}
					}
				});
			}, btnOkText:"Да", btnCancelText:"отменить"});		});
	}

	function cc_diary_weight_edit_init()
	{
		$("table.diary_weight td.edit img").click(function(){
			var id = $(this).attr("id").replace(/edit_/, "") * 1,
				dat = $(this).parent().parent().find("td.date").html(),
				time = $(this).parent().parent().find("td.date").attr("class").replace(/date t/, ""),
				weight = $(this).parent().parent().find("td.weight").html() * 1,
				comment = $(this).parent().parent().find("td.comment").html();

			oConfirmBox.init({msg:'<table id="diary_weight_edit' + id + '" class="diary_weight_edit"><tr><td colspan="2">' + dat + '</td></tr><tr><td class="label">Вес</td><td><input type="text" name="w_' + id + '" id="w_' + id + '" value="' + weight + '" maxlength="3" class="weight" /> кг</td></tr><tr><td class="label">Комментарий</td><td><input type="text" name="c_' + id + '" id="c_' + id + '" value="' + comment + '" maxlength="255" class="comment" /></td></tr></table>', fn:function(){				var weight = $("table.diary_weight_edit td input.weight").val() * 1,
					comment = $("table.diary_weight_edit td input.comment").val();

				arCCAddParams["time"] = time;
				arCCAddParams["weight"] = weight;
				arCCAddParams["comment"] = comment;

				$.ajax({					type: "POST",
					url: "/calculator-calories/add-weight",
					data: arCCAddParams,
					dataType: "html",
					success: function(html){						if ($.trim(html).length)
						{
							//$("div.contentleft table.t1 td.vtp div.cnt_wrap").html(html);
							$("td.add2diary_weight").html(html);
							cc_diary_weight_del_init();
							cc_diary_weight_edit_init();
						}					}				});

			}, btnOkText:"Изменить", btnCancelText:"отменить"});
		});
	}

	if (mode == "diet")
	{
		cc_diary_diet_del_init();
		cc_diary_diet_edit_init();
	}
	else
	{
		cc_diary_activity_del_init();
		cc_diary_activity_edit_init();
	}
	cc_diary_weight_del_init();
	cc_diary_weight_edit_init();

	if ($("div.btn_add2diary_diet ul.tabs li").length)
	{		var i = $.trim(document.location.href.split("#")[1]);

		if (i.length)
			$("div.btn_add2diary_diet ul.tabs li:eq(" + (i * 1) + ")").click();
	}

	$(function() {
		$("div.diary_diet_date_wrap #diet_date").datepicker({			dateFormat: "yymmdd",			onSelect: function(dateText, inst){				window.location = document.location.href.replace(/\/\d+$/, "") + "/" + dateText;
			}		});
	});

	$("#frm_clubs_filter .metro_list").click(function(){
		$("#frm_clubs_filter .metro_list").val($(this).val());
	});

	$("div.description div.more_photo ul li img").click(function(){		var img_ = $("div.description div.photo_wrap img:eq(0)"),
			img = $(this),
			ar_src_ = img_.attr("src").split("/"),
			ar_src = img.attr("src").split("/");

		img_.attr("src", "/" + ar_src[(ar_src.length - 3)] + "/400_600_80/" + ar_src[(ar_src.length - 1)]);

		$("div.description div.more_photo ul li.active").removeClass("active");
		img.parent().addClass("active");
	});

	$("div.description div.more_photo_wrap div.arrow.left").click(function(){		if ($("div.description div.more_photo ul:animated").length) return;

		var width = ($("div.description div.more_photo ul li").length - 4) * $("div.description div.more_photo ul li:eq(0)").width(),
			pos = $("div.description div.more_photo ul").css("left").replace("px", "") * -1;

		if (pos > 0)
			$("div.description div.more_photo ul").animate({"left":"+=" + ($("div.description div.more_photo ul li:eq(0)").width() + 2)});	});

	$("div.description div.more_photo_wrap div.arrow.right").click(function(){
		if ($("div.description div.more_photo ul:animated").length) return;

		var width = 0,//($("div.description div.more_photo ul li").length - 4) * $("div.description div.more_photo ul li:eq(0)").width(),
			pos = $("div.description div.more_photo ul").css("left").replace("px", "") * -1;

		$("div.description div.more_photo ul li").each(function(){			width += $(this).width() + 2;		});

		width = width - $("div.description div.more_photo").width() * 1;
		if (pos < width)
			$("div.description div.more_photo ul").animate({"left":"-=" + ($("div.description div.more_photo ul li:eq(0)").width() + 2)});
	});

	$("span.quote_comment").click(function(){		$("#field_pole2").val('<q>' + $(this).parent().find("div.text").text() + '</q>\n\n' + $("#field_pole2").val());	});

	$("span.quote_uname").click(function(){
		$("#field_pole2").val('<q>' + $(this).parent().find("span.nick a").html() + '</q>\n\n' + $("#field_pole2").val());
	});

	$("a.photo_delete").click(function(){		var url = $(this).attr("href");
		oConfirmBox.init({msg:"Удалить картинку", fn:function(){window.location = url;}, btnOkText:"Да", btnCancelText:"отменить"});

		return false;
	});

	$("div.profile div.i.rating").hover(
		function(){			$("div.tip", $(this)).show();		},
		function(){		}
	);
	$("div.profile div.i.rating div.tip div.close").click(function(){		$(this).parent().hide();	});
});
