var helper = [0,0,0,0,0];
function onload_photo_fn() {
	$("#photo_holder .markwrap_div, #photo_holder .lreact, #photo_holder .rreact").mouseout(function(e){
		$(this).children().css("display","none");
	});
	$("#photo_holder").mousemove(function(e){
		e.stopPropagation();
		divs = $("#photo_holder .markwrap_div, #photo_holder .lreact, #photo_holder .rreact");
		divs.each(function(){
			var off = this.getBoundingClientRect();
			div = $(this);
			if((off.left <= e.clientX)&&(off.top<= e.clientY)&&((off.right)>=e.clientX)&&((off.bottom)>=e.clientY)) {
				div.children().css("display","block");
			}
		});
	});
	$("#photo_holder").click(function(e){
		$("#dialog").dialog("close");
	});
	$("#a_init_mark").click(function(e){
		e.preventDefault();
		$("#photo_holder .rreact, #photo_holder .lreact, #photo_holder .markwrap_div").css('display','none');
		$("#helpdiv").show();
		$("#markdiv").show("slow");
		$('#photo_holder').unbind('click');
		$("#photo").marque();
	});
	$("#a_cmark").click(function(e){
		e.preventDefault();
		$("#helpdiv").hide();
		$("#markdiv").hide("slow");
		cancel_selection("#photo");
	});
	$("#a_mark").click(function(e){
		e.preventDefault();
		prom = $("#photo").getRect();
		if( (!document.getElementById('chk_me').checked && $("[name=sl_friend]").val()==0) ){
			alert('Вы не указали человека');
			return false;
		}
		if( prom===false || prom.width==0 || prom.height==0 )
		{
			alert('Вы никого не выделили');
			return false;
		}
		$("#helpdiv").hide();
		$("#markdiv").hide("slow");
		jQuery.ajax({
			url: this.href,
			type: 'post',
			data:{
				x:prom.left,
				y:prom.top,
				w:prom.width,
				h:prom.height,
				self: ($("#chk_me").attr("checked")? $("#chk_me").val():0),
				user: $("[name=sl_friend]").val()
				},
			dataType: 'json',
			success: update_marks,
			error: a_error
		});
	});
	$(".lreact, #larrow_sm").click(previous);
	$(".rreact, #rarrow_sm").click(next);
	$("#markview .mark_a").mouseover(show_marked);
	$("#markview .mark_a").mouseout(hide_marked);
	$("#markview .markdel_a").click(click_marked);
	$("#ph_num").change(function(e){
		var chpos = this.form.action.indexOf('?gid=');
		var gid = this.form.action.substring(chpos+5);
		var user_id = $(this.form).attr("user_id");
		get_ph($(this).val(),gid, user_id);
	});
	$("#chk_me").change(function(e){
		if($("#chk_me").attr("checked")) {
			$("#sl_friend, [name=sl_friend]").attr("disabled",true);
		}
		else {
			$("#sl_friend, [name=sl_friend]").attr("disabled",false);
		}
	});
	$('#sl_friend').keyup(function(){ $('[name=sl_friend]').val('0'); });
	$('#sl_friend').change(checkLogin);
	$('#sl_friend').autocomplete('/service/ajax/ac_friends.php',{cacheLength:1, matchSubset:false, delay:400, autoFill:false, maxItemsToShow:15, selectFirst:true, formatItem:formatPersons, scrollHeight:320, width:300, extraParams:{uid:user_id} });
	$('#sl_friend').result(function(event, data, formatted){ $('[name=sl_friend]').val(data[4]); });
}

function formatPersons(row, i, num)
{
	var result = "<a href='#' onclick='return false;'>";
	result+='<img src="/user/avatar.php?id='+row[4]+'&type=6"/>';
	result+='<span class="bold">'+row[0]+'</span><br/>'+row[1]+' '+row[2]+"</a>";
	return result;
}
function checkLogin()
{
	setTimeout("setLogin();", 500);
	return false;
}
function setLogin()
{
	login = document.getElementById('sl_friend').value;
	$.post( '/service/ajax/find_user_id.php','login='+login, function(data)
	{
		$('[name=sl_friend]').val(data);
	});
}

function a_error(req, tst, er) {
	alert(tst+" "+er);
}
function click_marked(e) {
	var src = this.href;
	if(src.indexOf('ajax_mark.php?')>0){
		e.preventDefault();
		jQuery.ajax({
			url: src,
			type: 'post',
			data:{pst:'1'},
			dataType: 'json',
			success: update_marks
		});
	}
}
function fill_content(data){
	$("#dialog_content").html(data);
	$(document).ready(onload_photo_fn);
}
function get_ph(pnum,gid,user_id) {
	$("#dialog_content").html("");
	if(user_id) { 
		gid = 'mr';
		$.ajax({
			url: 'foto.php',
			type: 'get',
			data:{id:pnum, gid:gid, user_id: user_id},
			dataType: 'html',
			success: fill_content
		});
	}
	else {
		$.ajax({
			url: 'foto.php',
			type: 'get',
			data:{id:pnum, gid:gid},
			dataType: 'html',
			success: fill_content
		});
	}
}
function previous(e) {
	$("#ph_num").val(parseInt($("#ph_num").val())-1);
	$("#ph_num").change();
}
function next(e) {
	$("#ph_num").val(parseInt($("#ph_num").val())+1);
	$("#ph_num").change();
}
function rnd_color() {
	return 'rgb('+Math.ceil(Math.random()*255).toString()+','+
					Math.ceil(Math.random()*255).toString()+','+
					Math.ceil(Math.random()*255).toString()+')';
}
function show_marked(e) {
	var chpos = this.href.indexOf('?id=');
	var id = this.href.substring(chpos+4);
	var color = rnd_color();
	helper[0] = $("#mark"+id).parent();
	helper[0].children().css("display","block");
	for(var i=1; i < 5; i++) {
		helper[i] = $(document.createElement('div'));
		$("#photo_holder").append(helper[i]);
		helper[i].css({
			'opacity':'0.5',
			'background': color,
			'position':'absolute'});
	}
	ph= $("#photo_holder");
	w = ph.width(); h=ph.height(); 
	var pos = helper[0].position(); hw = helper[0].width(); hh = helper[0].height();
	helper[1].css({
		top: 0,
		left: 0,
		width: w+'px',
		height: pos.top+'px'});
	helper[2].css({
		top: pos.top+'px',
		left: hw+pos.left+'px',
		width: w-hw-pos.left+'px',
		height: hh+'px'});
	helper[3].css({
		top: pos.top+hh+'px',
		left: 0,
		width: w,
		height: h - pos.top - hh + 'px'});
	helper[4].css({
		top: pos.top+'px',
		left: 0,
		width: pos.left+'px',
		height: hh+'px'});
}
function hide_marked(e) {
	for(var i = 1; i < 5; i ++) {
		helper[i].remove();
	}
	helper[0].children().css("display","");
}
function update_marks(data,txtStatus) {
	var tmp = eval(data);
	if(tmp.length==0) {return 0;};
	$("#photo_holder .markwrap_div").remove();
	$("#markview").html("На этом фото: "+tmp[0]);
	for(var i = 1; i < tmp.length; i++) {
		mrwrap = $(document.createElement("div"));
		mr = $(document.createElement("div"));
		mrwrap.append(mr);
		mrtitle = $(document.createElement("div"));
		mr.append(mrtitle);
		mrwrap.addClass("markwrap_div");
		mr.addClass("mark_div");
		mrtitle.addClass("mark_title_div");
		mrwrap.css({'left':tmp[i][2]+'px','top':tmp[i][3]+'px','width':tmp[i][4]+'px','height':tmp[i][5]+'px'});
		mr.css({'left':'0','top':'0','width':tmp[i][4]+'px','height':tmp[i][5]+'px'});
		mrtitle.text(tmp[i][1]);
		mr.attr('id',"mark"+tmp[i][0].toString());
		$("#photo_holder").append(mrwrap);
	}
	cancel_selection("#photo");
	$("#markview .mark_a").mouseover(show_marked);
	$("#markview .mark_a").mouseout(hide_marked);
	$("#markview .markdel_a").click(click_marked);
}
function cancel_selection(el) { 
	$("#photo").marqueDestroy();
	$("#photo_holder").click(function(e){ $("#dialog").dialog("close");	});
	$("#photo_holder .rreact, #photo_holder .lreact, #photo_holder .markwrap_div").css('display','block');
}
