var imgCrop = null, noteMark = null;
function upload4crop(form) {
	if($j('#userp').val()) {
    if(!imgCrop){
      imgCrop = new LookyImageCropper('#img4crop', { setSelect: [ 0, 0, 200, 200 ], aspectRatio: 1});
    }else{
      imgCrop.destroy();
    }

		JsHttpRequest.query('/ajax.upload4crop.php', {'userp': $j('#userp').get(0)},
			function(result, errors) {
      	if (result) {
          $j("#img4crop").attr({width: result.width, height: result.height});
          var i = $j('#img4crop').get(0);
          i.src = result.path + "?nocache=" + Math.random();
          i.onload = function() {
            imgCrop.add();
          };
					popupSwitch('avatarDialog', false);
					popupSwitch('cropDialog', true);
				} else {
					alert("При загрузке картинки произошла ошибка!");
				}
			},
		true);
	}
}

function soCropIt() {
  var cropArea = imgCrop.api.tellSelect();
  	JsHttpRequest.query(
		'/ajax.cropuploaded.php', {
			'left': cropArea.x,
			'top': cropArea.y,
			'width': cropArea.w
		},
		function(result, errors) {
			if (result) {
        popupSwitch('cropDialog', false);
        // result['big_pic'] - isn't 'src' but full html code of the img
        // <b></b> - is for rounded corners
        $j('#avatarbig a').html(result['big_pic']+"<b></b>");
        $j('#avatarbig img').attr('src', $j('#avatarbig img').attr('src') + '?nocache=' + Math.random());
			}
		},
	true);
  imgCrop.destroy();
}

function deleteCurentImg() {
	JsHttpRequest.query('/ajax.delete.avatar.php', {},
	function(result, errors) {
    if (result){
     var avatar = userpic_default_image; //"/i/usrpic/girl-230-color.png";
     //userpic_default_image - данная переменная инитится при рендеринге страницы
     $j('#avatarbig img').attr('src', avatar + '?nocache=' + Math.random());
    }
	}, true);
}

function startMark(event){
  if(!event){ return false; }
  var evt = $j.event.fix(event); evt.stopPropagation();
  if($j('#chooseFriendDialog').length == 0) return false;
  if($j('#chooseFriendDialog').css('visibility') == 'visible') {
    return false;
	} else {
		var i = $j('#currentPhoto').get(0);
    var h = $j(i).height();
    var w = $j(i).width();
    $j(i).css({height: h, width: w});
    //$j(i).closest("div").height(h);
    //$j(i).closest("div").css({height: h, width: w});
    if(!noteMark){
      noteMark = new LookyImageCropper('#currentPhoto', { setSelect: [ 50, 50, 100, 100 ], aspectRatio: 1});
    }else{
      noteMark.destroy();
    }
		noteMark.add();

    $j('#notes').css('visibility','hidden');
		popupSwitch('chooseFriendDialog', true, event);

	}
}

function markById(id, size){
  var coords = noteMark.api.tellSelect();
	JsHttpRequest.query(
	'/ajax.notes.php',
            {
                    action: 'add',
                    size: size,
                    foto_id: variable,
                    user_id: id,
                    user_name: '',
                    top: coords.y,
                    left: coords.x,
                    width: coords.w,
                    height: coords.h,
                    href: location.href
            },
            function(result, errors) {
				noteMark.destroy();
				$j('#notes').css('display','block');
				popupSwitch('chooseFriendDialog', false);
				addNote(coords,result,id);
				$j('#chooseFriendDialog input').get(0).value = '';
            },
            true
	);
}
function markByName(form, size){
	if(!$j.trim($j('#chooseFriendDialog input').val())){return;}
  var f = $j(form).get(0);
  var submitButton = $j(form).find("input[type=submit]");
  submitButton.attr('disabled', true);
  mat_check_common(f, function(matPassed){
  if(!matPassed){
	    submitButton.attr('disabled', false);
	    return false;
  }
  var coords = noteMark.api.tellSelect();
	JsHttpRequest.query(
	'/ajax.notes.php',
            {
                    action: 'add',
                    size: size,
                    foto_id: variable,
                    user_id: '',
                    user_name: $j('#chooseFriendDialog input').val(),
                    top: coords.y,
                    left: coords.x,
                    width: coords.w,
                    height: coords.h
            },
            function(result, errors) {
            	if(result['insert_id']) {
            		noteMark.destroy();
            		$j('#notes').css('display','block');
      					popupSwitch('chooseFriendDialog', false);
            		addNote(coords,result);
            	}
        			submitButton.attr('disabled', false);
            },
            true
	);
  });
}

function addNote(coords, info, id){
  var name = info['name'];
  var note = info['insert_id'];
	var li = document.createElement('li');
  var li2 = document.createElement('li');
	li.style.width = coords.w + 'px';
	li.style.height = coords.h + 'px';
	li.style.left = (coords.x+9) + 'px';
	li.style.top = (coords.y+9) + 'px';
	li.id = 'note' + note;
	li.innerHTML = '<a href="'+(id ? '/user/'+id : '#')+'" style="width: '+(coords.w-2)+'px; height: '+(coords.h-2)+'px;" title="'+name.replace(/<\/?[^>]+>/gi, ' ')+'"><span></span><b>'+name+'</b></a>';
	$j('#notes').get(0).appendChild(li);
  li2.id = 'notedUser'+note;
  var img_path = info['img_path'] ? info['img_path'] : '/i/usrpic/girl-32-color.png';
  if (id>0) {
  	li2.innerHTML = '<a onclick="removeNote('+note+'); return false" href="#" class="actions remove"><span></span></a>'+
      '<a href="/user/'+id+'" class="usrpic " title="'+name+'"><img src="'+img_path+'" alt="'+name+'" /><b></b></a>'+
      '<a href="/user/'+id+'" onmouseover="showNote('+note+')" onmouseout="hideNote('+note+')">'+name+'</a>'+
      '<br class="clear" />';
  } else {
    li2.innerHTML = '<a onclick="removeNote('+note+'); return false" href="#" class="actions remove"><span></span></a>'+
      '<span onmouseover="showNote('+note+')" onmouseout="hideNote('+note+')">'+name.replace(/<\/?[^>]+>/gi, ' ')+'</span><br class="clear" />';
  }
 	$j('#notedUsers').get(0).appendChild(li2);
 	var note_qty = parseInt($j('span#note_qty').html().replace('(', ''));
 	$j('span#note_qty').html('('+(note_qty+1)+')');
  if(note_qty == 0){$j('span#note_qty').closest("p").show();}
}

function removeNote(id){
	JsHttpRequest.query(
		'/ajax.notes.php',
		{
			action: 'remove',
			foto_id: variable,
			id: id
		},
		function(result, errors) { },
		true
	);
  $j('#note'+id+', #notedUser'+id).remove();
  var note_qty = parseInt($j('span#note_qty').html().replace('(', ''));
  $j('span#note_qty').html('('+(note_qty-1)+')');
  if(note_qty-1 == 0){$j('span#note_qty').closest("p").hide();}
}

function showNote(id){
	$j('#notes').css('visibility', 'visible');
	$j('#note'+id+' a').addClass('highlight');
}
function hideNote(id){
	$j('#notes').css('visibility', 'hidden');
  $j('#note'+id+' a').removeClass('highlight');
}

function markSort(el){
	var str = el.value.toLowerCase();
  $j('#chooseFriendDialog ul span').each(function(){
    $j(this).closest("li").css("display", $j(this).html().toLowerCase().indexOf(str) != -1 ? 'list-item' : 'none');
  });
}

$j(function(){
  if($j.browser.msie && parseFloat($j.browser.version) < 7){
    $j("div.box-photo").hover(
      function () {
        $j("div.box-photo span[class^=zoom]").show();
      },
      function () {
        $j("div.box-photo span[class^=zoom]").hide();
      }
    );
  }
});
