(function ($) {
	"use strict";
	var Plrbuilder = {
		initialised: false,
		version: 1.0,
		mobile: false,
		init: function () {
			if(!this.initialised) {
				this.initialised = true;
			} 
			else {
				return;
			}
		/*-------------- Functions Calling ---------------------------------------------------
		------------------------------------------------------------------------------------------------*/
		    
			this.menu_toggle();
			this.bottom_top();
			this.loader();
			this.closeNotification();
			
		},
		
		/*-------------- Functions Calling ---------------------------------------------------
		--------------------------------------------------------------------------------------------------*/


		// loader			
			loader: function () {
				jQuery(window).on('load', function() {
					$(".loader").fadeOut();
					$(".spinner").delay(500).fadeOut("slow");
				});
			},
		// loader
		
		// Navbar js
			menu_toggle: function() {
				$('.plr_toggle').click(function(e){
					e.stopPropagation();
					$('.plr_header_menu').toggleClass('menu_open');
				});

				$('.plr_header_menu').click(function(e){
					e.stopPropagation();
				});

				$('body,html').click(function(e){
				   $('.plr_header_menu').removeClass('menu_open');
				});
			},
		// Navbar js	
		
		// Bottom To Top
			bottom_top: function(){  
				if($('#button').length > 0){
					
					var btn = $('#button');

					$(window).scroll(function() {
					  if ($(window).scrollTop() > 300) {
						btn.addClass('show');
					  } else {
						btn.removeClass('show');
					  }
					});

					btn.on('click', function(e) {
					  e.preventDefault();
					  $('html, body').animate({scrollTop:0}, '300');
					});


				}
			},
		// Bottom To Top

			closeNotification: function(){
				$(document).on('click','.close',function(){
					$('.plr_notification').removeClass('plr_success_msg');
					$('.plr_notification').removeClass('plr_error_msg');
				})
			}
	};
	Plrbuilder.init();	
	
	
	$(document).on('click', '.submitFormValid', function(e) {	
	     e.preventDefault();
	 var  err = 0;
	 var formId= $(this).closest('form').attr('id');
	 var targetForm = $(this).closest('form');
	 var targetUrl = targetForm.attr('action');
	
	 
	  $('#'+formId+ ' .required').each(function(){
		  var thisid = $(this).attr('id');
		  var thisval = $(this).val();
		  if(thisval.trim()==''){
				showNotifications('error','Oops, you missed out some of the fields.');
			 err++;$(this).focus();return false;
			 
		  }
		  
		var valid = $(this).attr('data-valid'); 
		if(typeof valid != 'undefined'){
		    
			if(valid=='email'){
			  if (!emailValidate(thisval)) {
				showNotifications('error','You have entered an invalid email address.');
					err++;$(this).focus();return false;
			  }
		    }	
		}
	  })
	  if(err==0){
		
		 $.ajax({
            url: targetUrl,
			method: "post",
			data : new FormData(targetForm[0]),
			processData: false,
			contentType: false,
            success: function(data) {
               var resp = JSON.parse(data);
            //   return false;
			   if(resp.status){
				showNotifications('success',resp.msg);
				  
				  if(typeof resp.data_redirect != 'undefined'){ //redirect
					
					setTimeout(function(){ location.href = resp.data_redirect; }, 3000);
				  }
				  if(typeof resp.data_reset != 'undefined'){ //redirect
				      targetForm[0].reset();
				  }
				  if(typeof resp.data_reload != 'undefined'){ //redirect
				      location.reload();			  
				  }
			   }else{
				showNotifications('error',resp.msg);
			   }
            }
        })
		 
		 
		 
		 
	  }
	  
	 });
	 
	 
	 $(document).on('click', '.submitForm', function(e) {	
        var targetForm = $(this).closest('form');
		var targetUrl = targetForm.attr('action');
		
		
        $.ajax({
            url: targetUrl,
			method: "post",
			data : new FormData(targetForm[0]),
			processData: false,
			contentType: false,
            success: function(data) {
               var resp = JSON.parse(data);
			   if(resp.status){
				showNotifications('success',resp.msg);
				  if(typeof resp.data_redirect != 'undefined'){ //redirect
					
					setTimeout(function(){ location.href = resp.data_redirect; }, 3000);
				  }
				  if(typeof resp.data_reset != 'undefined'){ //redirect
				      targetForm[0].reset();
				  }
				  if(typeof resp.data_reload != 'undefined'){ //redirect
				      location.reload();			  
				  }
				  
				  
			   }else{
				showNotifications('error',resp.msg);
			   }
            }
        })
    });
    
    $(document).on('click', '.pricePlan', function(e) {
	   // console.log($(this).attr('data-plan'));
	    $('[name="planType"]').attr('data-plan',$(this).attr('data-plan'));
	    $('#PricePaymentModal').modal('show'); 
	});
	$(document).on('click', '.payment_btn', function(){
	    var _this = $(this);
        var plan = $('[name="planType"]').attr('data-plan');
        var paymentType = _this.attr('data-type');
	   // console.log(paymentType)
	    if((paymentType != '' && plan != '') && (paymentType != 'undefined' && plan != 'undefined')){
	        choosePlan(plan,paymentType);
	    }
	})
	 

}(jQuery));	

function getNextProducts(i,cateid=''){
	$('.pagination_a').each(function(){
		$(this).removeClass('active');
	});
    let numberOfPages = parseInt($('#numberOfPages').val());
    if( i != 0 && i <= numberOfPages ){
        $.ajax({
            url: baseurl + 'home/getProductsToFrontEnd', 
            type: "POST",             
            data: {'i':i,'cateid':cateid,'webid':$('#webid').val()},
            success: function(e) {
                $('#showProduct').html(e)
                $('.changePage').remove();
                let liStr = '';
                
                let webid = $('#webcateid').length > 0 ? $('#webcateid').val() : $('#webid').val() ;
    
                for(let j = i ; j < numberOfPages + 1 ; j++) {
                    if( j < i+4 || j > numberOfPages - 3 ) { 
                        let cls = j == i ? 'active' : '' ;
                        if( $('#webcateid').length > 0 ) 
							liStr += '<li class="changePage"><a href="javascript:;" class="pagination_a '+cls+'" onclick="getNextProducts( '+j+','+webid+')" data-pagenum="'+j+'">'+j+'</a></li>';
                        else
							liStr += '<li class="changePage"><a href="javascript:;" class="pagination_a '+cls+'" onclick="getNextProducts( '+j+',\'web_'+webid+'\')" data-pagenum="'+j+'">'+j+'</a></li>';
                            
                    } if( j == numberOfPages - 4 ) { 
                        liStr += '<span class="changePage">...</span>';
                    }
                }
                $('.plr_pagination ul li:eq(0)').after(liStr);
            }
        });
    }
	
}

function getOtherProducts(type,cateid=''){
	$('.pagination_a').each(function(){
		if( $(this).hasClass('active') ){
			if( type == 'last' )
				getNextProducts(parseInt($(this).data('pagenum'))+1 , cateid);
			else
				getNextProducts(parseInt($(this).data('pagenum'))-1 , cateid);
		}
	});
}

function emailValidate(mail) {
    if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,7})+$/.test(mail)) {
        return !0
    }
    return !1
}

function saveProfile(){
    let c_name = $.trim($('#c_name').val());
    if(c_name != ''){
        let websiteURLs = $('#websiteURL').val();
	    let websiteURL = (websiteURLs.split('plr/')).length == 2 ? baseurl + 'plr/'+siteurl+'/profile' : websiteURLs+'/pages/profile';
       $.ajax({
          url: websiteURL, 
          type: "POST",             
          data: {'c_name':c_name,'c_pwd':$('#c_pwd').val()},
          success: function(e) {
              if(e == 1)
			  showNotifications('success','Profile updated successfully.');
              else
              showNotifications('error','Something went wrong. Please, refresh the page and try again.');
 
             setTimeout(function(){ location.reload(); }, 3000);
          }
        });
    }else
    showNotifications('error','Please enter the name to continue.')
 }

function submitNewsletter(){
    let news_name = $.trim($('#news_name').val());
    let news_email = $.trim($('#news_email').val());
    if(news_name != '' && news_email != ''){
		if (!emailValidate(news_email)) {
			showNotifications('error','You have entered an invalid email address.');
		}
		else{
			$.ajax({
				url: baseurl + 'plr/'+siteurl+'/newsletter', 
				type: "POST",             
				data: {'news_name':news_name,'news_email':news_email},
				success: function(e) {
					if(e == 1)
						showNotifications('success','Thanks for subscribing to our newsletter.');
					else
						showNotifications('error','Something went wrong. Please, refresh the page and try again.');
	   
				   setTimeout(function(){ 
						$('#news_name,#news_email').val('');
						$('.plr_notification').removeClass('plr_success_msg');
						$('.plr_notification').removeClass('plr_error_msg');
					}, 3000);
				}
			  });
		}
    }else
    showNotifications('error','Please enter the name and email to subscribe.')
 }

function choosePlan(planId,paymentSettings){
	let loggedInUser = $('#loggedInUser').val();
    // console.log(loggedInUser)
	if( loggedInUser == 0 )
		showNotifications('error','Please login or signup before continuing.')
	else if( paymentSettings == '0' )
		showNotifications('error','Please, ask site owner to connect their payment method.')
	else{
	    let websiteURLs = $('#websiteURL').val();
	    let websiteURL = (websiteURLs.split('plr/')).length == 2 ? baseurl + 'plr/'+siteurl+'/pricing' : websiteURLs+'/pages/pricing';
	    
		$.ajax({
			url: websiteURL, 
			type: "POST",             
			data: {'planID':planId, 'paymentType':paymentSettings},
			success: function(e) {
				if(e == 'error')
					showNotifications('error','Please, ask site owner to connect their payment method.')
				else if(e == 'free')
					showNotifications('success','Thank you for purchasing a plan.')
				else{
					$('#shoot').html(e);
				    $('#PricePaymentModal').modal('hide'); 
				    if($('#stripebutton').length){
				        setTimeout(function(){
				            // console.log($('#stripebutton').length)
					        $('#stripebutton').trigger('click');
			            }, 500);
				    }
					$('#paymentButton').trigger('click');
				}
			}
		});
	}
 }

function showNotifications(type, message){
    $('.plr_notification').removeClass('plr_success_msg');
    $('.plr_notification').removeClass('plr_error_msg');
    let img = baseurl+'assets/backend/images/'+type+'.png';
    $('.plr_happy_img img').attr('src',img);
    if( type == 'success' )
        $('.plr_yeah h5').text('Congratulations!');
    else
        $('.plr_yeah h5').text('Oops!');
    $('.plr_yeah p').text(message);
    $('.plr_notification').addClass('plr_'+type+'_msg');
}

$('.plr_productFound').hide();
    $(document).on('click', '.myInput', function(e) {
            e.preventDefault();
	       var value = $('#myInput').val();
	       console.log(baseurl + 'Admin/productFilter');
	       $.ajax({
            url: baseurl + 'Admin/productFilter',
			method: "post",
			data :{'value':value},
            success: function(data) {
              var resp = JSON.parse(data);
              if(resp.status==1){
              $('.plr_pagination').hide();
                $(".plr_filter").empty();
                $("#showProduct").empty();
                setTimeout(function(){
                    $.each(resp.data, function (index, value) {
                        if(!resp.data[index]['p_imagelink']==""){
    			            var img = `<img src="${resp.data[index]['p_imagelink']}" alt="${resp.data[index]['p_name']}">`;
    			        }else{
			                var img = '<img src="'+baseurl+'assets/frontend/images/dummy/dummy'+Math.floor((Math.random() * 9) + 1)+'.png" alt="'+resp.data[index]['p_name']+'"><span class="dummyName">'+resp.data[index]['p_name']+'</span>';
                                       
    			        }
                       console.log(img);
                  $('#showProduct').append('<div class="col-xl-3 col-lg-4 col-md-6 col-sm-6" bis_skin_checked="1"><div class="plr_pro_box plr_animation_box" bis_skin_checked="1"><a href="'+resp.url+'/'+resp.data[index]['p_urlname']+'"><div class="grid_img" bis_skin_checked="1"><span class="plr_product_list_img plr_animation">'+img+'</span></div></a><div class="bottom_content" bis_skin_checked="1"><h5><a href="javascript:;">'+resp.data[index]['p_name']+'</a></h5></div></div></div>'); 
                });
                },400);
              }else{
                  $(".plr_filter").empty();
                  $('.plr_pagination').hide();
                 setTimeout(function(){
                  $('.plr_productFound').show();
                 },200);
              }
            }
        })
            
    }); 
    $('.plr_productFound').hide();
    $(document).on('click', '.CustomDomainmyInput', function(e) {
            e.preventDefault();
	       var value = $('#myInput').val();
	       $.ajax({
            url:  '/Admin/productFilter',
			method: "post",
			data :{'value':value},
            success: function(data) {
              var resp = JSON.parse(data);
              if(resp.status==1){
              $('.plr_pagination').hide();
                $(".plr_filter").empty();
                $("#showProduct").empty();
                setTimeout(function(){
                    $.each(resp.data, function (index, value) {
                  $('#showProduct').append('<div class="col-xl-3 col-lg-4 col-md-6 col-sm-6" bis_skin_checked="1"><div class="plr_pro_box plr_animation_box" bis_skin_checked="1"><a href="'+resp.url+'/'+resp.data[index]['p_urlname']+'"><div class="grid_img" bis_skin_checked="1"><span class="plr_product_list_img plr_animation"><img src="'+resp.data[index]['p_imagelink']+'" class="plr_animation_img" alt="Web Copy that Sells " data-pagespeed-url-hash="552594933" ></span></div></a><div class="bottom_content" bis_skin_checked="1"><h5><a href="javascript:;">'+resp.data[index]['p_name']+'</a></h5></div></div></div>'); 
                });
                },400);
              }else{
                  $(".plr_filter").empty();
                  $('.plr_pagination').hide();
                 setTimeout(function(){
                  $('.plr_productFound').show();
                 },200);
              }
            }
        })
            
    }); 

