/**Редактирование**/

//Отобразить карту (отображается в конечном виде в thickbox-е)
function showMapToMarkPhoto(idPhoto, objLink) {
  if (($("#map_block").css("display") == "block") && !confirm("Вы действительно хотите выбрать другую фотографию, отмечаемую на карте?"))
    return false;

  $("#map_block").attr("id_photo", idPhoto);
  $("#map_block").show();
  var curLat = parseFloat($('.editPhotoBlock[@id_photo="' + idPhoto + '"]').attr("lat"));
  var curLong = parseFloat($('.editPhotoBlock[@id_photo="' + idPhoto + '"]').attr("long"));
  if (!curLat || !curLong) {
    objMaps.get(0).init(0); //инициализируем карту (без точек) - один раз.
    return 1;
  }
  var curDescr = $('.editPhotoBlock[@id_photo="' + idPhoto + '"] .photo_descr').val();
  $("#idPhotoLat").val(curLat ? curLat : '');
  $("#idPhotoLong").val(curLong ? curLong : '');
  $("#curPhotoMapInfo").html('Вы отмечаете фото с названием: "<span id="descrBody">' + curDescr + '</span>"');
  $("#approveMapChoice").attr("disabled", "disabled");
  if (!parseInt($("#map_block").attr("activated"))) { //если карта не активирована
    $("#map_block").attr("activated", 1);
  } else {
    objMaps.get(0).map.clearOverlays(); //очищаем карту от отмечания пред. фотографии
  }
  objMaps.get(0).init([curLat, curLong, curDescr]); //инициализируем карту (без точек) - один раз.
};

//Отобразить карту (отображается в конечном виде в thickbox-е)
function showMapToMarkPhotoInline(idPhoto, objLink) {
//  if (($("#map_block").css("display") == "block") && !confirm("Вы действительно хотите выбрать другую фотографию, отмечаемую на карте?"))
//    return false;
  $("#map_block").attr("id_photo", idPhoto);
  $("#map_block").show();
  var curLat = parseFloat($('.editPhotoBlock').attr("lat"));
  var curLong = parseFloat($('.editPhotoBlock').attr("long"));
  var curDescr = $('.editPhotoBlock .photo_descr').val();
  $('#edit_photo_inner').hide();
  $('#map_block').show();
  $("#idPhotoLat").val(curLat ? curLat : '');
  $("#idPhotoLong").val(curLong ? curLong : '');
  $("#curPhotoMapInfo").html('Вы отмечаете фото с названием: "<span id="descrBody">' + curDescr + '</span>"');
  $("#approveMapChoice").attr("disabled", "disabled");

  if (!parseInt($("#map_block").attr("activated"))) { //если карта не активирована
    $("#map_block").attr("activated", 1);
  } else {
    objMaps.get(0).map.clearOverlays(); //очищаем карту от отмечания пред. фотографии
  }
  if (!curLat || !curLong) {
    objMaps.get(0).init(0); //инициализируем карту (без точек) - один раз.
    return 1;
  }
  objMaps.get(0).init([curLat, curLong, curDescr]); //инициализируем карту (без точек) - один раз.
};

//Прячем окошко с карту, карту оставляем инициализированной
function hideMapToMarkPhotoInline() {
  $("#curPhotoMapInfo").html("Фотография не выбрана");
  $("#map_block").hide();
  $('#edit_photo_inner').show();
  //tb_remove();
};


//Устанавливаем широту и долготу для фотографии по AJAX
function setLatLngAjax(objBtn, isInline) {
    var objBtn = $("#approveMapChoice");
    if ($(objBtn).attr("pressed") == "pressed")
      return false;
    $(objBtn).attr("pressed", "pressed"); //Добавляем защиту от повторных нажатий
    var idPhoto = $("#map_block").attr("id_photo");
    $('.editPhotoBlock[@id_photo="' + idPhoto + '"]').attr("lat", $("#idPhotoLat").val());
    $('.editPhotoBlock[@id_photo="' + idPhoto + '"]').attr("long", $("#idPhotoLong").val());
    $.ajax({
    	type: "GET",
      url: W_AJAX + 'photo/setLatLng/' + idPhoto + '/' + $("#idPhotoLat").val() + '/' + $("#idPhotoLong").val(),
      success: function(responseText){
        if (navigator.userAgent.indexOf ("Opera") != -1) var arrInfo = eval('(' + responseText + ')');
        else var arrInfo = JSON.parse(responseText);
        if (arrInfo['result'] == 'OK') {
          if (isInline)  hideMapToMarkPhotoInline(); //прячем карту
          else hideMapToMarkPhoto(); //прячем карту
          $('.editPhotoBlock[@id_photo="' + idPhoto + '"] a.ajax').attr("class", "ajax ok");
    	    alert('Фотография успешно отмечена на карте!');
    	  }
    	  else {
          $(objBtn).attr('pressed', 'no');
          alert(arrInfo['err_text']);
        }
      }
    });
    $(objBtn).removeAttr("pressed");
};

//Прячем окошко с карту, карту оставляем инициализированной
function hideMapToMarkPhoto() {
  $("#curPhotoMapInfo").html("Фотография не выбрана");
  $("#map_block").hide();
  tb_remove();
};

/**Общее**/

function showImage(id, el, gallery) {
	var mainPhotoBlock = $('#mainPhotoBlock'+id);
	$('#ajax'+id).remove();
	if ((typeof(el) == 'object' && $('#mainPhoto'+id).attr('photoid') != $(el).attr("photoid")) || (typeof(el) != 'object')) {
		$('#album'+id).append('<img id="ajax' + id + '" src="' + W_IMAGES + 'icons/ajax.gif" style="position:absolute;z-index:250;left:-300px;top:-300px;" />');
		var width = $(mainPhotoBlock).width();
		var height = $(mainPhotoBlock).height();
		if (width>500) $('#ajax'+id).css({left:(width/2-8)+ $(mainPhotoBlock).offset().left, top:(height/2-8)+ $(mainPhotoBlock).offset().top});
	}
	if (typeof(el) == 'object') {
		var file = $(el).attr("file");
		var newFile = $(el).attr("file");
		var newPhotoId = $(el).attr("photoid");
	}
	else {
		if (typeof(el) == 'string') {
				var newFile = $('.prev[@photoid="' + el + '"]').attr('file');
				var newPhotoId = el;
		}
		else {
			var file = $('#mainPhoto'+id).attr("file");
			el = $('#mainPhoto'+id).attr("photoid");
			if ($('.prev[@file="' + file + '"]').next(':first').attr('file')) {
				var newFile = $('.prev[@file="' + file + '"]').next(':first').attr('file');
				var newPhotoId = $('.prev[@file="' + file + '"]').next(':first').attr('photoid');
			}
			else {
				var newFile = $('#preview'+id).children('.prev:first').attr('file');
				var newPhotoId = $('#preview'+id).children('.prev:first').attr('photoid');
			}
		}
	}
	setAllInfo(id, newFile, newPhotoId, gallery);
};

function showPrevImage(id, gallery) {
	var mainPhotoBlock = $('#mainPhotoBlock'+id);
	$('#ajax'+id).remove();
	$('#album'+id).append('<img id="ajax' + id + '" src="' + W_IMAGES + 'icons/ajax.gif" style="position:absolute;z-index:250;" />');
	var width = $(mainPhotoBlock).width();
	var height = $(mainPhotoBlock).height();
	$('#ajax'+id).css({left:(width/2-8)+ $(mainPhotoBlock).offset().left, top:(height/2-8)+ $(mainPhotoBlock).offset().top});
	var file = $('#mainPhoto'+id).attr("file");
	var el = $('#mainPhoto'+id).attr("photoid");
	if ($('.prev[@file="' + file + '"]').prev(':first').attr('file')) {
		var newFile = $('.prev[@file="' + file + '"]').prev(':first').attr('file');
		var newPhotoId = $('.prev[@file="' + file + '"]').prev(':first').attr('photoid');
	}
	else {
		var newFile = $('#preview'+id).children('.prev:last').attr('file');
		var newPhotoId = $('#preview'+id).children('.prev:last').attr('photoid');
	}
	setAllInfo(id, newFile, newPhotoId, gallery);
};

function changePhotoMargins(element) {
  var width = $(element).width();
	var height = $(element).height();
	if ($('.album:first').attr('gallery') == '1') var galery = 740;
	else var galery = 560;
	var marginHor = (galery-width)/2;
	var marginVer = (515-height)/2;
	var top = -(height / 2) - 11;
	$(element).css('margin-left', marginHor);
	$(element).css('padding-top', marginVer);
}

function setPhotoSrc(mainPhoto, newSrc) {
  $(mainPhoto).hide();
  $(mainPhoto).attr('src', newSrc); // Загружаем новую главную картинку
  changePhotoMargins(mainPhoto);
  $(mainPhoto).show();
  $(".preview img").each(function (i) {
    $(this).attr('src', $(this).attr('src'));
  });
}

function setAllInfo(id, newFile, newPhotoId, gallery){
	$('#mainPhotoBlockIn'+id).children('.photoSubText').text($('.prev[file="' + newFile + '"] a img').attr('title'));
	$('#hiddenPhoto').remove();
	var bigImg = $('#mainPhoto'+id);
	var bigImgId = '#mainPhoto'+id;
  //$('#mainPhoto'+id).attr('src', W_IMAGES + newFile); // Загружаем новую главную картинку
	$('#mainPhoto'+id).attr('alt', $('.prev[file="' + newFile + '"] a img').attr('title'));
	changePhotoMargins(bigImg);

	//$('#mainPhotoBlockIn'+id).css('height',$('#mainPhoto'+id).height()+20);
	$('#mainPhoto'+id).attr('file', newFile);
	$('#mainPhoto'+id).attr('photoid', newPhotoId);
	$('#preview'+id).children('.prev').children('a').children('img.prev-selected').attr('class', 'prev-nonselected').fadeTo(200, 0.6);
	var preview = $('.prev[@file="' + newFile + '"] > a > img');
	$(preview).attr('class', 'prev-selected').fadeTo(200, 1.0);
// Мотаем превьюшки
	if (gallery == 1) var width = 730;
	else var width = 560;
	if ($(preview).offset().left > $('#album'+id).offset().left + width || $(preview).offset().left < $('#album'+id).offset().left) $("#previewOut"+id)[0].scrollTo('#prev'+newPhotoId);
	if (gallery == 1) {
	  $('#photoCommentMorev').html($('.prev[file="' + newFile + '"] img').attr('alt'));
	  $('#tags4album').html(showTags($('.prev[file="' + newFile + '"]').attr('tags'), W_ABSPATH + 'gallery/search/?sort=ratingDown&keywords=&tags=', ' '));
	  $('#photoAuthor').html('<b>Автор:</b> <a href="'+W_ABSPATH+'profile/'+$('.prev[file="' + newFile + '"]').attr('authorId')+'" class="userLink" title="'+$('.prev[file="' + newFile + '"]').attr('author')+'">'+$('.prev[file="' + newFile + '"]').attr('author')+'</a>');
	  $('#mapPhotoAction').remove();
	  if ($('.prev[file="' + newFile + '"]').attr('lat') != '0') {
	  	$('#photoActions').append('<a href="'+W_ABSPATH+'gallery/map/photo/' + newPhotoId + '" style="float:right;margin-left:8px;" id="mapPhotoAction" >Фото на карте</a>');
	  };
  	$('#section').html('<b>Раздел:</b> <a href="'+W_ABSPATH+'gallery/?album='+$('.prev[file="' + newFile + '"]').attr('albumId')+'">'+$('.prev[file="' + newFile + '"]').attr('album')+'</a>');
	  if ($('.prev[file="' + newFile + '"]').attr('url') != undefined) {
	  	$('#articlePhotoAction').html('<b>Статья: </b><a href="'+W_ABSPATH+$('.prev[file="' + newFile + '"]').attr('url')+'" title="'+$('.prev[file="' + newFile + '"]').attr('article')+'" >'+$('.prev[file="' + newFile + '"]').attr('article')+'</a>');
	  }
	  else $('#articlePhotoAction').text('');

		var title = $('.prev[file="' + newFile + '"] > a > img').attr('title');
		var header = title;
		if ($('.prev[file="' + newFile + '"]').attr('edit') == '1') header += ' (<a href="#TB_inline?height=400&amp;width=670&amp;inlineId=edit_photo&amp;modal=true" onclick="loadEditPhotoInfo('+newPhotoId+');" class="thickbox">ред.</a>)';
		if (id == -2) header += '<a title="Удалить из своих" href="javascript:album.delPhotoForMe('+newPhotoId+');"><img src="' + W_IMAGES + 'icons/delete.gif" style=""/></a>';
		$('#albumHeader h1').html(header);
		if (!title) title = 'Фото без имени';
		title += '. Фотографии Санкт-Петербурга – iPetersburg.ru';
		top.document.title = title;
		thickBox_init();
		if ($('.prev[file="' + newFile + '"]').attr('my') != '1') {
			$('#addForMe').html('<a href="#" >Добавить в мой альбом</a>');
			album.getPhotoPollData(newPhotoId);
			$('#addForMe a').bind("click", function(){
			  album.addPhotoForMe(newPhotoId, this);
			  return false;
			});
		}
		else $('#addForMe').html('В моем альбоме');
	}
	//$('.tags').html(showTags($('.prev[file="' + newFile + '"]').attr('tags'), W_ABSPATH + 'gallery/?sort=ratingDown&keywords=&tags=', ' '));
	if (gallery == 1) document.location = '#'+id+'&'+newPhotoId;
	//changePhotoMargins(bigImg);
	$('body').append('<img id="hiddenPhoto" src="' + W_IMAGES + newFile + '" style="position:absolute;top:-2000px;" alt="" onload="setPhotoSrc(\'' + bigImgId + '\',\'' + W_IMAGES + newFile + '\');"/>');
};

function album(){};

album.addPhotoForMe = function(id, objLink){
  $.post(W_AJAX + 'photo/addForMe',
    {
      ID_photo: id
    },
    function(responseText) {
   	  if (navigator.userAgent.indexOf ("Opera") != -1) var arrInfo = eval('(' + responseText + ')');
    	else var arrInfo = JSON.parse(responseText);
      if(arrInfo['result'] == 'OK') {
        album.addToFavShowSuccess(objLink);
				$('.your_info > a').text(arrInfo['photos']);
				//$(objLink).after('В моем альбоме');
				$(objLink).remove();
				$('#prev'+id).attr('my', '1');
      }
      else
        alert(arrInfo['err_text']);
    });
};

album.delPhotoForMe = function(id){
  $.post(W_AJAX + 'photo/delForMe',
    {
      ID_photo: id
    },
    function(responseText) {
   	  if (navigator.userAgent.indexOf ("Opera") != -1) var arrInfo = eval('(' + responseText + ')');
    	else var arrInfo = JSON.parse(responseText);
      if(arrInfo['result'] == 'OK') {
        document.location = W_ABSPATH+'gallery/my/';
      }
      else
        alert(arrInfo['err_text']);
    });
};

album.remove = function(id){
  $.post(W_AJAX + 'remove/album/'+id,
    {},
    function(responseText) {
   	  if (navigator.userAgent.indexOf ("Opera") != -1) var arrInfo = eval('(' + responseText + ')');
    	else var arrInfo = JSON.parse(responseText);
      if(arrInfo['result'] == 'OK') {
        document.location = W_ABSPATH+'galleries/';
      }
      else
        alert(arrInfo['err_text']);
    });
};


album.getPhotoPollData = function(id){
  $.post(W_AJAX + 'photo/getPhotoPollForm',
    {
      ID_photo: id
    },
    function(responseText) {
   	  if (navigator.userAgent.indexOf ("Opera") != -1) var arrInfo = eval('(' + responseText + ')');
    	else var arrInfo = JSON.parse(responseText);
      if(arrInfo['result'] == 'OK') {
				//alert('Фотография добавлена');
				$('.poll_box').html(arrInfo['form']);
      }
      else
        alert(arrInfo['err_text']);
    });
};

album.deleteImage = function(id){
	if (confirm("Уверены, что хотите удалить эту фотографию?")){
	  $.post(W_AJAX + 'photo/delete',
	    {
	      ID_photo: id
	    },
	    function(responseText) {
	   	  if (navigator.userAgent.indexOf ("Opera") != -1) var arrInfo = eval('(' + responseText + ')');
	    	else var arrInfo = JSON.parse(responseText);
	      if(arrInfo['result'] == 'OK') {
					$('#editPhotoBlock'+id).remove();
	      }
	      else alert(arrInfo['err_text']);
			}
		);
	}
};

album.filter = function(){};

album.filter.pressDatedown = function(){
	if($("#mFilter").attr("value") == 'Поиск фотографий')
		value = $("#mFilter").attr("value", '');
	$("#dateSortHidden").attr("value", "dateUp");
	$("#sortForm").submit();
};

album.filter.pressDateup = function(){
	if($("#mFilter").attr("value") == 'Поиск фотографий')
		value = $("#mFilter").attr("value", '');
	$("#dateSortHidden").attr("value", "dateDown");
	$("#sortForm").submit();
};

album.filter.pressRatingdown = function(){
	if($("#mFilter").attr("value") == 'Поиск фотографий')
		value = $("#mFilter").attr("value", '');
	$("#dateSortHidden").attr("value", "ratingUp");
	$("#sortForm").submit();
};

album.filter.pressRatingup = function(){
	if($("#mFilter").attr("value") == 'Поиск фотографий')
		value = $("#mFilter").attr("value", '');
	$("#dateSortHidden").attr("value", "ratingDown");
	$("#sortForm").submit();
};

album.filter.pressBig = function(){
	if($("#mFilter").attr("value") == 'Поиск фотографий')
		value = $("#mFilter").attr("value", '');
	$("#sizeHidden").attr("value", "g2");
	$("#sortForm").submit();
};

album.filter.pressSmall = function(){
	if($("#mFilter").val() == 'Поиск фотографий')
		value = $("#mFilter").attr("value", '');
	$("#sizeHidden").attr("value", "g1");
	$("#sortForm").submit();
};

album.addToFavShowSuccess = function(objToPrepend) {
  if ($("#successAddPhotoToMe").length)
    $("#successAddPhotoToMe").remove();
 	var strEl = '<div class="pop-up" id="successAddPhotoToMe">' +
			        '<table class="pmain" cellspacing="0" cellpadding="0" border="0">' +
			          '<tr><td class="tl"/><td class="t"/><td class="tr"/></tr>' +
			          '<tr>' +
			            '<td class="l"/>' +
			            '<td class="body">' +
			              '<div class="content" style="display: block;">' +
			               'Фотография добавлена в Ваш альбом!</div>' +
			            '</td><td class="r"/>' +
			         '</tr>' +
			          '<tr><td class="bl"/><td class="b"/><td class="br"/></tr>' +
			        '</table>' +
			      '</div>';
  objToPrepend = $(objToPrepend).parent();
  $(objToPrepend).prepend(strEl);
  //alert($(objToPrepend).html());
  $("#successAddPhotoToMe").css("left", $(objToPrepend).offset().left+0).fadeIn(1000);
  $("#successAddPhotoToMe").fadeOut(2000);
};

function redefineAlbums(){
	var els = $('html').find('.mainPhoto').get();
	$.each(els, function() {
		var id = $(this).attr('albumId');
		var file = $(this).attr('file');
		var width = $(this).width();
		var height = $(this).height();
		if ($('.album:first').attr('gallery') == '1') var galery = 740;
		else var galery = 560;
		var marginHor = (galery-width)/2;
		var marginVer = (515-height)/2;
		var top = -(height / 2) - 11;
		$(this).css('margin-left', marginHor);
		$(this).css('padding-top', marginVer);
		var left = $('#album'+id).offset().left;
		var top2 = $('#album'+id).offset().top+$('#album'+id).children('.jScrollPaneContainer').height;
		var width2 = $('#album'+id).width();
		var height2 = $('#mainPhotoBlock'+id).height();
		var ff = 0;
		if ($.browser.mozilla) var ff = 1;
		$('#mainPhotoBlock'+id).children('.image-left').css({'left': left, 'top': top2+280});
		$('#mainPhotoBlock'+id).children('.image-right').css({'left': (left + width2-32+ff), 'top': top2+280});
		$('#mainPhotoBlock'+id).children('.image-hide').css({'left': (left + width2 - 25), 'top': top2+55});
		$('#mainPhotoBlock'+id).children('.div-left').css({'left': left, 'top': top2});
		$('#mainPhotoBlock'+id).children('.div-right').css({'left': (left + width2*0.6), 'top': top2});
	});

};


function loadEditPhotoInfo(id) {
  $.post(W_AJAX + 'photo/editInfo',
    {
      ID_photo: id
    },
    function(responseText) {
   	  if (navigator.userAgent.indexOf ("Opera") != -1) var arrInfo = eval('(' + responseText + ')');
    	else var arrInfo = JSON.parse(responseText);
      if (arrInfo['result'] == 'OK') {
      	var arrUrl = window.location.href.split('#');
      	$('.editPhotoBlock').attr('id_photo', arrInfo['id_photo']);
      	$('.editPhotoBlock a.ajax').attr('onclick', '').unbind('click').bind('click', function () {
      	  showMapToMarkPhotoInline(arrInfo['id_photo'], this);
      	  return false;
      	});
      	$('.editPhotoBlock').attr('lat', arrInfo['lat']);
      	$('.editPhotoBlock').attr('long', arrInfo['long']);
      	if (!empty(arrInfo['lat']) && !empty(arrInfo['long'])) $('.editPhotoBlock a.ajax').addClass(' ok');
      	else  $('.editPhotoBlock a.ajax').attr('class', 'ajax');
				$('#edit_image_delete').bind('click', function(){album.deleteImage(id);tb_remove();document.location=arrUrl[0]});
				$('.photo_descr').val(arrInfo['descr']);
				$('.photo_alt').text(arrInfo['alt']);
				$('.photo_tags').val(arrInfo['tags']);
				$('#edit_image_preview').attr('src', W_IMAGES + arrInfo['src']);
				$('#hidden_photo_id').val(id);
      }
      else alert(arrInfo['err_text']);
    });
};

function saveEditPhotoInfo() {
  $.post(W_AJAX + 'photo/saveInfo',
    {
      ID_photo: $('#hidden_photo_id').val(),
      descr: $('.photo_descr').val(),
			alt: $('.photo_alt').val(),
			tags: $('.photo_tags').val()
    },
    function(responseText) {
   	  if (navigator.userAgent.indexOf ("Opera") != -1) var arrInfo = eval('(' + responseText + ')');
    	else var arrInfo = JSON.parse(responseText);
      if(arrInfo['result'] == 'OK') {
				tb_remove();
				window.location.reload();
      }
      else
        alert(arrInfo['err_text']);
    });
};


function updatePreviews(count) {
	var els = $('html').find('.previewOut').get();
	$.each(els, function() {
		var id = $(this).attr('id').substr(10);
		var offset = 0-$(this).css('left').substr(0, $(this).css('left').length-2);
		var num = Math.ceil(offset/92);
		if (!num) num = 0;
		var previews = $('#preview'+id).find('img');
		var min = num-2;
		var max = num+count;
		for (var i=min; i<max; i++) {
			if (previews.eq(i).attr('src') == '' && i>=0) {
				var text = previews.eq(i).parent().parent().attr('file');
				text = text.replace('gb_', 'm_');
				previews.eq(i).attr('src', W_IMAGES + text.replace('b_', 'm_'));
			}
		}
	});
}
