var store_photos = {};
var ajax_send = {};
var phlayer_top_editor_menu = !1;
var _bottom_widget_timeout;



for (var i = 0; i < slides_C; ++i)
    store_photos[slides[i].id] = slides[i]; //store_photos.push(slides[i]);	  

 

ga('#phlayer_store_slides')
    .remove();

// set the current userid in localstorage
localStorage.setItem('attch_checkUser', uid);
 var thumbnailsUpdated, timeout_x, timeout_y;
	var inited = false;
    ga(document)
        .ready(function() {
 
            ga('#pviewer-gallery-link')
                .nobleSlider({
					//_SLIDER_ENABLE_AUTO_HEIGHT	:true,
 
					
					
                     _SLIDER_BEZIER_ENGINE: 'cubic-bezier(.6,.12,.16,.65)',
                     _SLIDE_ANIMATION_DURATION: 400, // miliseconds
                    _SLIDE_FADE: false,
                    //_ENABLE_TOUCH_FOR_THUMBS:false,
                   // _FADE_EFFECT_DURATION: 1,
                    _FADE_OUT_PREV_SLIDE: true,
 
                    _TOUCH_SWIPE_TRESHOLD: 50,
                    _TOUCH_SWIPE_SPEED_RATIO: 1.3,
                    _IMAGE_SCALE_MODE: 'original',_IMAGE_TO_CENTER:true,
                    //_ASPECT_RATIO: 1.8,
                        //,_SLIDER_ENABLE_AUTO_HEIGHT:true
                        //,_SLIDER_HEIGHT_ANIMATION_DURATION:200
                        // _IMG_SMALL_SIZE: 500,
                        // _IMG_MEDIUM_SIZE: 800,
                        // _IMG_LARGE_SIZE: 1600,
                       _ENABLE_TOUCH_SWIPE:true, 
                    _SLIDE_END_HIDE_ARROWS: true,
                    _LARGE_IMAGES_ON_FULL_SCREEN: true,
                    _FADE_ARROWS: false,
                    _NUM_IMAGES_TO_PRELOAD: 1,
                    _SLIDER_HEIGHT: ga(window).height()-90,
                    _SLIDER_WIDTH: '100%',

	
                    _INITIAL_ACTIVE_SLIDE: $('.nb-slide.__starter')
                        .index(),
                    _ALLOW_FULL_SCREEN: false,
                    _SLIDES_ORIENTATION: 'horizontal',
                    _IMAGE_TO_CENTER: true,
                    /*_ALLOW_TO_PULL: {
                                           pullDistance: 160,
                                           maxOpacity: 0.9,
                                           closeButton: '.js_popup_close',
                                           overlayClass: '.modal-new',
                                           popupContainer: '.photo-layer '
                                       },&*/
                    _ENABLE_ARROWS: false,
                    _ENABLE_PAGINATION: false,

                    _CLBK_IMAGE_LOADED: function(ev) {

                        widget_reposition(ev.index);


                        /*
                        		var act_image = $('.nb-slide.nb__active').find('img');
                        		if(!act_image.hasClass('large-image-loaded'))
                        		act_image.attr('src',act_image.attr('src').replace('&low','')).addClass('large-image-loaded');
                        */
                    },
                    _RESIZE_SLIDER: function() {
                        widget_reposition($('.nb-slide.nb__active')
                            .index(), 1);
                    },
                    update: function() {

                    },
                    _CLBK_GET_TO_SLIDE: function(ev) {
                        var evt = document.createEvent('Event');
						inited = false;
                        evt.preventDefault();
                        evt.stopImmediatePropagation();
                        for(var k in ajax_send)
                        	ajax_send[k].abort();
                        //window.stop();
                        clearTimeout(ply_r_time);
                        $('.pl_pc_photo_stub')
                            .hide();
                        $('.photo-layer_bottom')
                            .addClass('__white_bg');
                        ///$('#phlayer_ratings').empty();
                        ga(window)
                            .scrollTop(0);
                        setTimeout(function() {
                            $('.phlayer_emoji_input_sticky')
                                .removeClass('__on __bfon fixed_always')
                                .removeAttr('style');
                        }, 100);

                        // check for removed photos & remove slides
                        var removed_slides = $('.nb-slide.__removed');
                        if (removed_slides.length) {
                            setTimeout(function() {
                               	ga('.pviewer-footer,.photo_viewer_right_sidebar,.header-more-pviewer').show();
                                    
                                $('.pl_pc_photo_stub')
                                    .remove();
                                removed_slides.remove();
                                $('#pviewer-gallery')
                                    .nobleSlider('_previousSlide');
                                $('#pviewer-gallery')
                                    .nobleSlider('update');

                            }, 150);
                        }
                        phlayer_top_editor_menu = !1;
						
						// disable zoom in when slide to another photo
						if(ga('#phlayer_zoom').hasClass('active'))
							ga('#phlayer_zoom').trigger('click.zoomin');

                    },
                    _CLBK_WHEN_SLIDE_COMPLETE: function(ev) {
					//	var evt = window.event || event;
						//evt.preventDefault();
						
						//evt.stopPropagation();
						 
                      //  for(var k in ajax_send)
                        //	ajax_send[k].abort();						
                        //window.stop();
                        var act_image = $('.nb-slide.nb__active')
                            .find('img');
                        //if(!act_image.attr('src').indexOf('&low') == -1)
                        //act_image.attr('src',act_image.attr('src').replace('&low','')).addClass('large-image-loaded');

                        //widget_reposition(ev.index);
                        var curul_slide = $('.nb-slide.nb__active');
                        var curul_slide_id = curul_slide.data('slpid'); //$('.nb-slide').eq(ev.index).data('slpid');
                        act_image.addClass('target-photo-' + curul_slide_id);
                        clearTimeout(ply_r_time);
                        ply_r_time = setTimeout(function() {
							ga('#curr_pviewer_pictureid').val(curul_slide_id);
                            ga('.photo-layer_bottom')
                                .removeClass('__white_bg');
                            getPhotoBottomValues(curul_slide_id, curul_slide, ev.index);

                        }, 250);
						
						if(ga('.pviewer_more_btn').hasClass('opened'))
							ga('.pviewer_more_btn').trigger('click');
				 
						createUrl('', '', store_photos[curul_slide_id]['direct-photo-link']);//photo_direct_link);
						//if(!inited){initPviewer(curul_slide_id);inited=true;}
                    }
					
					
                }); // slider
				//initPviewer(phl_inited_photo);
			 }); // document
		
 	
		function  getPhotoBottomValues(i, imgtag, imgindex){
			
			
			
			
		if (i === phlayer_last_infID && !ga('#initialized-by-dom').length) { return;}

			phlayer_last_infID = i;
			
			var g = store_photos[i];
		// console.log(g);
 /*
			var w_js_count = '.js-count';
			// update photo description
			//ga('[rel="widget-likes"]').find(w_js_count).html(g.info);
			
			// update photo comments count
			ga('[rel="widget-comments"]').find(w_js_count).text(g.count_comments);
			
			// update photo shares count
			ga('[rel="widget-shares"]').find(w_js_count).text(g.shares_count);
			
			// update photo likes count
			ga('[rel="widget-likes"]').find(w_js_count).text(g.likes);
 
			ga('.pviewer-picture-album').html( g.albid == null ? '<a href="/profile?q='+g.uid+'&cmd=pphotos&nav=photos" onclick="ga(\'.pviewer_close_btn\').trigger(\'click\');" hrefattr="true">'+lang.personal_photos+'</a>' : '<a href="/profile?q='+g.uid+'&cmd=album&i='+g.albid+'&nav=photos" hrefattr="true">'+g.albumname+'</a>');
			*/
			/*ga('#bottom_like_button').replaceWith('<a class="item_button item_like '+ ( g.liked_by_me > 0 ? '__active' : '' ) +'" id="bottom_like_button" href="javascript:void(0);" data-log-click=\'"type":"like","item":"photo","itemid":"'+g.id+'"\'>\
					<span class="ico-like glyphicon glyphicon-heart"></span>\
					<b id="pviewer-likes-count" class="v_value v_like js-count js_count">'+g.likes+'</b></a>');
 */
 
				/*
			
			if(g.liked_by_me > 0 ){
				
				ga('[rel="widget-likes"]').find('.widget').addClass('__active');
				
			} else {
				
				ga('[rel="widget-likes"]').find('.widget').removeClass('__active');
			}
			
			
			if(g.shared_by_me > 0){
				
				ga('#sharebuttonwp').parent().addClass('__active');
				
			} else {
				
				ga('#sharebuttonwp').parent().removeClass('__active');
			}
			*/
			// hide tags
			   ga('#picture_tags').hide()
                ga('#picture_tags').find('tgdt').empty();
			
			if(ga('#initialized-by-dom').length){
				getPhotoStars(escape(g.id));
			 
				getPhotoComments(escape(g.id));
				getPhotoTags(escape(g.id));
				ga('#initialized-by-dom').remove();
				return;			
			}
			
			// set author image
			if(clubid > 0)
			ga('#pviewer_bot_pic_author_img').html('<a href="/community/'+clubid+'" hrefattr="true"><img src="/clubpicture?i='+clubid+'&size=small&clubid='+clubid+'&corr=1&logo=true" /></a>');	
			else
			ga('#pviewer_bot_pic_author_img').html('<a href="/user/'+g.uid+'" hrefattr="true"><img src="/getPhoto?p='+g.uphoto+'&sz=small" /></a>');
			
			// author fullname
			if(clubid > 0)
			ga('#pviewer_bot_pic_author_name').html('<a href="/community/'+clubid+'" hrefattr="true">'+g.name+'</a>');
			else
			ga('#pviewer_bot_pic_author_name').html('<a href="/user/'+g.uid+'" hrefattr="true">'+g.fullname+'</a>');
			
			// picture added
			ga('#pviewer_bot_pic_added').html(g.padded);
			
			
			//picture album
			if(clubid > 0)
			ga('#pviewer_bot_pic_album').html(
			
				g.community_album_id == null ? '<a hrefattr="true" href="/community/'+clubid+'/album-0">'+lang.Community_Main_album+'</a>' : '<a href="/community/'+clubid+'/album-'+community_album_id+'" hrefattr="true">'+g.community_album_name+'</a>'
			);
			else
			ga('#pviewer_bot_pic_album').html(
			
				g.albid == null ? '<a hrefattr="true" href="/profile?q='+g.uid+'&cmd=pphotos&nav=photos">'+lang.personal_photos+'</a>' : '<a href="/profile?q='+g.uid+'&cmd=album&i='+g.albid+'&nav=photos" hrefattr="true">'+g.albumname+'</a>'
			);
			
			// picture full size link
			if(clubid > 0)
			ga('#pviewer_bot_pic_link').html('<a href="/clubpicture?i='+g.id+'&size=large&clubid='+clubid+'" target="_blank">'+lang.Pviewer_view_full_size+'</a>');	
			else
			ga('#pviewer_bot_pic_link').html('<a href="/getPhoto?p='+g.id+'&sz=large" target="_blank">'+lang.Pviewer_view_full_size+'</a>');
			
			// picture description
			if(g.info != ''){
			ga('#pviewer_bot_pic_info').html(g.info);
			ga('#picture_description').show();
			} else {
				ga('#picture_description').hide();
			}
			
			up_href();
			
			
			ga('#link-photo-viewer-widget-buttons').html('<div class="div-loader photoviewer"></div>');
			ga('.comm_widget_pb').empty();
			
			var getWidgetData = function(){
				
			var send_arr = {};
			
 
			send_arr['cmd'] = 'photoviewer-get-widget-values';
			send_arr['photoid'] = escape(g.id);
			send_arr['link'] = '1';
			send_arr['author'] = escape(g.uid);
			if(clubid > 0) send_arr['clubid'] = escape(clubid);
			
			
			
			ajax_send.getWidgets = jAjax('/cmd.php', 'post', send_arr);
			ajax_send.getWidgets.done(function(data) {
				  
				ga('#link-photo-viewer-widget-buttons').html(data);
				getPhotoStars(escape(g.id));
				getPhotoComments(escape(g.id));
				getPhotoTags(escape(g.id));
			});
			}
			
			
		 
				
				getWidgetData();
		 
			
			// update like button 
			/////ga('#bottom_like_button').removeAttr('data-log-click').attr('data-log-click','{"type":"like","item":"photo","itemid":"'+g.id+'"}');
			
			
		}
		
		
function pviewerUpdateLikeDB(c,picture_id){
	picture_id = ga('#curr_pviewer_pictureid').val();
 
	switch(c) {
		
		
		case 'active':
		store_photos[picture_id]['liked_by_me'] = 1;
		store_photos[picture_id]['likes']++;
		break;
		
		case 'inactive':
		store_photos[picture_id]['liked_by_me'] = 0;
		store_photos[picture_id]['likes']--;
		break;
	}
	
	
	
}
		
		
    function widget_reposition(index, x) {

        var cur_slide = ga('.nb-slide')
            .eq(index),
            cur_slide_img = cur_slide.find('img');

        if (cur_slide_img.attr('src') !== preloader || x) {

            var css = {},
                _L_R = (cur_slide.width() - cur_slide_img.width()) / 2,
                _L_B = (cur_slide.height() - cur_slide_img.height()) / 2;
            css['right'] = _L_R;
            css['bottom'] = _L_B;
            css['display'] = 'inline';
            cur_slide.find('.widget_photoLayer')
                .css(css);
            cur_slide.find('.widget_lsco_bot_shadow')
                .css({
                    'display': 'inline',
                    'width': cur_slide_img.width(),
                    'left': _L_R,
                    'height': cur_slide_img.height(),
                    'top': (cur_slide.height() - cur_slide_img.height()) / 2
                });
            cur_slide.find('.photo-layer_bottom_block')
                .css({
                    'left': _L_R,
                    'bottom': _L_B,
                    'visibility': 'visible'
                });
            cur_slide.find('.photo-layer_description_tx')
                .css('max-width', cur_slide_img.width() - 200);

        }

    }
	
	function initPviewer(picture_id){  
		var g = store_photos[picture_id];
		
		ga(document).off('click.showPviewerRightMenu').on('click.showPviewerRightMenu', '.pviewer_more_btn', function(e){
		
		var pviewer_right_sidebar = ga('.photo_viewer_right_sidebar');
		if(!ga(this).hasClass('opened')) {
			
		ga(this).addClass('opened');
		pviewer_right_sidebar.css({
                            '-webkit-transform': 'translate3d(0,0px,0)',
                            'transform': 'translate3d(0,0px,0)'
                        });
						
		}else{
		
			pviewer_right_sidebar.removeAttr('style');
			ga(this).removeClass('opened');
		}
		});
		
        var phlayer_crop_photo = ga('#phly_crop_photo_btn');
        var phly_rotate_photo = ga('#phly_rotate_photo');
        var phly_delete_photo = ga('#phly_delete_photo');
        
        // tag people
        ga('#phlayer_tag_friends')
            .off('click.tagP')
            .on('click.tagP', function(e) { 
                e.preventDefault();
                var __image_to_det = ga('img.target-photo-' + g.id);

 

                // check for tags in photo
                var get_tags_in_photo = __image_to_det.parent()
                    .find('.__tagged');
                if (get_tags_in_photo.length) {
                    var get__this_tag_id = get_tags_in_photo.find('._tagged_user')
                        .attr('id')
                        .split('_')[1];
                    __tags_users_ck.push(get__this_tag_id);

                    if (g.userid === _U.i)
                        get_tags_in_photo.removeClass('__defaultCur')
                        .draggable({
                            containment: "parent"
                        });
                    else {

                        get_tags_in_photo.each(function() {
                            var this_tag_id = ga(this)
                                .find('._tagged_user')
                                .attr('id')
                                .split('_')[1];

                            if (this_tag_id === _U.i)
                                get_tags_in_photo.find('#tgu_' + this_tag_id)
                                .parent()
                                .removeClass('__defaultCur')
                                .draggable({
                                    containment: "parent"
                                });
                            get_tags_in_photo.find('#tgu_' + this_tag_id)
                                .find('.tagged_close')
                                .removeAttr('onclick')
                                .off('click.deleteMeFromTags click')
                                .on('click.deleteMeFromTags', function(e) {
                                    e.preventDefault();

                                    $(this)
                                        .closest('section')
                                        .remove();
                                    deleteTagsFromBottom(this, event);
                                    $('#finish_tag_edit').addClass('tg_remove_himself')
                                        .trigger('click');
                                });
                        });

                    }

                }

                $('.photo_viewer_top_sidebar')
                    .addClass('__off');
                $('.photo-layer_panel.__pins')
                    .removeClass('__off')
                    .on(crossEvent, function() {
                        $(this)
                            .addClass('z1');
                    });
                __image_to_det.off('click.tagit')
                    .on('click.tagit', function(e) {
                        var $this = $(this);
                        var offset = $this.parent()
                            .offset();

                        var position = {

                            left: e.pageX - 7 - offset.left,
                            top: e.pageY - 7 - offset.top
                        }

                        var __tag_appendFriends = function() {
                            var __me_tg_fr = '<div class="tag_me fixed_always"><div onclick="return _tagThisUser(this,event);" data-taginfo=\'{"uname":"' + _U.n + '","uid":"' + _U.i + '","uphoto":"' + _U.p + '","ugender":"' + _U.g + '"}\' id="taguinfo_' + _U.i + '" class="__tags_friends_list"><img src="/getPhoto?p=' + _U.p + '&sz=small&g=' + _U.g + '"><span class="utagName">' + _U.n + '</span></div></div>';
                            var __tg_allFriends = '';
                            for (var j = 0; j < __tag_friends.length; j++) {
                                var __f_vr_d = __tag_friends[j];
                                __tg_allFriends += '<div onclick="return _tagThisUser(this,event);" data-taginfo=\'{"uname":"' + __f_vr_d.name + '","uid":"' + __f_vr_d.id + '","uphoto":"' + __f_vr_d.photo + '", "ugender" : "' + __f_vr_d.gender + '"}\' id="taguinfo_' + __f_vr_d.id + '" class="__tags_friends_list"><img src="/getPhoto?p=' + __f_vr_d.photo + '&sz=small&g=' + __f_vr_d.gender + '"><span class="utagName">' + __f_vr_d.name + '</span></div>';
                            }

                            $('section.phlayer_tag:not(.__tagged)')
                                .remove();
                            var tag_markup = $('<section class="phlayer_tag" style="display:block;border-radius: 50%;width:14px;height:14px;background:rgba(0,0,0,0.55);"><div class="phlayer_tags"><div onclick="$(this).closest(\'section\').remove();deleteTagsFromBottom(this,event);" class="close_box_ic"></div><input placeholder="' + lang.whoIsIt + '" onkeyup="showTagAsTextBtn(this,event);" type="text" class="phlayer_tags_input">' + __me_tg_fr + '<div class="sct_tag_my_friends">' + __tg_allFriends + '</div></div></section>')
                                .draggable({
                                    containment: "parent"
                                })
                                .css({
                                    "position": "absolute",
                                    "top": position.top,
                                    "left": position.left
                                });

                            $this.parent()
                                .append(tag_markup)
                                .find('.phlayer_tags_input')
                                .fastLiveFilter('.sct_tag_my_friends', {
                                    timeout: 200,

                                })
                                .focus();
                        }

                        // get friends
                        var __tagP_gFriends = function() {



                            ajaxLoading();

                            ajax_send.tag_friends = jAjax('/cmd.php', 'post', 'cmd=getAllFriends');

                            ajax_send.tag_friends.done(function(data) {

                                removeAjaxLoad();
                                var data = validateJson(data, 1);

                                __tag_friends = data;
                                __tag_appendFriends();
                            });

                        }
                        if (!__tag_friends) __tagP_gFriends();
                        else __tag_appendFriends();



                    })
                    .addClass('tagging');
                $('#pviewer-gallery')
                    .nobleSlider('destroyTouchSwipe')
                    .nobleSlider('destroyKeyboard');
                // destroy arrows & big like btn
                ga('.photo_viewer_right_sidebar,.header-more-pviewer,.pviewer-footer').fadeOut();
             ///   $('.nb-full-screen-button').addClass('_hide_always');




            });


        // photo getlink
        ga('#phlayer_get_link')
            .off('click.photo_link')
            .on('click.photo_link', function(e) {
				 
					itemGenerateLink();
            });
        // photo report
        ga('#phly_report_photo')
            .off('click.photo_report')
            .on('click.photo_report', function(e) {
                var phly_send_obj = {
                    "uid": navuid,
                    "id": i,
                    "type": "photo"
                };
                return windowsPopup('report_photo', phly_send_obj);
            });
		 
        // hide options buttons for non-owner of this photo
        if (g.userid !== _U.i) {
			
            phlayer_crop_photo.hide(); // crop btn
            phly_delete_photo.hide(); // delete btn
            phly_rotate_photo.hide(); // rotate btn
            ga('#phlayer_bookmark_photo').show(); // bookmark photo
            ga('#phly_report_photo').show(); // report photo
 
        } else {
            phlayer_crop_photo.show(); //crop btn
            phly_delete_photo.show(); // delete btn
            phly_rotate_photo.show(); // rotate btn
            ga('#phlayer_bookmark_photo').hide(); // bookmark photo
            ga('#phly_report_photo').hide(); // report photo
			
			
			
			
			localStorage.setItem('phlayer-rotatephoto', picture_id);
			phly_rotate_photo.attr('data-photoc', picture_id);
			
			
        phly_delete_photo.attr({
            'href': '/profile?q=' + uid + '&cmd=deletephoto&ph=' + picture_id,
            'data-undophoto': '{"uid":"' + uid + '","pid":"' + picture_id + '","aid":"' + g.paid + '","pfl":"' + g.pfilename + '","ex":"' + g.pext + '","fsize":"' + g.fsize + '","pos":"' + g.ppos + '","ad":"' + g.padded + '"}'
        });
        // insert into localstorage data for undelete respective photo
        localStorage.setItem('phlayer-undophoto', '{"uid":"' + uid + '","pid":"' + picture_id + '","aid":"' + g.paid + '","pfl":"' + g.pfilename + '","ex":"' + g.pext + '","fsize":"' + g.fsize + '","pos":"' + g.ppos + '","ad":"' + g.padded + '"}');

			
			
			// crop photo
			phlayer_crop_photo.on('click',function(e){
				e.preventDefault();  
				cropPicture(this);
				
				
			});
			

			
			
        }		
		
		isFavorite(picture_id);


	}
	
	function getPhotoComments(pid){
		
		
		ga('#phlayer-com-emoji').empty(); 

		var s_element = clubid ? ga('#phlayer-com-emoji').addClass('incommunity') : ga('#phlayer-com-emoji'); 

		
				// build comments section
		commentsWidget( ///ga('#phlayer_act_f2').val(),
						pid,
						s_element,
						'photo',
						{'width':'100%','height':'auto','min-height':40,'overflow':'hidden','box-sizing':'border-box'/*,'padding':'1px'*/},
						ga('#pp_photo_viewer'),
						'#phlayer-com-emoji', uid,'2',1,function(){

		

			
		if( ga('[anchor="1"]').length && ga('.comment').length ) {
			 
		//scrollToAnchor(ga('[anchor="1"]').attr('id'));
		ga('html').scrollTop( ga('[anchor="1"]').offset().top);
		}
						});
		

	}
	
	
	function getPhotoStars(picture_id){
		var i = picture_id;
		
       // get photo rating
        ajax_send.check_ratings = jAjax('/profile', 'post', 'cmd=check_photo_rate&type=pos&photoid=' + i + (clubid ? '&clubid='+clubid : ''));
        ajax_send.check_ratings.done(function(data) {  
            var data = validateJson(data, 1); 
            var phlayer_bottom_cnt = ga('.photo_layer_bottom_com'),
                phlayer_rating_section = ga('#phlayer_ratings');


            if (data.success) {

                var no_rated_markup = '<div data-photoc-id="' + i + '" data-rateit-u="cmd=rateit&type=pos&itemid=' + i + (clubid ? '&clubid='+clubid : '')+'" class="phlayer_rating_stars '+ (clubid ? 'is_community' : '') +'" id="phlayer_rating_stars"><div class="rate-ex0-cnt __empty ' + (data.photo_owner ? '__stdisabled' : '') + '">\
            		<div id="1" class="rate-btn-1 rate-btn"></div>\
            		<div id="2" class="rate-btn-2 rate-btn"></div>\
            		<div id="3" class="rate-btn-3 rate-btn"></div>\
            		<div id="4" class="rate-btn-4 rate-btn"></div>\
            		<div id="5" class="rate-btn-5 rate-btn"></div>\
        		</div></div>';

                var rated_markup = '<div data-photoc-id="' + i + '" class="phlayer_rating_stars" id="phlayer_rating_stars">\
			<div class="rate-ex0-cnt __rated ' + (data.voted_by_me == 1 ? '__dbld' : '') + '">\
            		<div id="1" class="rate-btn-1 rate-btn"></div>\
            		<div id="2" class="rate-btn-2 rate-btn"></div>\
            		<div id="3" class="rate-btn-3 rate-btn"></div>\
            		<div id="4" class="rate-btn-4 rate-btn"></div>\
            		<div id="5" class="rate-btn-5 rate-btn"></div>\
        		</div></div>';

                var rated_markup =

                    '<div data-photoc-id="' + i + '" ' + (data.voted_by_me == 1 ? 'title="' + lang.your_rate_is.replace('%s', data.my_rate) + '"' : '') + ' class="phlayer_rating_stars __exist_rating ' + (data.voted_by_me == 1 ? '__dbld' : '') + (data.photo_owner ? '__stdisabled' : '') + '" id="phlayer_rating_stars">\
					 <div id="star_already_rated_0_simulator" class="star_bg" style="position: absolute; top: 0px; left: ' + Math.floor(data.rate_bg) + 'px; padding: 0px; margin: 0px; width: 120px; height: 24px; /*z-index: 0; */background-position: -' + Math.floor(data.rate_bg) + 'px 0px;background-repeat: repeat-x;"></div>\
					 <div id="star_already_rated_1_simulator" class="star_bg" style="position: absolute; top: 0px; left: 0px; padding: 0px; margin: 0px; width: ' + data.rate_bg + '%; height: 24px; /*z-index: 1; */background-position: 0px -24px;background-repeat: repeat-x;"></div>\
					 <div onclick="sendRate(this,event,255)" id="star_already_rated_2_simulator" class="star_bg" style="position:absolute;top:0px;left:0px;padding:0;cursor:pointer;margin:0;background-position: 0px -48px;background-repeat: repeat-x;width:0px;height:24px;/*z-index:2;*/"></div>\
					 <div class="phly_rating_inf">' + (data.voted_by_me == 1 ? '<!--<div class="ic tico ic_voted_succ"></div>--->' : '') + '<span class="phly_maxrw">' + data.rate_value + '</span>/5 (from ' + data.rate_times + ' ratings)</div></div>';

                /* '<div class="phlayer_rating_stars" id="phlayer_rating_stars"><div class="rate-result-cnt">\
                                    <div class="rate-bg" style="width:'+data.rate_bg+'%"></div>\
                                    <div class="rate-stars"></div>\
                                    </div></div>';
                */
                //if(!phlayer_rating_section.find('#phlayer_rating_stars').length)

                if (phlayer_rating_section.length)
                    phlayer_rating_section.html(data.rate_times && data.rate_value ? rated_markup : no_rated_markup)
                    .find('.phlayer_rating_stars.__exist_rating')
                    .off('mousemove.alreadyRated')
                    .on('mousemove.alreadyRated', function(e) {
                        if (data.voted_by_me == 1) {
                            $(this)
                                .off('mousemove.alreadyRated');
                            return;
                        }

                        var st_xoff = 0;
                        var flying_stars = ga('#star_already_rated_2_simulator'),
                            flyin_st_z = ga('#star_already_rated_0_simulator'),
                            flyin_st_o = ga('#star_already_rated_1_simulator');

                        var stars_off = e.pageX - flying_stars.offset()
                            .left;
                        if (stars_off >= 1 && stars_off <= 24) {
                            st_xoff = 20;
                            st_yoff = 120;
                            st_zoff = 0;
                        } else if (stars_off >= 24 && stars_off <= 24 * 2) {
                            st_xoff = 40;
                            st_yoff = 100;
                            st_zoff = 1;
                        } else if (stars_off >= 24 * 2 && stars_off <= 24 * 3) {
                            st_xoff = 60;
                            st_yoff = 80;
                            st_zoff = 2;
                        } else if (stars_off >= 24 * 3 && stars_off <= 24 * 4) {
                            st_xoff = 80;
                            st_yoff = 60;
                            st_zoff = 3;
                        } else if (stars_off >= 24 * 4 && stars_off <= 24 * 5) {
                            st_xoff = 100;
                            st_yoff = 40;
                            st_zoff = 4;
                        }
                        flying_stars.css('width', st_xoff + '%');

                        if (!flyin_st_o.data('star-owd'))
                            flyin_st_o.attr('data-star-owd', flyin_st_o.css('width'));
                        flyin_st_o.css('width', '0');

                        if (!flyin_st_z.data('star-ol'))
                            flyin_st_z.attr('data-star-ol', flyin_st_z.css('left'));

                        if (!flyin_st_z.data('star-owd'))
                            flyin_st_z.attr('data-star-owd', flyin_st_z.css('width'));

                        if (!flyin_st_z.data('star-obgpos'))
                            flyin_st_z.attr('data-star-obgpos', flyin_st_z.css('background-position'));

                        flyin_st_z.css({
                            'left': st_zoff * 24 + 'px',
                            'width': st_yoff + 'px',
                            'background-position': st_zoff * 24 + 'px 0'
                        });
                    })
                    .off('mouseleave.alreadyRated')
                    .on('mouseleave.alreadyRated', function(e) {
                        var flying_stars = ga('#star_already_rated_2_simulator'),
                            flyin_st_z = ga('#star_already_rated_0_simulator'),
                            flyin_st_o = ga('#star_already_rated_1_simulator');

                        flyin_st_o.css('width', flyin_st_o.data('star-owd'));
                        flyin_st_z.css({
                            'left': flyin_st_z.data('star-ol'),
                            'width': flyin_st_z.data('star-owd'),
                            'background-position': flyin_st_z.data('star-obgpos')
                        });
                        flying_stars.css('width', '0%');
                    });
            } else {

                phlayer_bottom_cnt.prepend('<div class="phlayer_rating_stars" id="phlayer_rating_stars"><h3>An error occured at receiving rates</h3></div>');

            }

        });
		
	}
	
		// is favorite
	function isFavorite(itemid){
		 
		var ajax_send_for_fv = jAjax('/cmd.php', 'post', {  "cmd" : "isfavorite", "categ":"photo", "itemid" : escape(itemid)  });
		ajax_send_for_fv.done(function(data){
			
			if(data > 0){
				
				
				ga('#phlayer_bookmark_photo').replaceWith('<div id="phlayer_bookmark_photo" data-deletebookmark="'+data+'" onclick="return deleteBookmark(event,this,\'photo\');" class="pli" title="Remove from bookmark" data-tipsy-orientation="n" rel="tipsy"><i class="ic tico ic_phly_bookmarked"></i></div>');
			} else {
				
				ga('#phlayer_bookmark_photo').replaceWith('<div id="phlayer_bookmark_photo" data-bookmark=\'{"categ":"photo","itemid":"'+itemid+'"}\' onclick="return bookmarkthis(this,event);" class="pli" title="Bookmark" data-tipsy-orientation="n" rel="tipsy"><i class="ic tico ic_phly_bookmark"></i></div>');
				
			}
			
			
		});
		
	}
	
	

// bottom tags markup
function bottom_tag_markup(pid) {

    return '<span id="plp_pinnedTrigger_%uid%" class="js-pin-trigger" data-id="%pin_id%"><span class="tag">' +
        '<span class="tag_tx"><%atag% href="/user/%uid%" hrefattr="true">%uname%</%atag%>' +
        '<span style="display:%allow_tag_delete%" onclick="return deletePhotoTag(this,event,\'%uid%\',\''+pid+'\');" data-id="%pin_id%" class="js-del-pin-trigger tag_del_w"> <i class="fader"></i> <span class="tag_del ic_close-cs1 ic10"></span></span>' +
        '</span></span></span>';

}

// get tags
function getPhotoTags(pid) {

    var _tag_markup = '<section id="utag_%uid%" class="phlayer_tag __tagged __defaultCur" style="display: block;z-index: 1; border-radius: 50%; width: 14px; height: 14px; position: absolute; top: %p_top%px; left: %p_left%px; background: rgba(0, 0, 0, 0.55);">' +
        '<div class="_tagged_user" id="tgu_%uid%"><div class="tagged_uinfo">' +
        '<div onclick="$(this).closest(\'section\').remove();deleteTagsFromBottom(this,event);" class="tagged_close ic"></div>' +
        '<img src="/getPhoto?p=%uphoto%&sz=small&g=%ugender%"><span class="tuname ellip">%uname%</span></div></div></section>';

    var bottom_tag_pin = bottom_tag_markup(pid);
   ga('#picture_tags').hide()
                ga('#picture_tags').find('tgdt').empty();
    if (!pid) return;

    ajax_send.getPhotoTags = jAjax('/cmd.php', 'post', 'cmd=getPhotoTags&photoid=' + escape(pid));
    ajax_send.getPhotoTags.done(function(data) {  
        if (data == 0) return;
        else if (data == 1) {
            $('.phlayer_tag.__tagged.__defaultCur')
                .remove();
            ga('#picture_tags').hide()
                ga('#picture_tags').find('tgdt').empty();
        } else {

            data = validateJson(data, 1);

            for (var i = 0; i < data.length; i++) {
                var r = data[i];
/*
                $('.nb-slide[data-slpid="' + pid + '"] .nb-image-container')
                    .prepend(
                        _tag_markup
                        .replace(/%p_top%/g, r.p_top)
                        .replace(/%p_left%/g, r.p_left)
                        .replace(/%uid%/g, r.userid)
                        .replace(/%uphoto%/g, r.uphoto)
                        .replace(/%ugender%/g, r.ugender)
                        .replace(/%uname%/g, r.uname)
                    );
					*/

                ga('#picture_tags')
                    .show()
                    .find('tgdt')
                    .append(
                        bottom_tag_pin
                        .replace(/%uid%/g, r.userid)
                        .replace(/%pin_id%/g, r.pin_id)
                        .replace(/%uname%/g, r.uname)
                        .replace(/%allow_tag_delete%/g, r.photo_owner === _U.i ? '' : 'none')
                        .replace(/%atag%/g, r.userid.indexOf('as-text') != -1 ? 'atag' : 'a')
                    );

            }

        }

    });
	
 
	// mouseover on bottom tagged people
	ga(document).on('mouseover.BottomTaggetPeople', '.js-pin-trigger', function(e){
		
		var uid = ex_string_number(ga(this).attr('id')); 
		ga('#utag_'+uid).addClass('show');
	}).on('mouseout.BottomTaggetPeople', '.js-pin-trigger', function(e){
		var uid = ex_string_number(ga(this).attr('id')); 
		ga('#utag_'+uid).removeClass('show');
		
	});


}

// delete tag from photo
function deletePhotoTag(el, ev, uid, photoid) {
    ev.preventDefault();

    var $el = ga(el);

   // ga('button#finish_tag_edit').addClass('__ear')
      //  .trigger('click');
		
		var send = jAjax('/cmd.php', 'post', {'cmd':'delete-tag-from-photo','photoid': escape(photoid), 'tag_id' : escape(uid)});
		send.done(function(data){
			if(data == 1){
				$el.closest('.js-pin-trigger')
					.remove();
				ga('section #tgu_' + uid)
					.closest('section')
					.remove();	
			} else {
				kn_liveNotif(lang.photo_tag_delete_error,'warn',3500,lang.photo_tag_delete_err_info);
				
			}
			
		});


}

// finish tagging
function finishTagging(el, ev) {
    ev.preventDefault();
    var $el = $(el),
        tg_remove_himself = $el.hasClass('tg_remove_himself') ? '1' : '',
        _t_obj = {};
    var ear = $el.hasClass('__ear') ? 1 : '';
    var tagging_in_slide = $('.nb-slide.nb__active');
    var __t_photo = tagging_in_slide.data('slpid');
    tagging_in_slide.find('.phlayer_tag.__tagged')
        .removeClass('ui-draggable ui-draggable-handle')
        .addClass('__defaultCur')
        .each(function(i) {
            var $this = $(this);
            var __t_position_top = $this.css('top')
                .replace('px', ''),
                __t_position_left = $this.css('left')
                .replace('px', '');
            var __t_user = $this.find('._tagged_user')
                .attr('id')
                .split('_')[1];

            if (__t_user.indexOf('as-text') != -1)
                _t_obj[i] = {
                    pos_top: __t_position_top,
                    pos_left: __t_position_left,
                    user: __t_user,
                    uname: $this.find('.tuname').text(),
                    photo: __t_photo

                };
            else
                _t_obj[i] = {
                    pos_top: __t_position_top,
                    pos_left: __t_position_left,
                    user: __t_user,
                    photo: __t_photo

                };

        });

    //alert(__tags_users_ck);

    $el.removeClass('__ear').addClass('curDefault')
        .text(lang.Please_wait);

    var afterTagDoneClick = function() {

        $el.removeClass('curDefault tg_remove_himself')
            .text(lang.Done);


 
        $el.closest('.photo-layer_panel.__pins')
            .removeClass('z1')
            .addClass('__off').on(crossEvent, function() {
                $(this).removeClass('z1');
            });
        tagging_in_slide.find('img.tagging')
            .removeClass('tagging')
            .off('click.tagit');
        $('#pviewer-gallery')
            .nobleSlider('initTouchSwipe')
            .nobleSlider('initKeyboard');

        // restore hidden elements
        ga('.photo_viewer_right_sidebar,.header-more-pviewer,.pviewer-footer').fadeIn();
         

    }

    if (!__tags_users_ck.length && !ear) return afterTagDoneClick();
    ajaxLoading();
    ajax_send.savePhotoTags = jAjax('/cmd.php', 'post', 'cmd=saveTaggsInPhoto&removeHimself=' + tg_remove_himself + '&byu=' + escape(_U.i) + '&photo=' + escape(__t_photo) + '&tags=' + JSON.stringify(_t_obj));
    ajax_send.savePhotoTags.done(function(data) {

        removeAjaxLoad();
        afterTagDoneClick();

        if (data == 2) kn_liveNotif(lang.Done,'done',5000,lang.tags_is_under_review.replace('%s', ga('.photo-layer_info_w a.ucard_info_name').html()));
			
		//jboxNotice(lang.tags_is_under_review.replace('%s', ga('.photo-layer_info_w a.ucard_info_name').html()), 'right', 'bottom', '#000'); //displayErr(lang.not_permision_to_update_tag);


    });
}


// get tagged user markup
function taggedUMarkup() {

    var _tagged_u_markup = '<div class="_tagged_user" id="tgu_%tid%"><div class="tagged_uinfo"><div onclick="$(this).closest(\'section\').remove();deleteTagsFromBottom(this,event);" class="tagged_close ic"></div><img src="%tphoto%"><span class="tuname ellip">%tuname%</span></div></div>';

    return _tagged_u_markup;

}

// tag user
function _tagThisUser(el, ev) {

    ev.preventDefault();
    var curr_tagging_photo = $('.nb-slide.nb__active');
    var $el = $(el);
    var _tag_udata = $el.data('taginfo');

    if (curr_tagging_photo.find('#tgu_' + _tag_udata.uid)
        .length)
        return kn_liveNotif(lang.Error,'warn',5000,lang.tagging_user_already_tagged);
		
		//jboxNotice(lang.tagging_user_already_tagged, 'right', 'bottom', 'red');

    $('.phlayer_tags')
        .replaceWith(
            taggedUMarkup()
            .replace(/%tid%/g, _tag_udata.uid)
            .replace(/%tphoto%/g, '/getPhoto?p=' + _tag_udata.uphoto + '&sz=small&g=' + _tag_udata.ugender)
            .replace(/%tuname%/g, _tag_udata.uname)
        );
    $('.phlayer_tag')
        .addClass('__tagged');
    $('.phlayer_bottom_tags')
        .show()
        .find('tgdt')
        .append(
            bottom_tag_markup()
            .replace(/%uid%/g, _tag_udata.uid)
            .replace(/%pin_id%/g, '')
            .replace(/%uname%/g, _tag_udata.uname)
            .replace(/%allow_tag_delete%/g, '')
            .replace(/%atag%/g, _tag_udata.uid.indexOf('as-text') != -1 ? 'atag' : 'a')
        );
    __tags_users_ck.push(_tag_udata.uid);
}

// delete bottom tags
function deleteTagsFromBottom(el, ev) {
    ev.preventDefault();
    var $el = $(el);
    var tag_uid = $el.closest('._tagged_user')
        .attr('id')
        .split('_')[1];
    ga('#plp_pinnedTrigger_' + tag_uid)
        .remove();
    delete __tags_users_ck[__tags_users_ck.pindexof(tag_uid)];
}

// show button tag as text
function showTagAsTextBtn(el, ev) {
    ev.preventDefault();
    var __tag_box = $('.phlayer_tags');
    var btn_shtxt = '<div class="plpp_add_text_c" id="plpp_add_text_c">' +
        '<button class="plpp_add_text button center __def __wide" id="plpp_add_text">' + lang.tag_add_as_text + '</button></div>';

    if (!$.trim($(el).val())) return __tag_box.find('#plpp_add_text_c').remove();

    if (!__tag_box.find('#plpp_add_text_c').length)
        __tag_box.append(btn_shtxt).find('button#plpp_add_text').off('click.tagAsText').on('click.tagAsText', function(e) {
            e.preventDefault();
            var __random_id = 'as-text-' + (new Date()).getTime();
            $('.phlayer_tags')
                .replaceWith(
                    taggedUMarkup()
                    .replace(/%tid%/g, __random_id)
                    .replace(/%tphoto%/g, '/getPhoto?p=0&sz=small')
                    .replace(/%tuname%/g, el.value)
                );
            ga('.phlayer_tag')
                .addClass('__tagged');
            $('.phlayer_bottom_tags')
                .show()
                .find('tgdt')
                .append(
                    bottom_tag_markup()
                    .replace(/%uid%/g, __random_id)
                    .replace(/%pin_id%/g, '')
                    .replace(/%uname%/g, el.value)
                    .replace(/%allow_tag_delete%/g, '')
                    .replace(/%atag%/g, 'atag')
                );
            __tags_users_ck.push(__random_id);

        });

}
