/****
* Обрабатыващий модуль для "Избранные"
***/

jQuery(function() {
	/************************ user/my-favorite/ items sortable ************************/
	var sortable_group = jQuery("ul[id^='sortable-group-']");
	var sortable_group_name = sortable_group.attr('name');
	var placeholder					= 'object-sortable-holder';

	if (sortable_group_name == 'person') {
		placeholder					= 'object-sortable-holder-person';
	}

	sortable_group.sortable({
		opacity			: 0.7,
		revert			: true,
		delay				: 100,
		tolerance		: 'pointer',
		cursor			: 'move',
		placeholder	: placeholder,
		update			: function(event, ui) {
			var sortable_element = jQuery(this);
			var post_params	= sortable_element.sortable('serialize');
			post_params = post_params + '&object-type=' + sortable_group_name;

			sortable_element.sortable('disable');

			jQuery.post(
				'/favorits/my-favorite-sortable',
				post_params,
				function(data) {
					sortable_element.sortable('enable');
				}, 'json'
			);
		}
	});
});

/*
* Добавление в избранное "Раздела"
*
* uid       - идентификатор пользователя
* chapterid - идентификатор раздела
* objectid  - идентификатор объекта
*/
function addFavoritObject(uid,chapterid,objectid,fstatus){
 if (!parseInt(chapterid) || !parseInt(objectid) || !parseInt(uid)) {
  alert('Ошибка добавления в "Избранное"!');
  return false;
 }

 var fillStatus = fstatus;

 if (jQuery('#guiHdnFillStatus').attr('id') == 'guiHdnFillStatus') {fillStatus   = jQuery('#guiHdnFillStatus').val();}
 if (!(fillStatus > 0)) {
  showPopUpWindow('guiAlertWindow');
  jQuery('#guiDivMessage').html('<p>Для добавления в Избранное Вам необходимо заполнить все обязательные поля в <a href="/user/profile-edit/'+uid+'" title="Личный профиль">вашем&nbsp;личном&nbsp;профиле</a></p>');
  return false;
 }


 var option = {};

 option['userId']    = uid;
 option['objectId']  = objectid;
 option['chapterId'] = chapterid;

 switch(parseInt(chapterid)){
   case 2: // статьи
   case 3: // каталог
   case 4: // фото
   case 1: // форум
   case 5: // видео
      jQuery('#guiPInterestStruct').html('<span class="articleNavi"><a href="">загрузка ...</a></span>');
      break;
 }

 jQuery.ajax({
    	 type     : "POST",
    	 url      :  "/favorits/add-intersting",
    	 async    : false,
    	 data     : option,
    	 dataType : "json",
    	 success  : function(data){

                     if (!(data.code > 0)) {



                      switch(parseInt(chapterid)){
                      	case 1: // форум
                      	case 2: // статьи
                            jQuery('#guiPInterestStruct').hide();
							jQuery('#guiPInterestStruct').html('<a href="javascript:void(0)" onclick="removeFavorits('+uid+','+chapterid+','+objectid+');" class="simpe-link" id="guiRemoveFromInterestingPhoto">В избранном&nbsp;<img src="/public/img/red-heart-comment.gif" border="0" class="actionImg" /></a>');
                      	    jQuery('#guiPInterestStruct').animate({ opacity: "show" }, 'slow');

                      	    jQuery('#guiTdInInterest').hide();
							jQuery('#guiTdInInterest').html(data.html);
							jQuery('#guiTdInInterest').animate({ opacity: "show" }, 'slow');
                      		break;
						case 3: // каталог
						    jQuery('#guiTdInInterest').html(data.html);
						    jQuery('#guiPInterestStruct').html('<img src="/public/img/red-heart-comment.gif" border="0" class="statusImg" />&nbsp;<a href="javascript:void(0)" title="Удалить фирму из избранных" id="del-favorite-link" class="simpe-link" onclick="removeFavorits('+uid+','+chapterid+','+objectid+');">эта фирма находится в избранном</a>');
						    jQuery('#guiPFavoriteCountTab').hide();
							jQuery('#guiPFavoriteCountTab').html(data.html);
							jQuery('#guiPFavoriteCountTab').animate({ opacity: "show" }, 'slow');
                      		break;
                      	case 4: // фото
                      	    jQuery('#guiPInterestStruct').hide();
							jQuery('#guiPInterestStruct').html('<a href="javascript:void(0)" onclick="removeFavorits('+uid+','+chapterid+','+objectid+');" class="simpe-link" id="guiRemoveFromInterestingPhoto">Фото в избранном&nbsp;<img src="/public/img/red-heart-comment.gif" border="0" class="actionImg" class="actionImg"/></a>');
                      	    jQuery('#guiPInterestStruct').animate({ opacity: "show" }, 'slow');

                      	    jQuery('#guiTdInInterest').hide();
							jQuery('#guiTdInInterest').html(data.html);
							jQuery('#guiTdInInterest').animate({ opacity: "show" }, 'slow');
                      		break;
                      	case 5: // Видео
                      		break;
						case 6: // для избранных людей
							/*var html = jQuery('img[name=guiDivGrayHeart' + objectid + ']').parent('a').html();
							
							if( html.substr(0,20) == 'Добавить в Избранные' ) {
								var res = 'Удалить из списка Избранных' + html.substr(20);
								jQuery('img[name=guiDivGrayHeart' + objectid + ']').parent('a').html( res );
							}*/
							jQuery.each(jQuery('img[name=guiDivGrayHeart' + objectid + ']'), function(i, e) {
								var html = jQuery(e).parent('a').html();
								if( html.substr(0,7) == 'Следить' ) {
									var res = 'Слежу' + html.substr(7);
									jQuery(e).parent('a').html( res );
								}
							});
							
							jQuery('img[name=guiDivGrayHeart' + objectid + ']').attr('src','/public/img/red-heart-comment.gif');
							jQuery('img[name=guiDivGrayHeart' + objectid + ']').parent('a').removeAttr('onclick').unbind("click");
							jQuery('img[name=guiDivGrayHeart' + objectid + ']').parent('a').bind('click',function(){removeFavorits(uid,chapterid,objectid);});
	                        jQuery('img[name=guiDivGrayHeart' + objectid + ']').parent('a').css({cursor:'hand', cursor:'pointer'});


                      		break;
                      } // switch
                     }
		            },
    	 error    : function (){}
		});
}
/*
* Добавление в "Портфолио"
*
* uid       - идентификатор пользователя
* photoid - идентификатор фото
* objectid  - идентификатор объекта
*/



function addFavoritPortfolio(uid,photoid,catid){
 if (!parseInt(catid) || !parseInt(photoid) || !parseInt(uid)) {
  alert('Ошибка добавления в "Портфолио"!');
  return false;
 }

 var option = {};

 option['userId']    = uid;
 option['photoId'] = photoid;
 option['catId'] = catid;
 var linkId = jQuery('#linkId').val();


 jQuery.ajax({
    	 type     : "POST",
    	 url      :  "/favorits/add-portfolio",
    	 async    : false,
    	 data     : option,
    	 dataType : "json",
    	 success  : function(data){

                     if (!(data.code > 0)) {

jQuery('#guiUPortfolioStruct').html('<a class="greenLink" style="padding-left:5px;padding-right:5px;" href="/catalog/show-item/'+linkId+'"> Фотография размещена в портфолио</a>');

                     }
		            }, 
    	 error    : function (){}
		}); 
}

// Ап фото на главной 
function upPhoto(uid,photoid){
 if (!parseInt(photoid) || !parseInt(uid)) {
  alert('Ошибка при добавлении в список на комментарии');
  return false;
 }

 var option = {};

 option['userId']    = uid;
 option['photoId'] = photoid;

 jQuery.ajax({
    	 type     : "POST",
    	 url      :  "/favorits/up-photo",
    	 async    : false,
    	 data     : option,
    	 dataType : "json",
    	 success  : function(data){

                     if (!(data.code > 0)) {

jQuery('#guiUpStruct').html('<span style="font-size:14px;color:#999;">Комментарии запрошены</span>');

                     }
		            }, 
    	 error    : function (){}
		}); 
}


// Добавление чужих фото в Портфолио
function addFavoritPortfolioForeign(){

 var option = {};

 option['userId']    = jQuery('#userId').val();
 option['photoId'] = jQuery('#photoId').val();
 option['catId'] = jQuery('#catId').val();
 option['OwnerId'] = jQuery('#OwnerId').val();

 var linkId = jQuery('#linkId').val();
 

 jQuery.ajax({
    	 type     : "POST",
    	 url      :  "/favorits/add-portfolio",
    	 async    : false,
    	 data     : option,
    	 dataType : "json",
    	 success  : function(data){

                     if (!(data.code > 0)) {

jQuery('#guiUPortfolioStruct').html('<a class="greenLink" style="padding-left:5px;padding-right:5px;" href="/catalog/show-item/'+linkId+'"> Фотография размещена в портфолио</a>');

                     }
		            }, 
    	 error    : function (){}
		}); 
}

/*
 * удаление с избранного "Раздела"
 *
 * uid       - идентификатор пользователя
 * chapterid - идентификатор раздела
 * objectid  - идентификатор объекта
 */
 function removeFavorits(uid,chapterid,objectid){

  if (!parseInt(chapterid) || !parseInt(objectid) || !parseInt(uid)) {
   alert('Ошибка удаления с "Избранного"!');
   return false;
  }

  var option = {};

  option['userId']    = uid;
  option['objectId']  = objectid;
  option['chapterId'] = chapterid;

  switch(parseInt(chapterid)){
   case 1: // форум
   case 2: // статьи, рассказы
      jQuery('#guiPInterestStruct').html('<span class="articleNavi"><a href="">загрузка ...</a></span>');
   case 3: // каталог
      jQuery('#guiPInterestStruct').html('<span class="articleNavi"><a href="">загрузка ...</a></span>');
      break;
  }
	
  jQuery.ajax({
    	 type     : "POST",
    	 url      :  "/favorits/remove-from-intersting",
    	 async    : false,
    	 data     : option,
    	 dataType : "json",
    	 success  : function(data){

                     if (!(data.code > 0)) {
                       switch(parseInt(chapterid)){
                      	case 1: // форум
                      	case 2: // статьи
                      	    if (data.newcount > 0) {
                      	     jQuery('#guiPInterestStruct').html('<a href="javascript:void(0)" class="simpe-link"  onclick="addFavoritObject('+uid+','+chapterid+','+objectid+');" id="addToInteresting">Добавить в избранное&nbsp;<img src="/public/img/addToFav.png" border="0" class="actionImg" /></a>');
						     jQuery('#guiTdInInterest').hide();
							 jQuery('#guiTdInInterest').html(data.html);
							 jQuery('#guiTdInInterest').animate({ opacity: "show" }, 'slow');
                      	    }else{
								  jQuery('#guiPInterestStruct').hide();
							      jQuery('#guiPInterestStruct').html('<a href="javascript:void(0)" class="simpe-link"  onclick="addFavoritObject('+uid+','+chapterid+','+objectid+');" id="addToInteresting">Добавить в избранное&nbsp;<img src="/public/img/addToFav.png" border="0" class="actionImg" /></a>');
								  jQuery('#guiPInterestStruct').animate({ opacity: "show" }, 'slow');
								  jQuery('#guiTdInInterest').html('');
						         }
                      		break;
						case 3: // каталог
                            jQuery('#guiTdInInterest').html(data.html);
						    jQuery('#guiPInterestStruct').html('<img src="/public/img/addToFav.png" border="0" class="statusImg" />&nbsp;<a href="javascript:void(0)" id="add-favorite-link" class="simpe-link" onclick="addFavoritObject('+uid+','+chapterid+','+objectid+');">добавить в избранное</a>');

						    if (data.newcount == 0) {
                             jQuery('#guiPFavoriteCountTab').animate({ opacity: "hide" }, 'slow');
						    }else{
		                          jQuery('#guiPFavoriteCountTab').html(data.html);
							     }


                      		break;
                      	case 4: // фото
                      	    if (data.newcount > 0) {
                      	     jQuery('#guiPInterestStruct').html('<a href="javascript:void(0)" onclick="addFavoritObject('+uid+','+chapterid+','+objectid+');" class="simpe-link" id="addToInteresting">В избранные фото&nbsp;<img src="/public/img/addToFav.png" border="0" class="actionImg" /></a>');
						     jQuery('#guiTdInInterest').hide();
							 jQuery('#guiTdInInterest').html(data.html);
							 jQuery('#guiTdInInterest').animate({ opacity: "show" }, 'slow');
                      	    }else{
								  jQuery('#guiPInterestStruct').hide();
							      jQuery('#guiPInterestStruct').html('<a href="javascript:void(0)" onclick="addFavoritObject('+uid+','+chapterid+','+objectid+');" class="simpe-link" id="addToInteresting">В избранные фото&nbsp;<img src="/public/img/addToFav.png" border="0" class="actionImg" /></a>');
								  jQuery('#guiPInterestStruct').animate({ opacity: "show" }, 'slow');
								  jQuery('#guiTdInInterest').html('');
						         }
                      		break;
                      	case 5: // Видео
                      		break;
						case 6: // для избранных людей
							 
							jQuery.each(jQuery('img[name=guiDivGrayHeart' + objectid + ']'), function(i, e) {
								var html = jQuery(e).parent('a').html();
								if( html.substr(0,5) == 'Слежу' ) {
									var res = 'Следить' + html.substr(5);
									jQuery(e).parent('a').html( res );
								}
							});
							
							
                      		 jQuery('img[name=guiDivGrayHeart' + objectid + ']').attr('src','/public/img/gray-heart-comment.gif');
	                         jQuery('img[name=guiDivGrayHeart' + objectid + ']').css({cursor:'hand', cursor:'pointer'});
	                         jQuery('img[name=guiDivGrayHeart' + objectid + ']').parent('a').removeAttr('onclick').unbind("click");
							 jQuery('img[name=guiDivGrayHeart' + objectid + ']').parent('a').bind('click',function(){addFavoritObject(uid,chapterid,objectid, 1);});
								//location.reload(true);
                      		break;
                      } // switch

                     }
		            },
    	 error    : function (){}
		});
 }

/*
 * Пользовательская функция для удаления избранного
 *
 * uid       - идентификатор пользователя
 * chapterid - идентификатор раздела
 * objectid  - идентификатор объекта
 *
 */
 function removeMyFavorits(uid,chapterid,objectid){
   if (!parseInt(chapterid) || !parseInt(objectid) || !parseInt(uid)) {
   alert('Ошибка удаления с "Избранного"!');
   return false;
  }

  showPopUpWindow('guiConfirmForm');

  jQuery('#guiHeaderMessage').css('color','#d90606');
  jQuery('#guiHeaderMessage').html('Удаление');
  jQuery('#guiBlockMessage').html('Вы уверены, что хотите удалить объект из Избранного!');
  jQuery('#guiBtnConfirmWin').attr('value','Да, уверен');
  jQuery('#guiBtnConfirmWin').bind('click',function(){
    jQuery(this).attr('disabled',true);
	var option = {};

    option['userId']    = uid;
    option['objectId']  = objectid;
    option['chapterId'] = chapterid;

    jQuery.ajax({
    	 type     : "POST",
    	 url      :  "/favorits/remove-from-intersting",
    	 async    : false,
    	 data     : option,
    	 dataType : "json",
    	 success  : function(data){
                    if (!(data.code > 0)) {
                      jQuery(this).attr('disabled',false);
                      location.reload(true);
                     }
				    },
    	 error    : function (){}
		});
  });




 }



