
var $jq = jQuery.noConflict();


$jq(window).on('load', function(){
	
	var pppEnabled = $jq('#pppEnabled').val();
	
	if(pppEnabled == 'Y'){
		pppGetFullPageContent('N');	
	}else{
		dapwp_payper_post_tabs_Validation();
		dapwp_enable_pay_per_post_option();	
	}
	
	$jq('#dap_metabox').show();
	$jq('.wrapper_pay_per_post').show();
	
	
});

function dapwp_enable_pay_per_post_option(){
	$jq("#enable_pay_per_post").on('change',function(){
		var enable_pay_per_post = $jq("#enable_pay_per_post:checked").prop('checked');
		//console.log("enable_pay_per_post "+enable_pay_per_post);
		if(enable_pay_per_post){
			pppGetFullPageContent('Y');
		}else{
			$jq('.enable_pay_per_post_wrapper').hide();
		}
	});
}	
function dapwp_show_teaser_content_option(){	
	$jq("#show_teaser_content").on('change',function(){
		var show_teaser_content = $jq("#show_teaser_content:checked").prop('checked');
		if(show_teaser_content){
			$jq('.teaser-content-wrapper').show();
		}else{
			$jq('.teaser-content-wrapper').hide();
		}
	});
}

function dapwp_tiny_editor_textarea(){ 
	
		tinymce.init({
			selector: 'textarea.dapwp_textare_tinymce',
		});
}

function dapwp_select_temp(temp){  
	$jq('.dapwp_template_list').find('.layout--outer').removeClass('selected');
	$jq('.dapwp_template_list').find('.layout--outer.'+temp).addClass('selected');
	$jq('.dapwp_template_list').addClass('temp_selected');
	if(temp == 'template2'){
		$jq('.button-layout-view').addClass('button-horizontal-view');
	}else{
		$jq('.button-layout-view').removeClass('button-horizontal-view');
	}
	dapwp_goto_next_tab('button_layout');
	
	
}

function dapwp_preview_set_design(){
	
	var enable_above_btn_msg =  $jq('#enable_above_btn_msg').prop('checked');
	var preview_wrapper = $jq('.button-layout-preivew_wrapper');
	if(enable_above_btn_msg){
		var above_text =  tinymce.get('above_text_textarea').getContent();
		
		preview_wrapper.find('.temp_above_text').html(above_text).show();
	}else{
		preview_wrapper.find('.temp_above_text').hide();
	}
	
	preview_wrapper.find('.btn_container').hide();
	var temp = $jq('.dapwp_template_list').find('.selected').attr('data-temp');
	if(temp == 'template2'){  
		$jq('.button-layout-view').addClass('button-horizontal-view');
	}else{
		$jq('.button-layout-view').removeClass('button-horizontal-view');
	}
	
	
	$jq('.payment_options_outer input:checked').each(function(i){ 
		    	 
         var payment_name = $jq(this).attr('data-payment-option');
         var btn_text = $jq('.btn_text_'+payment_name).val(); 
           
         if(payment_name == 'buynow'){
			payment_name = "buybutton";
         }else if(payment_name == 'rent'){
			 payment_name = "rentbutton";
		 }else if(payment_name == 'membership'){
			payment_name = "membershipbutton";
		 }
		 
         preview_wrapper.find('#'+payment_name+'.btn_container').html(btn_text).show();
    });
	
	
			
}
 
function dapwp_show_loader(){
		$jq('.dap_member_loading_wrapper').show();
}

function dapwp_hide_loader(){
	
	$jq('.dap_member_loading_wrapper').hide();
}

function dapwp_payper_post_all_tabs_Validation(){
	
	if(dapwp_general_tab_validation()){
		dapwp_show_tab_by_id('#general');
		return true;
	} else if(dapwp_btn_config_tab_validation()){
		dapwp_show_tab_by_id('#payment_button');
		return true;
	}else if(dapwp_btn_layout_tab_validation()){
		dapwp_preview_set_design();
		dapwp_show_tab_by_id('#button_layout');
		return true;
	}
	
}
function dapwp_payper_post_tabs_Validation(){
	
	
		$jq('.pay_per_post_left li.nav-item').on('click','a', function (e) {
			  e.preventDefault();
			if(e.target == e.currentTarget) {
				var current_tab_id = $jq(e.target).attr("href"); // activated tab
				
			}else {
				var current_tab_id = $jq(this).parents('li').find('a').attr("href"); // activated tab
				
			}
			
			if(current_tab_id == '#general'){
				dapwp_show_tab_by_id(current_tab_id);
				return true;
			}
			
			
			if(current_tab_id == '#general') {
				dapwp_show_tab_by_id(current_tab_id);
				return true;
			}else if(dapwp_general_tab_validation()){
				
				dapwp_show_tab_by_id('#general');
				return true;
			} 
			
			
			if(current_tab_id == '#messages') {
				dapwp_show_tab_by_id(current_tab_id);
				return true;
			}
			
			if(current_tab_id == '#button_configuration') {
				dapwp_show_tab_by_id(current_tab_id);
				return true;
			}
			
			if(current_tab_id == '#payment_button') {
				dapwp_show_tab_by_id(current_tab_id);
				return true;
			}else if(dapwp_btn_config_tab_validation()){
				
				dapwp_show_tab_by_id('#payment_button');
				return true;
			}
			
			if(current_tab_id == '#button_layout') {
				dapwp_preview_set_design();
				dapwp_show_tab_by_id(current_tab_id);
				return true;
			}else if(dapwp_btn_layout_tab_validation()){
				dapwp_preview_set_design();
				dapwp_show_tab_by_id('#button_layout');
				return true;
			}
			
			
			dapwp_show_tab_by_id(current_tab_id);
		
	});
}		

function dapwp_btn_layout_tab_validation(){
	var tab_validation_status = false;
	
	
	return tab_validation_status;
}

function dapwp_btn_config_tab_validation(){
	var tab_validation_status = false;
	var use_spc = $jq("input[name='use_spc']:checked"). val();
	if(use_spc == undefined ){
		dapwp_sweet_alert_msg('Please select button options');
		return tab_validation_status = true;
	}else if(use_spc == 'spc'){
		   var other_buy_button_link_select = $jq('select[name="other_buy_button_link_select"]').val();
		   if(other_buy_button_link_select == 0){
			   dapwp_sweet_alert_msg('Please select a checkout URL');
			 return   tab_validation_status = true;
		   }
		   
	}	
	
	var dapwp_membership_payment_checkbox = $jq(".dapwp_membership_payment_checkbox:checked").prop('checked');
	var membership_buynow_url = $jq('#membership_buynow_url').val();
	if(dapwp_membership_payment_checkbox && (membership_buynow_url == '')){
		
		dapwp_sweet_alert_msg('Please enter membership buy button URL');
		return   tab_validation_status = true;
	}
	
	if(!$jq('.dapwp_template_list').hasClass("temp_selected")){
		dapwp_sweet_alert_msg('Please select a template');
		return   tab_validation_status = true;
	}
	
	return tab_validation_status;
	
}



function dapwp_general_tab_validation(){
			var payment_option_not_select = true;
			var tab_validation_status = false;
			
			var enable_pay_per_post = $jq("#enable_pay_per_post").prop('checked');
			if(enable_pay_per_post){
				
			}else{
				dapwp_sweet_alert_msg('Please enable pay-per-post in the General tab');
				return tab_validation_status =  true;
			}
			
			var payment_select  = $jq('.wrapper_metabox_payment_option input[type="checkbox"]:checked');
			
			if(payment_select.length == 0){
				dapwp_sweet_alert_msg('Please select at least one payment option');
				return tab_validation_status =  true;
			}
			
			payment_select.each(function(){
				if(tab_validation_status){
					return tab_validation_status; 
				}
				var option_number = $jq(this).attr('data-payment-option');
				
				var pricing_field_selector = $jq('.pricing_section_outer .pricing_wrapper_'+option_number);
				var price = pricing_field_selector.find('input.price').val();
				
				if(option_number == 'buynow'){
					option_number = 'buy now';
				}
				
				if(price == 0 || price == ''){
					
					dapwp_sweet_alert_msg('Please enter amount for the '+option_number+' button');
					return tab_validation_status = true;
					
				}
				
				if(option_number == 'rent'){
					var access_day = pricing_field_selector.find('input.access_day').val();
					if(access_day == 0 || access_day == ''){
						dapwp_sweet_alert_msg('Please enter total number of days of access for the '+option_number+' button ');
						return tab_validation_status = true;
					}
				}
					
			});
			
			if(!tab_validation_status){
				var product_id = $jq("#productid").val();
				if(product_id == 0){
					dapwp_sweet_alert_msg('Please select a DAP product');
					return tab_validation_status = true;
				}
			}	
			
		return tab_validation_status;	
}

function dapwp_select_btn_options(){
	
	$jq('input[type="radio"][name="use_spc"]').on('click',function(){
		if($jq(this).val() == 'spc'){
			$jq('.spc_button_link').show();
			//$jq('.other_button_link').hide();
		}else{
			//$jq('.other_button_link').show();
			$jq('.spc_button_link').hide();
		}
	});
	
}



function dapwp_save_payper_post(obj , save_without_validation = 'no'){
	        
	     
	    
	
	    //General tab 
		var enable_pay_per_post = $jq("#enable_pay_per_post").prop('checked');
		if(enable_pay_per_post){
			enable_pay_per_post = 'Y';
		}else{
			enable_pay_per_post = 'N';
		}
		
		if((enable_pay_per_post == 'Y') && save_without_validation == 'yes' && dapwp_payper_post_all_tabs_Validation()){
			 return false;
		}	
		
		var enable_above_btn_msg = $jq('#enable_above_btn_msg').prop('checked');
		if(enable_above_btn_msg){
			enable_above_btn_msg = 'Y';
		}else{
			enable_above_btn_msg = 'N';
		}
		
		var payment_options_arr = [];
        $jq('.payment_options_outer input:checked').each(function(i){        
             payment_options_arr.push($jq(this).attr('data-payment-option'));
        });
       
        //var payment_options = payment_options_arr.join(", ");
        
        var id= $jq("#edit_id").val();
        var post_image = $jq(".post_image").val();
        var post_id = $jq("#dapwp_post_id").val();
        var product_id = $jq("#productid").val();
        
        // general
		var currency_code = $jq('select#currency_symbol option:selected').val();
		var currency_symbol = $jq('select#currency_symbol option:selected').attr('data-symbol');
		var payment_mode = $jq("input[type='radio'][name='payment_mode']:checked").val();
        
        var spc = $jq("input[name='use_spc']:checked").val();
        
        // pricing tab 
        var pricing_arr = {};
        var btn_config_arr = {};
        var btn_links_arr = {};
        var button_layout_option = '';
        $jq('.payment_options_outer input:checked').each(function(i){     
			 option_number = $jq(this).attr('data-payment-option');
			var price = $jq('.pricing_wrapper_'+option_number).find('input.price').val();
			var access_day = ' ';
			var link_id = 'buyId';
			if(option_number == 'rent'){
				link_id = 'rentId';
				 access_day = $jq('.pricing_wrapper_'+option_number).find('input.access_day').val();
				 
			}else if(option_number == 'buynow'){
				access_day = '9999';
			}else if(option_number == 'membership'){
				link_id = 'membershipId';
				access_day = '9999';
				price = 0;
			}
			
			
            pricing_arr[option_number] = { "price" :price, "access_day" : access_day};
            
            
            var buynow_above_text =  encodeURIComponent(tinymce.get('above_text_textarea').getContent());
            var buynow_text = $jq('.btn_text_'+option_number).val();
            
            btn_config_arr[option_number] = { "buynow_above_text" :buynow_above_text, "buynow_text" : buynow_text};  
            
            var other_buy_button_link_select = $jq('select[name="other_buy_button_link_select"]').val()  
            if(spc != 'spc'){
				var dapwp_website_url = $jq('#dapwp_website_url').val();
				var other_buy_button_link_select = dapwp_website_url+'/dap/paypalCoupon.php?cmd=_xclick&item_number='+product_id+'&currency_code='+currency_code;
			}
			
			if(option_number == 'membership'){
				other_buy_button_link_select = $jq('#membership_buynow_url').val();
				if ($jq('#membership_buynow_url').val().indexOf("?") != -1) {
					btn_links_arr[option_number] =  other_buy_button_link_select+'&'+link_id+'='+post_id+'&p_id='+product_id;
				}else{
					btn_links_arr[option_number] =  other_buy_button_link_select+'?'+link_id+'='+post_id+'&p_id='+product_id;	
				}
				
				
			}else{
				
				 if(spc != 'spc'){
					btn_links_arr[option_number] =  other_buy_button_link_select+'&buttonType='+option_number+'&postId='+post_id;
				}else{
					btn_links_arr[option_number] =  other_buy_button_link_select+'?'+link_id+'='+post_id+'&p_id='+product_id;
				}
			}
        });
        
       
       
        
        button_layout_option =  $jq('.dapwp_template_list').find('.selected').attr('data-temp');
        // message tab 
        var show_teaser_content = $jq("#show_teaser_content:checked").prop('checked');
		if(show_teaser_content){
			show_teaser_content = 'Y';
		}else{
			show_teaser_content = 'N';
		}
        
        //var teaser_content = $jq("#teaser_content").html();     
        var teaser_content = tinymce.get('teaser_content').getContent();
        var not_logged_in_msg = $jq("#not_logged_in_message").html();
        var no_access_msg = $jq("#no_access_msg").html();    
        
        // btn configuration tab 
         
       
        var other_buy_button_link_select = '';
        var spc_checkout_id = '';
        if(spc == 'spc'){
			var other_buy_button_link_select = $jq('select[name="other_buy_button_link_select"]').val();
			 var spc_checkout_id = $jq('select[name="other_buy_button_link_select"] option:selected').attr('checkout_id');
			
		}
		
		// landing page tab 
		
        var after_payment_action = $jq("#after_payment_action").val();
        var landing_url = '';
        if(after_payment_action == 'diff_page'){
			landing_url = $jq("#landing_url").val();
		}
		
		
        if(save_without_validation != 'yes' && after_payment_action == 'diff_page' && (landing_url == '')){
			 dapwp_sweet_alert_msg('Please enter URL of the landing page');
			 dapwp_show_tab_by_id('#landing_page');
			 return false;
		 }
		
		 pay_post_data = {
							'enable_pay_per_post':enable_pay_per_post,
							'payment_options_arr':payment_options_arr,
							'edit_id':id,
							'payment_mode':payment_mode,
							'currency_symbol':currency_symbol,
							'currency_code':currency_code,
							'post_image':post_image,
							'post_id':post_id,
							'product_id':product_id,
							'pricing_arr':pricing_arr,
							'btn_config_arr':btn_config_arr,
							'btn_links_arr':btn_links_arr,
							'show_teaser_content':show_teaser_content,
							'teaser_content':encodeURIComponent(teaser_content),
							'not_logged_in_msg':encodeURIComponent(not_logged_in_msg),
							'no_access_msg':encodeURIComponent(no_access_msg),
							'spc':spc, 
							'other_buy_button_link_select':other_buy_button_link_select,
							'after_payment_action':after_payment_action,
							'landing_url':landing_url,
							'button_layout_option':button_layout_option,
							'spc_checkout_id':spc_checkout_id,
							'enable_above_btn_msg':enable_above_btn_msg,
							};
        
         
		
		dapwp_show_loader();
		$jq.post(ajaxurl, {
			action: 'savePostMetaDataAjax',
			pay_post_data:pay_post_data
			
		
		}, function(response) {
			dapwp_hide_loader();
			response = $jq.parseJSON(response); 	
			
			if(response.success){
				dapwp_scroll_by_id('#dap_metabox');
				dapwp_sweet_alert_msg('Saved successfully');
			}
			if(response.error){
				dapwp_scroll_by_id('#dap_metabox');
				dapwp_sweet_alert_msg(response.error);
			}
			
			
			
		});	
	
	
	
	}


function dapwp_sweet_alert_msg(msg){
	dapwp_scroll_by_id('#dap_metabox');
	swal(msg);
}

/*****Image uploader******/
function dap_mediauploader(){
	
	var dap_metabox_img;	
	$jq(document).on('click','#myfile',function() {  
		
		if (dap_metabox_img) {
			dap_metabox_img.open();
			return;
		}
		dap_metabox_img = wp.media.frames.file_frame = wp.media({
			title: 'Choose Image',
			button: {
				text: 'Choose Image'
			},
			multiple: false
		});
		dap_metabox_img.on('select', function() {
			attachment = dap_metabox_img.state().get('selection').first().toJSON();	
			
			$jq('#dap_metabox .post_image').val(attachment.url);
			$jq('#dap_metabox .image_name').text(attachment.filename);
			$jq('#dap_metabox .image_name').show();
			
		});
		dap_metabox_img.open();
	});
	
	
}

/*****TinyMce editor******/
function dap_metabox_tiny_editor() {
	tinymce.init({
        selector: '.dap_metabox_tiny_editor',
        inline: true,
        height: 500,
        theme: 'modern',
        force_br_newlines: true,
        force_p_newlines: false,
        resize: "both",
        object_resizing: "img",
        forced_root_block: '',
        fontsize_formats: "8pt 9pt 10pt 11pt 12pt 13pt 14pt 15pt 16pt 17pt 18pt 19pt 20pt 22pt 24pt 26pt 30pt",
        theme_advanced_fonts: "Andale Mono=andale mono,times;" + "Arial=arial,helvetica,sans-serif;" + "Arial Black=arial black,avant garde;" + "Book Antiqua=book antiqua,palatino;" + "Comic Sans MS=comic sans ms,sans-serif;" + "Courier New=courier new,courier;" + "Georgia=georgia,palatino;" + "Helvetica=helvetica;" + "Impact=impact,chicago;" + "Symbol=symbol;" + "Tahoma=tahoma,arial,helvetica,sans-serif;" + "Terminal=terminal,monaco;" + "Times New Roman=times new roman,times;" + "Trebuchet MS=trebuchet ms,geneva;" + "Verdana=verdana,geneva;" + "Webdings=webdings;" + "Wingdings=wingdings,zapf dingbats",
       // plugins: ['advlist autolink lists link image charmap print preview hr anchor pagebreak', 'searchreplace wordcount visualblocks visualchars code fullscreen', 'insertdatetime media nonbreaking save table contextmenu directionality', 'emoticons template paste textcolor colorpicker textpattern imagetools'],     
        toolbar1: 'insertfile undo redo | styleselect | bold italic |  fontselect | fontsizeselect | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image',
        toolbar2: 'print preview media | forecolor backcolor emoticons | codesample',
        image_advtab: true,
        templates: [{
            title: 'Test template 1',
            content: 'Test 1'
        }, {
            title: 'Test template 2',
            content: 'Test 2'  
        }]
    });
}


function dapwp_after_payment_action(){
	$jq('#after_payment_action').on('change',function(){
		if($jq(this).val() == 'same_page'){
				$jq('.diff_page_wrapper').hide()
		}else{
			$jq('.diff_page_wrapper').show();
		}
	});
}

function dapwp_select_currency_symbol(){
	$jq('select#currency_symbol').on('change',function(){
		var data_symbol = $jq('select#currency_symbol option:selected').attr('data-symbol');
		$jq('.currency__symbol').text(data_symbol);
	});
}

function dapwp_select_payment_option(){
	$jq('.payment_options_outer input[type="checkbox"]').on('change',function(){
		var checkbox_checked_no = $jq('.payment_options_outer input[type="checkbox"]:checked').length;
		
		var payment_class = '.pricing_wrapper_'+$jq(this).attr('data-payment-option');
		var btn_link_class = '.btn_text_wrapper_'+$jq(this).attr('data-payment-option');
		var payment_name = $jq(this).attr('data-payment-option');
		if(checkbox_checked_no == 0){
			$jq('.pricing_section_outer').hide();
		}else{
			$jq('.pricing_section_outer').show();
		}
		
		if(this.checked){
			
			$jq(payment_class).show();
			$jq(btn_link_class).show();
			
			if(payment_name == 'membership'){
				$jq('.'+payment_name+'_buynow_url_wrapper').show();
			}
			
		}else{
			$jq(payment_class).hide();
			$jq(btn_link_class).hide();
			
			if(payment_name == 'membership'){
				$jq('.'+payment_name+'_buynow_url_wrapper').hide();
			}
		}
		
		
		
	});
	
}


function dapwp_enable_above_btn_msg(){
	$jq('#enable_above_btn_msg').on('click',function(){
		var enable_above_btn_msg =  $jq('#enable_above_btn_msg').prop('checked');
		if(enable_above_btn_msg){
			$jq('.above_btn_msg_wrapper').show();
		}else{
			$jq('.above_btn_msg_wrapper').hide();
		}
	});
}

function dapwp_goto_next_tab(tab_id){
	dapwp_scroll_by_id('#dap_metabox');
	$jq('.pay_per_post_left a[href="#'+tab_id+'"]').trigger('click');
}



function dapwp_show_tab_by_id(tab_id){
	
	dapwp_scroll_by_id('#dap_metabox');
	$jq('.pay_per_post_left a[href="'+tab_id+'"]').tab('show');
	
}


function dapwp_scroll_by_id(element_id){
	
	jQuery('html, body').animate({
		scrollTop: jQuery(element_id).offset().top
	}, 500);
}


/**Load page content if PPP is enabled****/


function pppGetFullPageContent(showLoader){
	dapwp_show_loader();
	var dapwp_post_id = $jq('#dapwp_post_id').val();
	$jq.post(ajaxurl, {
		action: 'pppGetFullPageContent',
		dapwp_post_id: dapwp_post_id,
	
	}, function(response) {
		dapwp_hide_loader();
		response = $jq.parseJSON(response); 	
		
		$jq('.pppAllTabsMainOuter').html(response);
		$jq('.enable_pay_per_post_wrapper').show();
		
		tinyMCE.remove('.dap_metabox_tiny_editor');
		tinyMCE.remove('textarea.dapwp_textare_tinymce');
		dap_metabox_tiny_editor(); 
		dapwp_tiny_editor_textarea();
		dap_mediauploader();
		dapwp_select_payment_option();
		dapwp_after_payment_action();
		dapwp_payper_post_tabs_Validation();
		dapwp_select_btn_options();
		//dapwp_select_button_layout_options();
		dapwp_select_currency_symbol();
		dapwp_enable_above_btn_msg();
		dapwp_enable_pay_per_post_option();
		dapwp_show_teaser_content_option();
		
		
		
	});		
}
