/**
 * Copyright: Codetipi
 * Plugin: Lets Review
 * Version: 3.1.1
 */
 (function( $ ) {

    'use strict';
	var lrPrv = {
		init: function() {
			this.cacheDom();
			this.cacheData();
			if ( parseInt( lrJS.letsReviewUReviews ) === 1 ) {
				this.sliderLoaders();
			}
			this.bindEvents();
			this.lightboxInit();
			this.tempAni();
			this.userRating();
		},
		cacheDom: function() {
			this.$doc				= $( document );
			this.$win 				= $( window );
			this.$body				= $( 'body' );
			this.$lrCheck			= $( '#lr-check' );
			this.rtl 				= this.$body.hasClass('rtl') ? true : false;
			this.$userRating 		= $( '[id^="cb-user-rating-"]' );
			this.$formLabels		= $( '.lets-review-ur-onoff-label' );
			this.$lrForm			= $( '.lets-review-form' );
			this.$toolTipOutput		= '';
			this.$toolTipCurrent	= '';
			this.cookies = 			Cookies.get('lets_review_user_rating');

			if ( parseInt( lrJS.letsReviewUReviews ) === 1 ) {
				this.dataGather 	= $(".lets-review-form-crits:first").data();
				this.$cSliders 		= $( '.lets-review-c-slider' );
			}
		},
		cacheData: function() {
			this.$winWidth			= this.$win.width();
		},
		bindEvents: function() {
			if ( this.$lrCheck.hasClass( 'lr-binded' ) ) {
				return;
			}
			this.$lrCheck.addClass('lr-binded');
			this.$win.on( 'resize', this.resize.bind(this) );
			this.$body.on( 'click', this.$formLabels, this.formLabels );
			this.$body.on( 'click', '.lets-review__up-down', this.upDown );
			this.$body.on( 'mouseenter', '.lr-tip', this.toolTipInit );
			this.$body.on( 'mousemove mouseleave click', '.lr-user__rating', this.userRatingBlock );
			this.$body.on( 'click touchend','#swipebox-slider .current img', function(){
				return false;
			}).on('click touchend','#swipebox-slider .current', function(){
				$('#swipebox-close').trigger('click' );
			});
			this.$doc.on( 'slide', '.lets-review-c-slider', this.slideIt );
			this.$doc.on( 'input', '.lr-input-score', this.visitorInput );

		},
		formLabels: function() {
			if ( lrPrv.$formLabels.length === 0 ) {
				return;
			}
			if ( $(this).find('input[name=lets_review_ur_onoff]:checked').val() === 'on' ) {
				lrPrv.$lrForm.slideDown( 200 );
 			} else {
 				lrPrv.$lrForm.slideUp( 200 );
 			}
		},
		lightboxInit: function() {
			if ( !!$.prototype.swipebox ) {
				$( '.lets-review-lightbox' ).swipebox( {
					hideBarsDelay : 0
				} );
			}
		},
		toolTipInit: function( e ) {
			if ( lrPrv.$winWidth < 1200 ) return;
			lrPrv.$toolTipCurrent = $( this );
			lrPrv.$toolTipCurrent.addClass( 'lr-tipped' );
			var direction = 'lr-tip-wrap-b';

			if ( lrPrv.$toolTipCurrent.hasClass( 'lr-tip-r' ) ) {
				direction = 'lr-tip-wrap-r';
			}
			if ( lrPrv.$toolTipCurrent.hasClass( 'lr-tip-l' ) ) {
				direction = 'lr-tip-wrap-l';
			}

			var output = '<div class="lr-tip-wrap font-s ' + direction  + '">' +
				'<div class="inner">' +
					lrPrv.$toolTipCurrent.data( 'title' ) +
				'</div>' +
				'<div class="detail"></div>' +
				'</div>';

			lrPrv.$body.append( output );

			lrPrv.$toolTipOutput = lrPrv.$body.find( ' > .lr-tip-wrap:not(.removing)' );

			if ( lrPrv.$toolTipCurrent.hasClass( 'lr-tip-move' ) ) {
				lrPrv.$toolTipCurrent.on( 'mousemove', lrPrv.tooltipLive );
				lrPrv.$toolTipOutput.addClass( 'lr-tip-mover' );
			} else {
				lrPrv.tooltipSetup();
			}

			lrPrv.$toolTipCurrent.on( 'mouseleave', lrPrv.tooltipDestroy );
		},
		tooltipDestroy: function() {
			lrPrv.$toolTipOutput.addClass( 'removing' );
			setTimeout( function() {
				$( '.removing' ).remove();
			}, 500 );
			lrPrv.$toolTipCurrent.off( 'mouseleave mousemove' );
		},
		tooltipLive: function( e ) {
			lrPrv.tooltipSetup( { 'left': e.clientX, 'top': e.clientY } );
		},
		tooltipSetup: function( args ) {
			if ( typeof( args ) === 'undefined' ) {
				args = {};
			}
			if ( typeof( args.output ) === 'undefined' ) {
				args.output = lrPrv.$toolTipOutput;
			}

			if ( typeof( args.current ) === 'undefined' ) {
				args.current = lrPrv.$toolTipCurrent;
			}

			var	instanceDetails = lrPrv.getDetails( args.output );
			var offset = lrPrv.getDetails( args.current );

			if ( typeof( args.left ) === 'undefined' ) {
				args.left = offset.left + ( offset.width / 2 ) - instanceDetails.width / 2;
			} else {
				args.left = args.left - instanceDetails.width / 2;
			}

			if ( typeof( args.top ) === 'undefined' ) {
				args.top = offset.top;
				args.top = args.top + offset.height;
			} else {
				args.top = args.top + 10;
			}

			if ( args.current.hasClass( 'lr-tip-r' ) ) {
				args.top = offset.top + ( offset.height / 2 ) - ( instanceDetails.height / 2 );
				args.left = offset.width + offset.left + 10;
			} else if ( args.current.hasClass( 'lr-tip-l' ) ) {
				args.top = offset.top + ( offset.height / 2 ) - ( instanceDetails.height / 2 );
				args.left =  offset.left - instanceDetails.width - 10;
			}
			args.output.css({
				left: args.left,
				top: args.top
			}).addClass( 'lr-tip-wrap-visible' );
		},
		resize: function( el, value ) {
			this.cacheData();
		},
		getDetails: function( elem ) {
	   		var output = elem[0].getBoundingClientRect();
	   		return { left: output.left, top: output.top, width: output.width, height: output.height };
		},
		tempAni: function( e ) {
			var box = document.querySelectorAll( '.lets-review-unseen' ),
				observer = new IntersectionObserver(function (entries) {
				entries.forEach(function (entry) {
					if ( entry.intersectionRatio > 0 ) {
						entry.target.classList.add('lets-review-seen' );
			            observer.unobserve(entry.target);
					}
				});
			}, { threshold: [0] });
			for ( var i = box.length - 1; i >= 0; i-- ) {
				observer.observe( box[i] );
			}
		},
		visitorInput: function() {
			var _this = $(this), val = parseFloat( _this.val() ), slider = _this.prev();
			if ( isNaN( val ) ) {
				val = 0;
				_this.val( 0 );
			}
			if ( val > lrPrv.dataGather['max'] ) {
				val = lrPrv.dataGather['max'];
				_this.val( lrPrv.dataGather['max'] );
			}
			if ( val > lrPrv.dataGather['min'] ) {
				val = lrPrv.dataGather['min'];
				_this.val( lrPrv.dataGather['min'] );
			}
			slider.slider( 'option', 'value', val );
			if ( _this.hasClass('lets-review-ind-crit') ) {
				lrPrv.scoreCalc( _this );
			}
		},
		slideIt: function( event, ui) {
			var eachSlider = $(this );
			eachSlider.next().val( ui.value );
			if ( eachSlider.next().hasClass('lets-review-ind-crit') ) {
				lrPrv.scoreCalc( eachSlider.next() );
			}
		},
		sliderLoaders: function() {
			if ( this.$lrCheck.hasClass( 'lr-binded' ) ) {
				return;
			}
			this.$cSliders.each( function() {
				var currentSlider = $(this);
				currentSlider.slider({
					min: 0,
					max: lrPrv.dataGather['max'],
					range: 'min',
					step: lrPrv.dataGather['step'],
					create: function( event, ui ) {
						currentSlider.find('.ui-slider-range').css( 'background-color', currentSlider.data('color') );
					}
				});
			});
		},
		upDown: function( e ) {
			e.preventDefault();
			var _this = $(this),
				type = _this.data( 'type' ),
				_thisP = _this.closest('.lets-review-block__wrap-51'),
				cid = _thisP.data( 'cid' );
			$.ajax({
			    method: 'POST',
			    data: {
			    	type: type,
			    	cid: cid,
			    },
			    url: lrJS.root + 'ud',
			    beforeSend: function( xhr ) {
			    	_thisP.addClass( 'updown-do' );
			        xhr.setRequestHeader( 'X-WP-Nonce', lrJS.nonce );
			    },
			    success: function( response ) {
			    	var upNew = response['upNew'],
			    		downNew = response['downNew'];
				    _thisP.find('.lets-review__up .updown-count').html( response['upNew'] );
				    _thisP.find('.lets-review__down .updown-count').html( response['downNew'] );
			    	Cookies.set( 'lr_updown', JSON.stringify( response['cook'] ), { expires: 30 });
			    	_thisP.removeClass( 'updown-do' );
			    },
			    error: function( response ) {
			        console.log( 'ERROR', response.responseText );
			    }
			});
		},
		scoreCalc: function( sliderTarget ) {

	        var cbTempTotal = 0;
	        var cbTotal;
	        var cbSliderFormat = sliderTarget.data('format' );
	        var cbCritScores = sliderTarget.closest('.lets-review-form-crits').find('.lets-review-all-crits .cb-cri-score' );
	        var cbFinalScoreInput = sliderTarget.closest('.lets-review-form-crits').find('.lets-review-final-score' );
	        var cbFinalScoreInput100 = sliderTarget.closest('.lets-review-form-crits').find('.lets-review-100' );

	        cbCritScores.each(function() {
	            cbTempTotal += parseFloat( $(this).val() );
	        });

	        if ( cbTempTotal === 0 && cbFinalScoreInput.val() > 0 ) {
	        	return;
	        }

	        if ( parseInt( cbSliderFormat ) === 1 ) {
	        	cbTotal = Math.round( cbTempTotal / cbCritScores.length );
	        } else {

	        	if ( lrJS.doubleDecimalStars === 'on' ) {
	        		cbTotal = ( cbTempTotal / cbCritScores.length ).toFixed(2);
	        	} else {
	        		cbTotal = Math.round( cbTempTotal / cbCritScores.length * 10 ) / 10;
	        	}

	        }

	        if ( isNaN(cbTotal) ) {
	        	cbFinalScoreInput.val('' );
	        	cbFinalScoreInput.prev().slider( 'option', {
	        		max: lrPrv.dataGather['max'],
	        		step: lrPrv.dataGather['step'],
	        		value: cbFinalScoreInput.val()
	        	});
	    	} else {
				cbFinalScoreInput.val(cbTotal);
	    		cbFinalScoreInput.prev().slider( 'option', {
	    			max: lrPrv.dataGather['max'],
	    			step: lrPrv.dataGather['step'],
	    			value: cbTotal
	    		});

		    }

	    	if ( parseInt( cbSliderFormat ) === 1 ) {
				cbFinalScoreInput100.val( cbFinalScoreInput.val() );
			} else if ( parseInt( cbSliderFormat ) === 2 ) {
				cbFinalScoreInput100.val( cbFinalScoreInput.val() * 10 );
			} else {
				cbFinalScoreInput100.val( cbFinalScoreInput.val() * 20 );
			}

		},
		userRatingBlock: function( e ) {
			var _this = $( this ),
				doRating = _this.hasClass( 'do-rating' ),
				_thisP = _this.closest('.with__uid'),
				_thisBlockWrap = _thisP.closest( '.lets-review-block__wrap' ),
				f_score_in = _thisBlockWrap.find( '.lets-review-block__final-score .score'),
				scoreType = _thisBlockWrap.data( 'scoreType' ),
				design = _thisBlockWrap.data( 'design' ),
				uid = _thisP.data('uid'),
				isPid = _thisP.data('isPid'),
				score100 = _this.data('scoreA'),
				score100bar = score100,
				score10 = _this.data('scoreB'),
				score5 = _this.data('scoreC'),
				crit = _this.data('crit'),
				widthDir = _this.data('widthDir'),
				score = _this.find( '.lets-review-block__crit__score' ),
				voteText = _this.find( '.vote__count' ),
				overlayWrap = _this.find( '.score-overlay-wrap' ),
				bar = overlayWrap.find( '.score-overlay' ),
				bounds = lrPrv.getDetails( overlayWrap ),
				mouseX = e.clientX,
		    	mouseY = e.clientY,
		    	width = mouseX - bounds.left;
		    var htmlScoreCache = score100;
		    var user100 = Math.round( width / bounds.width * 100 );
		    if ( user100 > 99.5 ) {
		    	user100 = 100;
		    } else if ( user100 < 0 ) {
		    	user100 = 0;
		    }
		    var htmlScore = user100,
		    	user100Bar = user100;
		    if ( widthDir === 'r' ) {
		    	user100Bar = ( user100 - 100 ) * -1;
		    	score100bar = ( score100 - 100 ) * -1;
		    }

		    if ( scoreType === 2 ) {
		    	htmlScoreCache = score10;
		    	htmlScore = Math.round( htmlScore * 10 ) / 100;
		    } else if ( scoreType > 2 ) {
		    	htmlScoreCache = score5;
		    	htmlScore = Math.round( htmlScore / 20 * 10 ) / 10;
		    }

		    if ( e.type === 'mousemove' && ! doRating ) {
			    bar.css( 'width', user100Bar + '%' );
			    score.html( htmlScore );
		    	lrPrv.levelChange( design, _this, user100 );
		    }

		    if ( e.type === 'mouseleave' && ! doRating ) {
		    	bar.css( 'width', score100bar + '%' );
			    score.html( htmlScoreCache );
			    lrPrv.levelChange( design, _this, score100 );
		    }

		    if ( e.type === 'click' ) {
		    	_this.addClass( 'lr-user__rated' );
			    $.ajax({
				    method: "POST",
				    data: {
				    	uid: uid,
				    	isPid: isPid,
				    	user100: user100,
				    },
				    url: lrJS.root + 'ur',
				    beforeSend: function( xhr ) {
				    	doRating = true;
				    	if ( _thisBlockWrap.hasClass('.lets-review-block__wrap-20' ) && f_score_in.length > 0 ) {
				    		f_score_in.addClass( 'do-rating' );
				    	}
				    	_this.addClass( 'do-rating' );
				    	_thisP.addClass( 'do-rating-wrap' );
				        xhr.setRequestHeader( 'X-WP-Nonce', lrJS.nonce );
				    },
				    success: function( response ) {
				    	var new100 = response['user100New'];
				    	if ( widthDir === 'r' ) {
				    		new100 = ( new100 - 100 ) * -1;
				    	}
				    	_this.data( 'title', lrJS.i18n.alreadyVoted );
				    	_this.data('scoreA', response['user100New'] );
				    	_this.data('scoreB', Math.round( response['user100New'] * 10 ) / 100 );
				    	_this.data('scoreC', Math.round( response['user100New'] / 20 * 10 ) / 10 );
				    	bar.css( 'width', new100 + '%' );
				    	if ( scoreType === 2 ) {
					    	score.html( _this.data('scoreB') );
					    	if ( _thisBlockWrap.hasClass('.lets-review-block__wrap-20' ) && f_score_in.length > 0 ) {
					    		f_score_in.html( _this.data('scoreB') )
					    	}
				    	} else if ( scoreType === 3 ) {
				    		score.html( _this.data('scoreC') );
				    		if ( _thisBlockWrap.hasClass('.lets-review-block__wrap-20' ) && f_score_in.length > 0 ) {
					    		f_score_in.html( _this.data('scoreC') )
					    	}
				    	} else {
				    		score.html( _this.data('scoreA') );
				    		if ( _thisBlockWrap.hasClass('.lets-review-block__wrap-20' ) && f_score_in.length > 0 ) {
					    		f_score_in.html( _this.data('scoreA') )
					    	}
				    	}
					    lrPrv.levelChange( design, _this, response['user100New'] );
					    voteText.html( response['voteText'] );
				    	Cookies.set( 'lr_block_rating', JSON.stringify( response['cook'] ), { expires: 30 });
				    	f_score_in.removeClass( 'do-rating' );
				    	_this.removeClass( 'do-rating' );
				    	_thisP.removeClass( 'do-rating-wrap' );
				    },
				    error: function( response ) {
				        console.log( 'ERROR', response.responseText );
				    }
				});
		    }

		},
		levelChange: function( design, el, score ) {
			if ( design !== 6 ) {
				return;
			}
			el.removeClass( 'level-1 level-5 level-10' )
	    	if ( score < 34 ) {
				el.addClass( 'level-1' );
			} else if ( score < 75 ) {
				el.addClass( 'level-5' );
			} else {
				el.addClass( 'level-10' );
			}
		},
		userRating: function() {
			if ( lrPrv.$userRating.length === 0 ) {
		    	return;
		    }
			lrPrv.$userRating.each(function() {
				var _this = $(this);
				if ( _this.hasClass('lr-running') ) {
					return true;
				}
				var letsReviewWrap = _this.closest('.lets-review-box-wrap' );

				if ( _this.hasClass( 'cb-rated' ) || ( lrPrv.cookies instanceof Array && ( lrPrv.cookies.indexOf( letsReviewWrap.data('pid' ) ) > -1 || lrPrv.cookies.indexOf( letsReviewWrap.data('uid' ) ) > -1 ) ) ) {
					return;
				}

				_this.addClass('lr-running');
				var hoverable = '';
				switch( letsReviewWrap.data('format') ) {
				    case 1:
				        hoverable = _this.find('.cb-bar' );
				        break;
				    case 2:
				        hoverable = _this.find('.cb-bar' );
				        break;
				    default:
				        hoverable = _this.find('.cb-overlay' );
				}

				var locationOverall, cbUserRatingLocation, usRatingWidth, usRatingWidthCache, urScoreCache, urTitle, urTitleCache, urScore;
				hoverable.on('mousemove click mouseleave mouseenter', function(e) {
					_this = $(this).closest('[id^="cb-user-rating-"]' );
					letsReviewWrap = _this.closest('.lets-review-box-wrap' );
					if ( e.type === 'mouseenter' ) {
						urTitle = _this.find('.cb-criteria' );
						urTitleCache = urTitle.html();
						urScore = _this.find('.cb-criteria-score' );
						urScoreCache = urScore.data('cb-score-cache' );
						usRatingWidthCache = urScore.data('cb-width-cache' );
						cbUserRatingLocation = _this.find('.cb-overlay' );
						locationOverall = lrPrv.getDetails( cbUserRatingLocation );
						usRatingWidth = cbUserRatingLocation.find('> span' );
			            urTitle.html( urTitle.data('cb-txt') );
			        }
			        var overlaySpanCalc = '';
					var baseX = Math.ceil( ( e.pageX - locationOverall.left ) / ( cbUserRatingLocation.width() / 100 ) );
					var overlaySpan = lrPrv.rtl === true ? 100 - baseX : baseX;

		            if ( overlaySpan > 100 ) { overlaySpan = 100; }
		    		if ( overlaySpan < 1 ) { overlaySpan = 0; }
		    		var cbOutOf5 = '';
		    		switch( letsReviewWrap.data('format') ) {
					    case 1:
					        overlaySpanCalc = overlaySpan;
					        cbOutOf5 = false;
					        break;
					    case 2:
					        overlaySpanCalc = Math.round( overlaySpan * 10 ) / 100;
					        cbOutOf5 = false;
					        break;
					    default:
					        overlaySpanCalc = Math.round( overlaySpan / 20 * 10 ) / 10;
					        cbOutOf5 = true;
					}

					if ( letsReviewWrap.hasClass('cb-out-of-5') ) {
						usRatingWidth.stop().animate( { 'width' : ( 100 - overlaySpan ) + '%'}, 15);
					} else {
						usRatingWidth.stop().animate( { 'width' : overlaySpan + '%' }, 15);
					}

		    		urScore.html( overlaySpanCalc );

		    		if ( e.type === 'mouseleave' || e.type === 'click' ) {
		    			if ( letsReviewWrap.hasClass('cb-out-of-5') ) {
							usRatingWidth.stop().animate( { 'width' : (100 - usRatingWidthCache) + '%' }, 200);
						} else {
							usRatingWidth.stop().animate( { 'width' : usRatingWidthCache + '%' }, 200);
						}
		    			urScore.html( urScoreCache );
		    			urTitle.html (urTitleCache );
		    		}
var type, typeFS;
		    		if ( e.type === 'click' ) {
			            $(this).off('mousemove click mouseleave mouseenter' );
			            _this.addClass('cb-rated lr-tip lr-tip-move' );

			            $.ajax({
			                type : "POST",
			                data : { action: 'lets_review_a_cb', letsReviewNonce: lrJS.letsReviewNonce, letsReviewScore: overlaySpan, letsReviewPostID: letsReviewWrap.data('pid'), letsReviewFormat: letsReviewWrap.data('format'), letsReviewUID: letsReviewWrap.data('uid') },
			                url  : lrJS.letsReviewAUrl,
			                dataType:"json",
			                beforeSend: function() {
			                	type = letsReviewWrap.data('type' );
								typeFS = letsReviewWrap.find('.cb-score-box' );
			                	_this.addClass('cb-voting' );

			                	if ( type === 3 && cbOutOf5 === false ) {
			                		typeFS.addClass('cb-fs-voting' );
			                	}
							},
			                success : function( data ){
			                	cbUserRatingLocation.find('> span').css('width', ( data[0] + '%' ) );
			                	_this.find('.cb-votes-count').html( data[2] );
			                	urScore.html( data[1] );
			                    Cookies.set('lets_review_user_rating', data[3], { expires: 7 });
			                    _this.removeClass('cb-voting' );
			                    if ( type === 3  && cbOutOf5 === false ) {
			                    	typeFS.find('.cb-final-score').html( data[1] );
			                    	typeFS.removeClass('cb-fs-voting cb-score--' );
			                    }
			                },
			                error : function(jqXHR, textStatus, errorThrown) {
			                    console.log("ERROR " + jqXHR + " :: " + textStatus + " :: " + errorThrown);
			                }
			            });

			            return false;
		    		}
				});
			});
		},
	};

	lrPrv.init();
})( jQuery );