
$(function(){
	$('.sel_change').sSelect();
	$(".newListSelected").each(function(){
		$(this).css("z-index",100-$(".newListSelected").index($(this)));
	});
	$(".xhr-loading").ajaxSend(function(){
			$(".xhr-loading").show()
	});
	$(".xhr-loading").ajaxComplete(function(){
			$(".xhr-loading").hide()
	});
	$(".price").css("cursor", "pointer");
	$(".price.out").click(function(){
		$(this).hide();
		$(this).prev().show()
	});
	$(".price").not(".out").click(function(){
		$(this).hide();
		$(this).next().show()
	});

	$(".dialog").dialog({
		bgiframe: true,
		autoOpen: false,
		modal: true
	});

	$("body").click(function(e){
		if($(e.target).is(".ui-widget-overlay")) $(".dialog").not(".modal").dialog("close");
	});
});

function eventAlert(event){}

// example registering simple callback function for messages
php.messages.defaultCallBack = function (msg, params){
	$('.inner_page #notes').empty();
	$('.inner_page #notes').prepend(msg);
	$('.inner_page #notes').fadeIn('slow');
}

// example registering simple callback function for messages
php.errors.defaultCallBack = function (msg, params){
	$('.inner_page #errors').empty();
	$('.inner_page #errors').prepend(msg);
	$('.inner_page #errors').fadeIn('slow');
}
$lib = {};

function myinit(){
	$lib.voted = {};

	$lib.voted.send = false;
	$lib.voted.onOut = function(){};

	$lib.voted.onHover = function(){
		if($lib.voted.send) return;

		voteid = /\d{1,}/.exec($('#url').attr('href'));
		if($(".vote#profile-"+voteid).attr('voted') == 'y') return;

		hoverSrc = "/images/over.gif";
		$(this).find('img').attr('src',hoverSrc);
		$(this).removeClass('empty').addClass('hover');
		$(this).nextAll('td').removeClass('hover').addClass('empty');
		$(this).prevAll('td').removeClass('empty').addClass('hover');
	}
}

$(document).ready(function(){
	myinit();

	//$(".lightbox").lightbox();
	$(".vote").hover(function(){},function(){
		$(".vote td").removeClass('hover').addClass('empty');
	});

	$(".vote td").hover($lib.voted.onHover,$lib.voted.onOut);
	$(".vote .voteicon").click(function(){
		voteid = /\d{1,}/.exec($('#url').attr('href'));
		voteid = voteid[0];
		vote = /\d{1,}/.exec($(this).attr("id"));
		vote = vote[0];

		if($(".vote#profile-"+voteid).attr('voted') == 'y') return;

		$(this).parents(".vote").find(".hover").addClass('voted').removeClass('hover');
		$.post("/catalog/vote/"+voteid+"/"+vote);
		$lib.voted.send = true;
	});
});


$admin = {};

$admin.notifier = {};
$admin.notifier.errors = "#errors";
$admin.notifier.notes = "#notes";

$admin.notifier.errorsShow = function(callback){
    //$.scrollTo(".main","slow");
//    $admin.notifier.errors.slideDown(1500, callback);
};
$admin.notifier.errorsHide = function(callback){
    //$admin.notifier.errors.slideUp(1000, callback);
};
$admin.notifier.errorsHighlight = function(callback){
//    $admin.notifier.errors.find(".error span")
//    .animate({
//        opacity:"hide"
//    }, 500, "linear", callback)
//    .animate({
//        opacity:"show"
//    }, 500, "linear", callback);
//    setTimeout($admin.notifier.errorsHide, 5000);
};

$admin.notifier.notesShow = function(callback){
    //$.scrollTo(".main","slow");
//    $admin.notifier.notes.slideDown(1500, callback);
};
$admin.notifier.notesHide = function(callback){
    //$admin.notifier.notes.slideUp(1000, callback);
};
$admin.notifier.notesHighlight = function(callback){
//    $admin.notifier.notes.find(".note span")
//    .animate({
//        opacity:"hide"
//    }, 500, "linear", callback)
//    .animate({
//        opacity:"show"
//    }, 500, "linear", callback);
//    setTimeout($admin.notifier.notesHide, 5000);
};

$admin.notifier.setTimeOutCallback = function(){
//    if($admin.notifier.errors.find(".error").length > 0){
//        $admin.notifier.errorsShow($admin.notifier.errorsHighlight);
//    }
//    if($admin.notifier.notes.find(".note").length > 0){
//        $admin.notifier.notesShow($admin.notifier.notesHighlight);
//    }
};
$admin.notifier.setTimout = function(sec){
//    $("#errors").hide();
//    $("#notes").hide();
//    setTimeout($admin.notifier.setTimeOutCallback, sec*1000);
};
$admin.notifier.bind = function(){
//    $admin.notifier.errors = $($admin.notifier.errors);
//    $admin.notifier.notes = $($admin.notifier.notes);
//    $admin.notifier.setTimout(1);
};
$admin.notifier.unbind = function(){

};

$admin.ajaxloading = {};
$admin.ajaxloading.parser = function(data){
	if(dataType == 'json'){
		if(data["refresh"]) {window.location.href = window.location.href;return;}
		if(data["text"]) $($this).text(data["text"]);
		if(data["class"]) $($this).attr("class",data["class"]);
		if(data["title"]) $($this).attr('title',data["title"]);
		if(data["params"]) $($this).data("params",data["params"]);
		if(data["js"]) {
			$.each(data["js"], function(k,v){
				$(k).html(v);
			});
		}
	}
};
$admin.ajaxloading.click = function(){
	$this = $(this);
	url = $this.attr("href");
	dataType = $this.attr("rel");
	params = $this.data("params");
	if($this.is(".confirm")){
		if(confirm($this.attr("title"))){
			$.get(url,params,$admin.ajaxloading.parser,dataType);
			return false;
		}
		return false;
	}
	$.get(url,params,$admin.ajaxloading.parser,dataType);
	return false;
};
$admin.ajaxloading.bind = function(){
	$("a.ajax").click($admin.ajaxloading.click);
};
$admin.ajaxloading.unbind = function(){
	$("a.ajax").unbind("click",$admin.ajaxloading.click);
};
$admin.hints = {};
$admin.hints.show = function(e){
	$hint = $(e.target).find("span.hint");
	if($hint.length == 0){
		$hint = $(e.target).parent().find("span.hint");
	}
	if($hint.length == 0){
		$hint = $(e.target).parent().parent().find("span.hint");
	}
	if($hint.length == 0){
		return false;
	}
	$hint.css("display","block");
	$hint.css("left", e.clientX+15);
	$hint.css("top", parseInt(e.clientY) + 10);
}
$admin.hints.hide = function(){
	$hint = $(this).find("span.hint");
	if($hint.length == 0){
		$hint = $(this).parent().find("span.hint");
	}
	if($hint.length == 0){
		$hint = $(this).parent().parent().find("span.hint");
	}
	if($hint.length == 0){
		return false;
	}
	$hint.hide();
}
$admin.hints.unbind = function(){
	$(".registration li").unbind("mousemove",$admin.hints.show);
	$(".registration li a").unbind("mousemove",$admin.hints.show);
	$(".registration li").unbind("mouseout",$admin.hints.hide);
	$(".registration li a").unbind("mouseout",$admin.hints.hide);
//    $(".hintable").unbind("mouseout",$admin.hints.hide);
//    $(".hintable").unbind("mouseout",$admin.hints.hide);
}
$admin.hints.bind = function(){
	$admin.hints.unbind();
	$(".registration li").mousemove($admin.hints.show);
	$(".registration li a").mousemove($admin.hints.show);
	$(".registration li").mouseout($admin.hints.hide);
	$(".registration li a").mouseout($admin.hints.hide);
//    $(".hintable").mouseout($admin.hints.show);
//    $(".hintable").mouseout($admin.hints.hide);
}

$admin.events = {};
$admin.events.profile_photos = {};
$admin.events.profile_photos.apply = function(){
	data = $(this).parents(".womanforpreviewphoto").find("form").serializeArray();
	url = $(this).attr("href");
	if($(this).parents(".womanforpreviewphoto").find("input[name*=remove]:checked").length > 0){
		if(!confirm("Удалить выбранные фотографии?")) return;
	}
	$.getJSON(url, data, $admin.events.profile_photos.apply_callback);
	return false;
};
$admin.events.profile_photos.apply_callback = function(data){
	$("#photo-"+data.main+".smallphoto").fadeOut("fast", function(){
		$(this).fadeIn("fast")
	});
	$.each(data.deleted, function(i,id){
		$photo = $("#photo-"+id+".smallphoto");
		$photo.fadeOut(1000, function(){
			$(this).remove()
		});
	});
	$('.content #notes').empty();
	$('.content #notes').prepend(data.notes);
	$('.content #errors').empty();
	$('.content #errors').prepend(data.errors);
	if((data.has_photos != undefined) && !data.has_photos){
		if($('#rec')){
			$('#rec').show();
		}
		$('#button').hide();
	}
	$admin.notifier.setTimout(1);
};
$admin.events.townclick_click = function(){
	$("div.townclick ul").toggle();
}
$admin.events.townclick_ul_click = function(){
	$("div.townclick ul").hide();
}
$admin.events.townclick_mouseleave = function(){
	$("div.townclick ul").hide();
}
$admin.events.update_metro = function(){
	$select = $(this);
	id = $select.val();
	$select_metro = $select.parents("form").find("select[name*='metro_id']");
	$select_metro.html("<option value=''>загрузка...</option>");
	$select_metro.attr("disabled", "disabled");
	$select_metro.parents("tr").show();
	$.getJSON("/catalog/metro/", {
		"cid":id
	},function(data){
		if(data.length > 0){
			$.each(data,function(i,o){
				option = "<option value='"+o.value+"'>"+o.text+"</option>";
				$select_metro.append(option);
			});
			$select_metro.find("option:first").remove();
			$select_metro.removeAttr("disabled");
		}else{
			$select_metro.parents("tr").hide();
		}
	});
}
$admin.events.fixLeftColumn = function(){
	$("div.leftmenu").each(function(i,o){
		height = 0;
		if($(o).find("ul").length){
			height = $(o).find("ul").height();
		}
		height = parseInt(height) + 20;
		$(o).height(height);
		if($(o).find("div.leftmenugreen").length){
			$(o).find("div.leftmenugreen").height(height);
		}
		if($(o).find("div.leftmenugreenlight").length){
			$(o).find("div.leftmenugreenlight").height(height);
		}
	});
};
$admin.events.unbind = function(){
	$("select[name*='city_id']").unbind("change",$admin.events.update_metro);
	$("div.townclick").unbind("click",$admin.events.townclick_click);
	$("div.townclick ul").unbind("click",$admin.events.townclick_ul_click);
	$("div.townclick ul").unbind("mouseleave",$admin.events.townclick_mouseleave);
};
$admin.events.bind = function(){
	$admin.events.unbind();
	$("select[name*='city_id']").change($admin.events.update_metro);
	$("div.townclick").click($admin.events.townclick_click);
	$("div.townname").click($admin.events.townclick_click);
	$("div.townclick ul").click($admin.events.townclick_ul_click);
	$("div.townclick ul").mouseleave($admin.events.townclick_mouseleave);
	$admin.events.fixLeftColumn();
	$("table.myblanks").not(".nojs").after('<div class="pager" id="pager"><select class="pagesize"></select></div>');
	$(".pager").attr("style","float: left; margin-top: 10px; margin-right: 10px;");
	var s = window.location.search.toString();
	if(s.length == 0) {
		s = "?";
	}
	var size = s.match(/pagesize=(\d+)/i);
	size = size?size[1]:25;

	$.each({"25":25,"50":50,"100":100,"500":500}, function(k,v){
		$(".pager select.pagesize").append('<option value="'+k+'"'+(size == k?' selected ':'')+'>'+v+'</option>');
	});
	$(".pager select.pagesize").change(function(){
		var size = $(this).val();

		if(s.match(/pagesize=(\d+)/i)){
			window.location.search = s.replace(/pagesize=(\d+)/i,"pagesize="+size);
		}else{
			if(s.match(/\?/i)) window.location.search = s + "&pagesize="+size;
		}
	});
	$(".pager select.pagesize option").click(function(){
		var size = $(this).val();

		if(s.match(/pagesize=(\d+)/i)){
			window.location.search = s.replace(/pagesize=(\d+)/i,"pagesize="+size);
		}else{
			if(s.match(/\?/i)) window.location.search = s + "&pagesize="+size;
		}
	});
	$("table.myblanks").not(".nojs").each(function(i,o){
		last = $(o).find("th").length - 1;
		if($(o).find("tbody tr").length == 0) return;
		headers = new Array;
		headers[last] = {};
		headers[last]['sorter'] = false;
		$(o).tablesorter({
			widgets: ['zebra'],
			headers: headers,
			dateFormat: "us"
		});
//        .tablesorterPager({
//            container: $("#pager"),
//            size: 500
//        });
	});
	$('.womanforpreviewphoto .apply').click($admin.events.profile_photos.apply);
	//    $("a.remove").click(function(){
	//        return confirm("Вы действительно хотите удалить?");
	//    });
	$("h4").show();
};

$admin.status = {};
$admin.status.set = function(){
	status = $(this).attr("href").toString().replace("#", "");
	value = $(this).attr("rel");
	id = $(this).attr("id");
	a = $(this);
	$.get("/admin/set_status", {
		"id":id,
		"status":status,
		"value":value
	},function(){
		if(value == "true"){
			a.text("Да");
			a.attr("rel",false);
		}else{
			a.text("Нет");
			a.attr("rel",true);
		}
	});
}
$admin.status.unbind = function(){
	$(".set_status").unbind('click',$admin.status.set);
}
$admin.status.bind = function(){
	$admin.status.unbind();
	$(".set_status").click($admin.status.set);
}

$admin.breadcrumbs = {};
$admin.breadcrumbs.showSubMenu = function(){
	$(this).parents("li").find("ul.sub").show();
	return false;
}
$admin.breadcrumbs.selectItem = function(){
	$("ul.sub a:first").parents("ul.headermenu > li").find("> a").text($(this).text());
	$(this).parents("ul.sub").hide();
}
$admin.breadcrumbs.unbind = function(){
	$("ul.headermenu li a").unbind("click",$admin.breadcrumbs.showSubMenu);
}
$admin.breadcrumbs.bind = function(){
	//$admin.breadcrumbs.unbind();
	//$("ul.headermenu > li").not(".active").find("> a").click($admin.breadcrumbs.showSubMenu);
	//$("ul.headermenu li ul li a").click($admin.breadcrumbs.selectItem);
	$("ul.headermenu > li").not(".active").hover(function(){
		$(this).addClass("hover");
	}, function(){
		$(this).removeClass("hover");
	});
}

$admin.inputHint = {};
$admin.inputHint.focus = function(){
	$(this).parents(".b-input-hint").not(".nojs").find("label").hide()
};

$admin.inputHint.blur = function(){
	if($(this).val()=='') $(this).parents(".b-input-hint").not(".nojs").find("label").show()
};

$admin.inputHint.change = function(){
	if($(this).val()!='') $(this).parents(".b-input-hint").not(".nojs").find("label").hide()
};
$admin.inputHint.mouseover = function(){
	if($(this).val()!='') $(this).parents(".b-input-hint").not(".nojs").find("label").hide()
};
$admin.inputHint.unbind = function(){
	$(".b-input-hint input").unbind("focus",$admin.inputHint.focus);
	$(".b-input-hint input").unbind("blur",$admin.inputHint.blur);
	$(".b-input-hint input").unbind("change",$admin.inputHint.change);
	$(".b-input-hint input").unbind("mouseover",$admin.inputHint.mouseover);
	$(".b-input-hint input").change();
}
$admin.inputHint.bind = function(){
	$admin.inputHint.unbind();
	$(".b-input-hint input").focus($admin.inputHint.focus);
	$(".b-input-hint input").blur($admin.inputHint.blur);
	$(".b-input-hint input").change($admin.inputHint.change);
	$(".b-input-hint input").mouseover($admin.inputHint.mouseover);
	$(".b-input-hint input").change();
}

$admin.edit = {};

$admin.edit.save = function(){
	tr = $(this).parents("tr");
	tds = tr.find("td.field");
	params = {};
	tds.each(function(n,o){
		value = $(o).find("input").val();
		if($(o).find(".hidden:first").find(":first").length > 0){
			$(o).find(".hidden:first").find(":first").text(value);
			$(o).html($(o).find(".hidden:first").html());
		}else{
			$(o).html(value);
		}
		params[$(o).attr('name')] = value;
	});
	$(this).html("Редактировать");
	$(this).click($admin.edit.edit);
	$(this).unbind("click",$admin.edit.save);

	$.post($(this).attr('href'), params);
	return false;
}

$admin.edit.edit = function(){
	tr = $(this).parents("tr");
	tds = tr.find("td.field");
	tds.each(function(n,o){
		html = $(o).html();
		$(o).html($("<span class='hidden'>"+html+"</span>"));
		if($(o).find(":first").find(":first").length > 0){
			value = $(o).find(":first").find(":first").text();
		}else{
			value = $(o).find(":first").text();
		}
		$(o).prepend($("<input type='text'/>").val(value));
	});
	$(this).html("Сохранить");
	$(this).unbind("click",$admin.edit.edit);
	$(this).click($admin.edit.save);

	return false;
}

$admin.edit.remove = function(){
	res = confirm("Вы действительно хотите удалить эту запись?");
	if(!res) return false;
	tr = $(this).parents("tr");
	$table = $(tr.parents("table").get(0));
	tr.remove();
	$.get($(this).attr("href"));
	return false;
}
$admin.edit.unbind = function(){
	//Editing
	$("table tr .item-edit").click($admin.edit.edit);
	$("table tr .item-delete").click($admin.edit.remove);
}
$admin.edit.bind = function(){
	$admin.edit.unbind();
	//Editing
	$("table tr .item-edit").click($admin.edit.edit);
	$("table tr .item-delete").click($admin.edit.remove);
}

$admin.find = {};
$admin.find.addField = function(){
	$model = $(this).parents(".model");
	model = $model.attr('id');
	field = $("select[name='fileds']").val();
	if($("#"+field).length) return false;

	select_name = model+"[operations][]";
	$select = $(" <select class='operations' name='"+select_name+"'></select> ");
	$select.html($select.html()+"<option value='='>=</option>");
	$select.html($select.html()+"<option value='<'><</option>");
	$select.html($select.html()+"<option value='>'>></option>");
	$select.html($select.html()+"<option value='!='>!=</option>");

	field_name = model+"[values][]";
	field_name_hidden = model+"[fields][]";
	$field = $("<div></div>").addClass("field").attr("id", field).html("<label for='"+field+"'>"+field+"</label>");
	$field.append($select);
	$field.append("<input type='hidden' value='"+field+"' id='"+field+"_name' name='"+field_name_hidden+"'>");
	$field.append("<input type='text' id='"+field+"' name='"+field_name+"'>");


	$model.append($field);
	$admin.inputHint.bind();
}
$admin.find.addModel = function(){
	model = $("select[name='model']").val();
	$model = $("<div></div>").addClass("model").attr("id", model).html(model+"<br><br>");
	$select = $("<select name='fileds'></select>");
	for(idx in eval("models."+model).fileds){
		filed = eval("models."+model).fileds[idx];
		$select.append("<option value='"+filed+"'>"+filed+"</option>");
	}
	$model.append($select);
	$model.append(" <input id='addField' type='button' value='Добавить поле'><br><br> ");
	$("#conditions").append($model);

	$("#addField").click($admin.find.addField);
	$admin.inputHint.bind();
}
$admin.find.unbind = function(){
	$("#addModel").unbind("click",$admin.find.addModel);
}
$admin.find.bind = function(){
	$admin.find.unbind();
	$("#addModel").click($admin.find.addModel);
	$admin.inputHint.bind();
}

// Admin tables
$(document).ready(function(){
	$.each($admin, function(i,o){
		if(o.bind) o.bind();
	});
});


//
$(document).ready(function(){
	$("#reg-girl").click(function(){
		$("#form-girl").toggle();
		$("#form-user").toggle();
		$("#reg-user").show();
		$("#reg-girl").hide();
	});

	$("#reg-user").click(function(){
		$("#form-girl").toggle();
		$("#form-user").toggle();
		$("#reg-user").hide();
		$("#reg-girl").show();
	});

	$("#fav img").hover(function(){
		$(this).attr('src',"/images/star_over.png");
	},function(){
		$(this).attr('src',"/images/star.png");
	});

	$("#fav").click(function(){
		caption = "Отметить анкету";
		url = $(this).find('a').attr('href')+"?KeepThis=true&TB_iframe=true&height=260&width=380";
		tb_show(caption, url, null, null);
		return false;
	});

	$("#tabs").tabs({
		selected: 0,
		fx: {
			opacity: 'toggle'
		}
	});

	$("ul.registration a").click(function(){
		contentId = $(this).attr("href");
		$(".contentpage form").attr("action", "/signup"+contentId);
	});

	if((ar = location.hash.match(/\#manager/)) && ar.length > 0){
		$("a[href*='#manager']").click();
		$.scrollTo(".main","slow");
	}
	if((ar = location.hash.match(/\#user/)) && ar.length > 0){
		$("a[href*='#user']").click();
		$.scrollTo(".main","slow");
	}

	$(".checkall").click(function(){
		var val = $(this).attr('checked');
		classes = $(this).attr("class").replace("checkall", "").split(" ");
		$.each(classes, function(i,o){
			if(o !== ''){
				var cl = o.split("_");
				if(cl[0] == 'check'){
					$("."+cl[1]).attr("checked",val);
				}
			}
		});
	});

	$("#add-favorite").click(function(){
		$.php($(this).attr('href'));
		return false;
	});

	$(".smallphoto a[href='#remove']").click(function(){
		var id = $(this).parents(".smallphoto").attr("id").match(/photo-(\d+)/i).pop();
		$.get("/photos/remove/"+id,function(data){
			if(data == 'success'){
				$("#photo-"+id).hide("slow", function(){
					$(this).remove()
				});
			}
		});
		return false;
	});

	$(".smallphoto a[href='#main']").click(function(){
		var id = $(this).parents(".smallphoto").attr("id").match(/photo-(\d+)/i).pop();
		ico = $(this);
		$.get("/photos/main/"+id,function(data){
			if(data == 'success'){
				ico.hide("slow");
			}
		});
		return false;
	});

	$(".delete").click(function(){
		if(!confirm("Вы точно хотите удалить эту анкету из Избранного?")) return false;
		url = $(this).attr("href");
		var id = $(this).attr("id").replace('-delete', '');
		$.get(url,function(data){
			if(data == 'success'){
				$("#"+id).hide("slow", function(){
					$(this).remove()
				});
			}
		});
		return false;
	});

	$(".photo img").css("cursor","pointer");
	//    $(".photo img").click(function(){
	//        src = $(this).attr("src").replace("preview", "big");
	//        big_src = $(".womanbigphoto img").attr("src");
	//        if(big_src){
	//            $(".womanbigphoto img").attr("src",src);
	//            $(this).attr("src",big_src.replace("big", "preview"));
	//            return false;
	//        }
	//        return true;
	//    });

	//    $("#notes").hide();
	//    if($("#notes").children().length > 0){
	//        $("#notes").show();
	//        $("#notes").animate({
	//            opacity:"hide"
	//        }, 'slow')
	//        .animate({
	//            opacity:"show"
	//        }, 'slow');
	//        window.setTimeout(function(){
	//            $("#notes").fadeOut('slow');
	//        }, 5000);
	//    }

	//    $("#errors").hide();
	//    if($("#errors .error").length > 0){
	//        $("#errors").slideDown("slow");
	//        //$.scrollTo("#errors");
	//        $("#errors").animate({
	//            opacity:"hide"
	//        }, 'slow')
	//        .animate({
	//            opacity:"show"
	//        }, 'slow');
	//        window.setTimeout(function(){
	//            $("#errors").fadeOut('slow');
	//        }, 5000);
	//    }

	$(".overshow-rel").css("cursor","pointer");
	$(".overshow-rel").hover(function(){
		id = "#"+$(this).attr('rel');
		if($(this).parents("table.tablesorter").length < 1){
			offsetLeft = $(this).get(0).offsetLeft - 126;
			offsetTop = $(this).get(0).offsetTop - 20 + 14;
			$(id+".overshow-div").css("left",offsetLeft).css("top",offsetTop);
		}
		$(id+".overshow-div").addClass("show");
	}, function(){
		$(id+".overshow-div").removeClass("show");
	});

	$(".overshow-div").hover(function(){
		$(this).addClass("show");
	}, function(){
		$(this).removeClass("show");
	});
});

$lib.ajax = {};
$lib.ajax.render = {};

$lib.ajax.render.errors = function(data){
	if(data.errors){
		$("#errors.ui-state-error").html(data.errors).fadeIn('slow');
	}else{
		$("#errors.ui-state-error").html('').fadeOut('slow');
	}
}

$lib.ajax.render.notes = function(data){
	if(data.notes){
		$("#notes.ui-state-highlight").html(data.notes).fadeIn('slow');
	}else{
		$("#errors.ui-state-highlight").html('').fadeOut('slow');
	}
}

$lib.ajax.render.data = function(data){
	$lib.ajax.render.errors(data);
	$lib.ajax.render.notes(data);
	$(".content div#data").hide().html(data.data).fadeIn('slow');
	$(".lightbox").lightbox();
	window.setTimeout("$.scrollTo('div#data',800);",1000);
};


$lib.forms = {};
$lib.forms.registration_user = function(data){
	$lib.ajax.render.errors(data);
	$lib.ajax.render.notes(data);
}
$lib.forms.registration_girl = function(data){
	$lib.ajax.render.errors(data);
	$lib.ajax.render.notes(data);
}

$lib.forms.login_user = function(data){
	$lib.ajax.render.errors(data);
	$lib.ajax.render.notes(data);
	uri = "'"+location.protocol+'//'+location.host+'/catalog'+"'";
	if(data.errors == ''){
		window.setTimeout("location="+uri,3000);
	}
}

$(function(){
	//    $("#form-user form").submit(function(){
	//        post = $(this).serializeArray();
	//        action = $(this).attr('action');
	//        $.post(action,post,$lib.forms.registration_user,'json');
	//        return false;
	//    });
	//
	//    $("#form-girl form").submit(function(){
	//        post = $(this).serializeArray();
	//        action = $(this).attr('action');
	//        $.post(action,post,$lib.forms.registration_girl,'json');
	//        return false;
	//    });
	//
	//    $("#login-form form").submit(function(){
	//        post = $(this).serializeArray();
	//        action = $(this).attr('action');
	//        $.post(action,post,$lib.forms.login_user,'json');
	//        return false;
	//    });
	//
	//    $(".ajax-form form").submit(function(){
	//        post = $(this).serializeArray();
	//        action = $(this).attr('action');
	//        $.php(action,post);
	//        //$.post(action,post,$lib.ajax.render.data,'json');
	//        return false;
	//    });

	$("#ajaxloading").bind("ajaxSend", function(){
		$(this).show();
	}).bind("ajaxComplete", function(){
		$(this).hide();
	});

	$("input.autocomplete").autocomplete({
		serviceUrl:'/catalog/city',
		minChars:2,
		delimiter: /(,|;)\s*/, // regex or character
		maxHeight:400,
		width:300,
		deferRequestBy: 0, //miliseconds
		params: {
		//country:'Yes'
		}, //aditional parameters
		// callback function:
		onSelect: function(value, data){
			$("input.autocomplete").parents('form').find("input.autocomplete_id").val(data);
		}
	// local autosugest options:
	//lookup: ['Москва', 'Киев'] //local lookup values
	});
});

$(function() {
	$.datepicker.setDefaults($.extend({
		showMonthAfterYear: false
	}, $.datepicker.regional['ru']));
	$(".datepicker").datepicker($.datepicker.regional['ru']);
});

jQuery(function($){
	$.datepicker.regional['ru'] = {
		closeText: 'Закрыть',
		prevText: '&#x3c;Пред',
		nextText: 'След&#x3e;',
		currentText: 'Сегодня',
		monthNames: ['Январь','Февраль','Март','Апрель','Май','Июнь',
		'Июль','Август','Сентябрь','Октябрь','Ноябрь','Декабрь'],
		monthNamesShort: ['Янв','Фев','Мар','Апр','Май','Июн',
		'Июл','Авг','Сен','Окт','Ноя','Дек'],
		dayNames: ['воскресенье','понедельник','вторник','среда','четверг','пятница','суббота'],
		dayNamesShort: ['вск','пнд','втр','срд','чтв','птн','сбт'],
		dayNamesMin: ['Вс','Пн','Вт','Ср','Чт','Пт','Сб'],
		dateFormat: 'dd.mm.yy',
		firstDay: 1,
		isRTL: false
	};
	$.datepicker.setDefaults($.datepicker.regional['ru']);
});

$(function(){
	if($(".lightbox").lightbox)$(".lightbox").lightbox();
	$(".checklength").keypress(function (e) {
		if(e.charCode < 1 || e.ctrlKey || e.altKey) return true;
		len = 255;
		try {
			len = parseInt(/\d+/.exec($(e.target).attr("class"))[0]);
		} catch (s) {
		}

		return ($(e.target).val().length < len)
	 });
});

function showSubMenu(elt){
	$(".submenu").hide();
	$("#"+elt).show();
}