<?php
/**
 * Button X
 *
 * This file is used to register ajax related functionality of the plugin.
 *
 * @package Buttons X
 * @since 0.1
 */

// Make sure we don't expose any info if called directly
if ( !defined( 'ABSPATH' ) )
	exit;

if( !class_exists( 'BtnsxAjax' ) ) {
	class BtnsxAjax {

		private static $instance;

		/**
		 * Initiator
		 * @since 0.1
		 */
		public static function init() {
			return self::$instance;
		}

		/**
		 * Constructor
		 * @since 0.1
		 */
		public function __construct() {
			// add_action( 'wp_ajax_spotify_ajax', array( $this, 'spotify_ajax' ) );
			// add_action( 'admin_footer', array( $this, 'oauth_spotify' ) );
			add_action( 'wp_ajax_twitter_ajax', array( $this, 'twitter_ajax' ) );
			add_action( 'admin_footer', array( $this, 'oauth_twitter' ) );
			add_action( 'admin_footer', array( $this, 'oauth_facebook' ) );
			add_action( 'wp_ajax_linkedin_ajax', array( $this, 'linkedin_ajax' ) );
			add_action( 'admin_footer', array( $this, 'oauth_linkedin' ) );
			add_action( 'admin_footer', array( $this, 'oauth_instagram' ) );
			add_action( 'wp_ajax_cs_preview', array( $this, 'social_counters_ajax' ) );
			add_action( 'admin_footer', array( $this, 'social_counters' ) );
			add_action( 'wp_ajax_dual_button', array( $this, 'dual_button_ajax' ) );
			add_action( 'admin_footer', array( $this, 'dual_button' ) );
			add_action( 'wp_ajax_settings_save', array( $this, 'settings_save_ajax' ) );
			add_action( 'wp_ajax_settings_reset', array( $this, 'settings_reset_ajax' ) );
			add_action( 'admin_footer', array( $this, 'settings_jquery' ) );
			add_action( 'wp_ajax_reset_button', array( $this, 'reset_button_ajax' ) );
			add_action( 'admin_footer', array( $this, 'reset_button' ) );
		}

		/**
		 * Function to fetch spotify token
		 * @since  1.7.5
		 * @return string
		 */
		public function spotify_ajax() {
			// check for nonce
			check_ajax_referer( 'btnsx-oath-spotify', 'security' );

			global $btnsx_settings;

			$code = $_POST['code'];
			$client_id = isset( $btnsx_settings['social_counters_si_client_id'] ) && $btnsx_settings['social_counters_si_client_id'] != '' ? $btnsx_settings['social_counters_si_client_id'] : '';
			$client_secret = isset( $btnsx_settings['social_counters_si_client_secret'] ) && $btnsx_settings['social_counters_si_client_secret'] != '' ? $btnsx_settings['social_counters_si_client_secret'] : '';
			$credentials = $client_id . ':' . $client_secret;
			$token = base64_encode( $credentials );

			$redirect_uri = isset( $btnsx_settings['social_counters_si_redirect_uri'] ) && $btnsx_settings['social_counters_si_redirect_uri'] != '' ? $btnsx_settings['social_counters_si_redirect_uri'] : '';

			// http post arguments
            $args = array(
                'method' => 'POST',
                'headers' => array(
                    'Authorization' => 'Basic ' . $token
                ),
                'body' => array( 'grant_type' => 'authorization_code', 'code' => $code, 'redirect_uri' => $redirect_uri )
            );
 
            // add_filter('https_ssl_verify', '__return_false');
            $data = wp_remote_post('https://accounts.spotify.com/api/token', $args);

            $keys = json_decode(wp_remote_retrieve_body($data));
			
			echo $keys->access_token;

		    wp_die();
		}

		/**
		 * Function to output social counters
		 * @since  1.7.5
		 * @return string
		 */
		public function oauth_spotify() { 
			$screen =  get_current_screen();
			if( $screen->id == 'buttons-x_page_buttons-x-settings' ){
				$si_nonce = wp_create_nonce( 'btnsx-oath-spotify' );
				global $btnsx_settings;
				$si_client_id = isset( $btnsx_settings['social_counters_si_client_id'] ) && $btnsx_settings['social_counters_si_client_id'] != '' ? $btnsx_settings['social_counters_si_client_id'] : '';
				$si_redirect_uri = isset( $btnsx_settings['social_counters_si_redirect_uri'] ) && $btnsx_settings['social_counters_si_redirect_uri'] != '' ? $btnsx_settings['social_counters_si_redirect_uri'] : '';
				?>
				<script type="text/javascript" >
				jQuery(document).ready(function($){
					var CLIENTID = '<?php echo $si_client_id; ?>';
					var REDIRECTURI = '<?php echo esc_url( $si_redirect_uri ); ?>';
					var _url = 'https://accounts.spotify.com/en/authorize?response_type=code&client_id='+CLIENTID+'&redirect_uri='+REDIRECTURI+'&state=<?php echo $si_nonce; ?>';
					function siLogin() {
			            var win         =   window.open(_url, 'sioauthwindow', 'width=800, height=600');
			            var pollTimer   =   window.setInterval(function() { 
			                try {
			                	if (win.document.URL.indexOf(REDIRECTURI) != -1) {
			                        window.clearInterval(pollTimer);
			                        var url = win.document.URL;
			                        var acToken = url.replace(REDIRECTURI+'?code=','');
			                        acToken = acToken.replace('&state=<?php echo $si_nonce; ?>','');
			                        win.close();
			                        var data = {
										'action': 'spotify_ajax',
										'security': '<?php echo $si_nonce; ?>',
										'code': acToken
									};
			                        $.ajax({
						                url: ajaxurl,
						                method: 'POST',
						                data: data
						            }).success(function(r){
					                    $('#social_counters_si_access_token').val(r);
						            });
			                    }
			                } catch(e) {
			                	// console.log(e);
			                }
			            }, 500);
			        }
					$('#spotify-oauth').on('click',function(e){
						e.preventDefault();
						siLogin();
					});
		    	});
				</script>
				<?php
			}
		}

		/**
		 * Function to fetch linkedin token
		 * @since  1.7.5
		 * @return string
		 */
		public function twitter_ajax() {
			// check for nonce
			check_ajax_referer( 'btnsx-oath-twitter', 'security' );

			global $btnsx_settings;

			$consumer_key = isset( $btnsx_settings['social_counters_tw_consumer_key'] ) && $btnsx_settings['social_counters_tw_consumer_key'] != '' ? $btnsx_settings['social_counters_tw_consumer_key'] : '';
			$consumer_secret = isset( $btnsx_settings['social_counters_tw_consumer_secret'] ) && $btnsx_settings['social_counters_tw_consumer_secret'] != '' ? $btnsx_settings['social_counters_tw_consumer_secret'] : '';
			$credentials = $consumer_key . ':' . $consumer_secret;
			$token = base64_encode( $credentials );

			// http post arguments
            $args = array(
                'method' => 'POST',
                'httpversion' => '1.1',
                'blocking' => true,
                'headers' => array(
                    'Authorization' => 'Basic ' . $token,
                    'Content-Type' => 'application/x-www-form-urlencoded;charset=UTF-8'
                ),
                'body' => array( 'grant_type' => 'client_credentials' )
            );
 
            // add_filter('https_ssl_verify', '__return_false');
            $data = wp_remote_post('https://api.twitter.com/oauth2/token', $args);

            $keys = json_decode(wp_remote_retrieve_body($data));
			
			echo $keys->access_token;

		    wp_die();
		}

		/**
		 * Function to output social counters
		 * @since  1.7.5
		 * @return string
		 */
		public function oauth_twitter() { 
			$screen =  get_current_screen();
			if( $screen->id == 'buttons-x_page_buttons-x-settings' ){
				$tw_nonce = wp_create_nonce( 'btnsx-oath-twitter' );
				?>
				<script type="text/javascript" >
				jQuery(document).ready(function($){
					$('#twitter-oauth').on('click',function(e){
						e.preventDefault();
						var data = {
							'action': 'twitter_ajax',
							'security': '<?php echo $tw_nonce; ?>'
						};
			            $.ajax({
			                url: ajaxurl,
			                data: data
			            }).success(function(r){
		                    $('#social_counters_tw_access_token').val(r);
		                    $('#twitter-oauth').removeClass('btnsx-sc-authenticate btnsx-sc-authenticated').addClass('btnsx-sc-authenticated');
				            $('#twitter-oauth').text('<?php _e("Authenticated, Please save settings!","btnsx"); ?>');
			            });
					});
		    	});
				</script>
				<?php
			}
		}

		/**
		 * Function to fetch linkedin token
		 * @since  1.7.5
		 * @return string
		 */
		public function linkedin_ajax() {
			// check for nonce
			check_ajax_referer( 'btnsx-oath-linkedin', 'security' );

			$url = $_POST['url'];
			$curl = curl_init();
			curl_setopt($curl, CURLOPT_URL, $url);
			curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
			curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-type: application/x-www-form-urlencoded'));
			$data = curl_exec($curl);
			curl_close($curl);

			// $data = json_decode($data);

			// echo $data['access_token'];
			
			echo $data;

		    wp_die();
		}

		/**
		 * Function to output social counters
		 * @since  1.7.5
		 * @return string
		 */
		public function oauth_linkedin() { 
			$screen =  get_current_screen();
			if( $screen->id == 'buttons-x_page_buttons-x-settings' ){
				$li_nonce = wp_create_nonce( 'btnsx-oath-linkedin' );
				global $btnsx_settings;
				$li_client_id = isset( $btnsx_settings['social_counters_li_client_id'] ) && $btnsx_settings['social_counters_li_client_id'] != '' ? $btnsx_settings['social_counters_li_client_id'] : '';
				$li_client_secret = isset( $btnsx_settings['social_counters_li_client_secret'] ) && $btnsx_settings['social_counters_li_client_secret'] != '' ? $btnsx_settings['social_counters_li_client_secret'] : '';
				$li_redirect_uri = isset( $btnsx_settings['social_counters_li_redirect_uri'] ) && $btnsx_settings['social_counters_li_redirect_uri'] != '' ? $btnsx_settings['social_counters_li_redirect_uri'] : '';
				?>
				<script type="text/javascript" >
				jQuery(document).ready(function($){
					var CLIENTID = '<?php echo $li_client_id; ?>';
					var CLIENTSEC = '<?php echo $li_client_secret; ?>';
					var REDIRECTURI = '<?php echo $li_redirect_uri; ?>';
					var _url = 'https://www.linkedin.com/uas/oauth2/authorization?response_type=code&client_id='+CLIENTID+'&redirect_uri='+REDIRECTURI+'&state=<?php echo $li_nonce; ?>';
					function liLogin( btn ) {
			            var win         =   window.open(_url, 'lioauthwindow', 'width=800, height=600');
			            var pollTimer   =   window.setInterval(function() { 
			                try {
			                	if (win.document.URL.indexOf(REDIRECTURI) != -1) {
			                        window.clearInterval(pollTimer);
			                        var url = win.document.URL;
			                        acToken = url.replace(REDIRECTURI+'&code=','');
			                        acToken = acToken.replace('&state=<?php echo $li_nonce; ?>','');
			                        win.close();
			                        var VALIDURL = 'https://www.linkedin.com/uas/oauth2/accessToken?grant_type=authorization_code&code='+acToken+'&redirect_uri='+REDIRECTURI+'&client_id='+CLIENTID+'&client_secret='+CLIENTSEC;
			                        var data = {
										'action': 'linkedin_ajax',
										'security': '<?php echo $li_nonce; ?>',
										'url': VALIDURL
									};
			                        $.ajax({
						                url: ajaxurl,
						                method: 'POST',
						                data: data,
						                dataType: 'json'
						            }).success(function(r){
						            	// console.log(r);
					                    $('#social_counters_li_access_token').val(r.access_token);
					                    btn.removeClass('btnsx-sc-authenticate btnsx-sc-authenticated').addClass('btnsx-sc-authenticated');
				            			btn.text('<?php _e("Authenticated, Please save settings!","btnsx"); ?>');
						            }).error(function(e){
						            	console.log(e);
						            });
			                    }
			                } catch(e) {
			                	// console.log(e);
			                }
			            }, 500);
			        }
					$('#linkedin-oauth').on('click',function(e){
						e.preventDefault();
						liLogin( $(this) );
					});
		    	});
				</script>
				<?php
			}
		}

		/**
		 * Function to output social counters
		 * @since  1.7.5
		 * @return string
		 */
		public function oauth_instagram() { 
			$screen =  get_current_screen();
			if( $screen->id == 'buttons-x_page_buttons-x-settings' ){
				$ig_nonce = wp_create_nonce( 'btnsx-oath-instagram' );
				global $btnsx_settings;
				$ig_client_id = isset( $btnsx_settings['social_counters_ig_client_id'] ) && $btnsx_settings['social_counters_ig_client_id'] != '' ? $btnsx_settings['social_counters_ig_client_id'] : '';
				$ig_redirect_uri = isset( $btnsx_settings['social_counters_ig_redirect_uri'] ) && $btnsx_settings['social_counters_ig_redirect_uri'] != '' ? $btnsx_settings['social_counters_ig_redirect_uri'] : '';
				?>
				<script type="text/javascript" >
				jQuery(document).ready(function($){
					var CLIENTID = '<?php echo $ig_client_id; ?>';
					var REDIRECTURI = '<?php echo $ig_redirect_uri; ?>';
					var _url = 'https://instagram.com/oauth/authorize/?client_id='+CLIENTID+'&amp;redirect_uri='+REDIRECTURI+'&amp;response_type=token';
					function igLogin( btn ) {
			            var win         =   window.open(_url, 'igoauthwindow', 'width=800, height=600');
			            var pollTimer   =   window.setInterval(function() { 
			                try {
			                	if (win.document.URL.indexOf(REDIRECTURI) != -1) {
			                        window.clearInterval(pollTimer);
			                        var url =   win.document.URL;
			                        acToken =   igGup(url, 'access_token')
			                    	// tokenType = gup(url, 'token_type');
			                    	// expiresIn = gup(url, 'expires_in');
			                        win.close();
			                        $('#social_counters_ig_access_token').val(acToken);
			                        btn.removeClass('btnsx-sc-authenticate btnsx-sc-authenticated').addClass('btnsx-sc-authenticated');
				                    btn.text('<?php _e("Authenticated, Please save settings!","btnsx"); ?>');
			                    }
			                } catch(e) {
			                	// console.log(e);
			                }
			            }, 500);
			        }
			        function igGup(url, name) {
			            name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
			            var regexS = "[\\#&]"+name+"=([^&#]*)";
			            var regex = new RegExp( regexS );
			            var results = regex.exec( url );
			            if( results == null )
			                return "";
			            else
			                return results[1];
			        }
					$('#instagram-oauth').on('click',function(e){
						e.preventDefault();
						igLogin( $(this) );
					});
		    	});
				</script>
				<?php
			}
		}

		/**
		 * Function to output social counters
		 * @since  1.7.5
		 * @return string
		 */
		public function oauth_facebook() { 
			$screen =  get_current_screen();
			if( $screen->id == 'buttons-x_page_buttons-x-settings' ){
				$ig_nonce = wp_create_nonce( 'btnsx-oath-facebook' );
				global $btnsx_settings;
				$fb_app_id = isset( $btnsx_settings['social_counters_fb_app_id'] ) && $btnsx_settings['social_counters_fb_app_id'] != '' ? $btnsx_settings['social_counters_fb_app_id'] : '';
				$fb_app_secret = isset( $btnsx_settings['social_counters_fb_app_secret'] ) && $btnsx_settings['social_counters_fb_app_secret'] != '' ? $btnsx_settings['social_counters_fb_app_secret'] : '';
				?>
				<script type="text/javascript" >
				jQuery(document).ready(function($){
					var CLIENTID = '<?php echo $fb_app_id; ?>';
					var CLIENTSEC = '<?php echo $fb_app_secret; ?>';
					var _url = 'https://graph.facebook.com/oauth/access_token?client_id='+CLIENTID+'&client_secret='+CLIENTSEC+'&grant_type=client_credentials&scope=publish_actions';
					function fbLogin( btn ) {
			            var win         =   window.open(_url, 'fboauthwindow', 'width=800, height=600');
			            var pollTimer   =   window.setInterval(function() { 
			                try {
			                	win.close();
			                	$.ajax({
					                url: _url,
					                method: 'GET',
					            }).success(function(r){
					            	r = r.replace('access_token=','');
				                    $('#social_counters_fb_access_token').val(r);
				                    btn.removeClass('btnsx-sc-authenticate btnsx-sc-authenticated').addClass('btnsx-sc-authenticated');
				                    btn.text('<?php _e("Authenticated, Please save settings!","btnsx"); ?>');
					            });
					            window.clearInterval(pollTimer);
			                } catch(e) {
			                	btn.text('<?php _e("Something went wrong! Please reload the page & try again.","btnsx"); ?>');
			                	// console.log(e);
			                }
			            }, 500);
			        }
					$('#facebook-oauth').on('click',function(e){
						e.preventDefault();
						fbLogin( $(this) );
					});
		    	});
				</script>
				<?php
			}
		}

		/**
		 * Function to output counters using ajax
		 * @since  1.7.5
		 * @return string
		 */
		public function social_counters_ajax() {
			// check for nonce
			check_ajax_referer( 'btnsx-cs', 'security' );

			$id = $_POST['id'];
			$theme = $_POST['theme'];
			if( $_POST['order'] != '' ){
				if( is_array($_POST['order']) ){
					$order = implode( ',', $_POST['order'] );
				}else{
					$order = $_POST['order'];
				}
			}else{
				$order = '';
			}

		    echo do_shortcode('[btnsx_social_counter id="'.$id.'" order="'.$order.'" theme="'.$theme.'"]');

		    wp_die();
		}

		/**
		 * Function to output social counters
		 * @since  1.7.5
		 * @return string
		 */
		public function social_counters() { 
			$screen =  get_current_screen();
			if( $screen->id == 'buttons-x-cs' ){
				$cs_nonce = wp_create_nonce( 'btnsx-cs' );
				?>
				<script type="text/javascript" >
				jQuery(document).ready(function($){
					var csAjax = function(){
						var data = {
							'action': 'cs_preview',
							'security': '<?php echo $cs_nonce; ?>',
							'id': $('#btnsx_opt_id').val(),
							'order': $('#btnsx_opt_order').val(),
							'theme': $('#btnsx_opt_theme').val()
						};
						$.ajax({
							url: ajaxurl,
							method: 'POST',
							data: data,
							beforeSend: function(){
								$('.btnsx-social-counter').hide();
								$('#btnsx-preview-loader').fadeIn('fast');
							}
						}).success(function( d ){
							$('#btnsx-preview-loader').hide();
							$('.btnsx-social-counter').remove();
							$('#btnsx-preview-container').append(d);
							$('.btnsx-social-counter').fadeIn();
						});
					}
					$('#btnsx-tabs-social-counters-0-0 ul .row').sortable({
				   		placeholder: 'ui-state-highlight',
				   		create: function (event, ui) {
				   			var r = $(this).sortable('toArray');
				   			// remove unwanted array values
				            for (var k in r) {
							    if (r[k] == 'btnsx_opt_id') {
							       r.splice(k, 1);
							    }
							}
							// strip out unwanted string in each array value
				            var key;
				            for( var i=0; i < r.length; i++ ) {
				            	key = r[i].replace('btnsx_opt_', '').replace('_container','');
				            	r[i] = key + ':' + $('#btnsx_opt_'+key).val();
				            }
				            $('#btnsx_opt_order').val(r);
				   		},
				   		update: function (event, ui) {
				            var r = $(this).sortable('toArray');
				            // remove unwanted array values
				            for (var k in r) {
							    if (r[k] == 'btnsx_opt_id') {
							       r.splice(k, 1);
							    }
							}
							// strip out unwanted string in each array value
							var key;
				            for( var i=0; i < r.length; i++ ) {
				            	key = r[i].replace('btnsx_opt_', '').replace('_container','');
				            	r[i] = key + ':' + $('#btnsx_opt_'+key).val();
				            }
				            $('#btnsx_opt_order').val(r);
					        // console.log(r);
					        csAjax();
				        }
				    });
		    		$('#btnsx-tabs-social-counters-0-0 ul .row').disableSelection();
		    		var keys = [], socialId, status;
	    			$('.btnsx-checkbox-sortable').on( 'change', function(){
	    				$('#btnsx-tabs-social-counters-0-0 ul .row > .col').each(function(){
	    					socialId = $(this).attr('id').replace('btnsx_opt_', '').replace('_container','');
	    					status = $(this).find('input[type=checkbox]').val();
	    					keys.push(socialId+':'+status);
	    				});
			            $('#btnsx_opt_order').val(keys);
	    				csAjax();
	    				keys = []; // reset
	    			});
	    			$('#btnsx_opt_theme').on( 'change', function(){
	    				csAjax();
	    			});
		    		csAjax();
		    	});
				</script>
				<?php
			}
		}

		/**
		 * Function to reset button using ajax
		 * @since  1.2
		 * @return string
		 */
		public function dual_button_ajax() {
			// check for nonce
			check_ajax_referer( 'btnsx-dual-button', 'security' );

			$btn_title = $_POST['button_title'];
			$class = isset( $_POST['button_position'] ) ? $_POST['button_position'] : '';

			if( $class == 1 ) {
				$class = 'btnsx-dual-first';
			} elseif( $class == 2 ) {
				$class = 'btnsx-dual-second';
			}

			$btn = get_page_by_title( $btn_title, 'OBJECT', 'buttons-x' );
			if( is_object($btn) ){
				$btn_id = $btn->ID;
			} else {
				$btn_id = '';
			}

			$atts = array(
				'id="'.$btn_id.'"',
				'class="'.$class.'"',
				'wrap_center="0"',
				'container="0"',
				'css_inline="1"'
			);

			// Filter - Dual Button Preview Short Code Args
				$btn_dual_preview_args_filter = apply_filters( 'btnsx_dual_button_preview_args', array() );
				$btn_dual_preview_args_filter_as_string = '';
				foreach ( $btn_dual_preview_args_filter as $key => $value ) {
					if( count($btn_dual_preview_args_filter) == 1 ){
						$btn_dual_preview_args_filter_as_string .= $value;
					} else {
						$btn_dual_preview_args_filter_as_string .= implode( ' ', $value );
					}
				}

			$sc = '[btnsx id="'.$btn_id.'" class="'.$class.'" wrap_center="0" container="0" css_inline="1" '.$btn_dual_preview_args_filter_as_string.']';

			echo do_shortcode($sc);

			wp_die();
		}
 		
		/**
		 * Function to reset a button
		 * @since  0.1
		 * @return string
		 */
		public function dual_button() {
			// create nonce
			$dual_button_nonce = wp_create_nonce( 'btnsx-dual-button' );
			$screen = get_current_screen();
		    if ( $screen->id == 'buttons-x-dual' ) {
				?>
			    <script type="text/javascript">
					jQuery( document ).ready( function( $ ) {
						var dualContainer = $('#btnsx-dual-preview-container');
						dualContainer.hide();
						var previewLoader = $('#btnsx-preview-loader');
						// Active tab
							var tab = $( '#btnsx_opt_dual_tab' ).val();
							$('#'+tab).click();
						// Save active tab
							$( '#btnsx-tabs' ).find('li').on('click',function(){
								$( '#btnsx_opt_dual_tab' ).val( $(this).attr('id') );
							});
						var dcDisplay = function(){
							animations();
							tooltip();
							var padTop1 = $('#btnsx_opt_dual_button_first_padding_top');
							var padTop1Val = padTop1.val();
							if( padTop1Val != null ){
								$('.btnsx-dual-first').css('padding-top',padTop1Val+'px');
							}
							var padBottom1 = $('#btnsx_opt_dual_button_first_padding_bottom');
							var padBottom1Val = padBottom1.val();
							if( padBottom1Val != null ){
								$('.btnsx-dual-first').css('padding-bottom',padBottom1Val+'px');
							}
							var padLeft1 = $('#btnsx_opt_dual_button_first_padding_left');
							var padLeft1Val = padLeft1.val();
							if( padLeft1Val != null ){
								$('.btnsx-dual-first').css('padding-left',padLeft1Val+'px');
							}
							var padRight1 = $('#btnsx_opt_dual_button_first_padding_right');
							var padRight1Val = padRight1.val();
							if( padRight1Val != null ){
								$('.btnsx-dual-first').css('padding-right',padRight1Val+'px');
							}
							var padTop2 = $('#btnsx_opt_dual_button_second_padding_top');
							var padTop2Val = padTop2.val();
							if( padTop2Val != null ){
								$('.btnsx-dual-second').css('padding-top',padTop2Val+'px');
							}
							var padBottom2 = $('#btnsx_opt_dual_button_second_padding_bottom');
							var padBottom2Val = padBottom2.val();
							if( padBottom2Val != null ){
								$('.btnsx-dual-second').css('padding-bottom',padBottom2Val+'px');
							}
							var padLeft2 = $('#btnsx_opt_dual_button_second_padding_left');
							var padLeft2Val = padLeft2.val();
							if( padLeft2Val != null ){
								$('.btnsx-dual-second').css('padding-left',padLeft2Val+'px');
							}
							var padRight2 = $('#btnsx_opt_dual_button_second_padding_right');
							var padRight2Val = padRight2.val();
							if( padRight2Val != null ){
								$('.btnsx-dual-second').css('padding-right',padRight2Val+'px');
							}
						}
						var changeDisplay = function(){
							previewLoader.hide();
							dualContainer.fadeIn();
						}
						var btnResponsive = function(){
							// Responsive
							var previewArea = $('#btnsx-preview .inside');
							var previewAreaWidth = previewArea.width();
							var firstBtnWidth = $('.btnsx-dual-first').outerWidth();
							var secondBtnWidth = $('.btnsx-dual-second').outerWidth();
							var btnWidth = firstBtnWidth + secondBtnWidth;
							if( btnWidth > previewAreaWidth ){
								dualContainer.addClass('btnsx-dual-full-width');
							}
						}

						// Buttons
							var button = function( d1, d2, d3, d4 ){
								if( d4 == '1' ){
					  				$('#btnsx-dual-divider').prevAll('style').remove();
						  		} else {
						  			$('#btnsx-dual-divider').nextAll('style').remove();
						  		}
					  			$('#btnsx-dual-preview-container').find(d1).replaceWith(d3);
					  			$('.btnsx-btn').removeClass('btnsx-btn-block');
					  			if( d4 == '1' ){
						  			$(d2).css({
						  				'border-top-right-radius': '0',
						  				'border-bottom-right-radius': '0',
						  			});
						  		} else {
						  			$(d2).css({
						  				'border-top-left-radius': '0',
						  				'border-bottom-left-radius': '0',
						  				'border-left-width': '0'
						  			});
						  		}
						  		btnResponsive();
					  			$(d2).fadeIn();
							}
							var btnsxFirstButton = function() {
								dualContainer.hide();
								previewLoader.show();
								var btn_title = $( '#btnsx_opt_dual_button_first' ).val();
								var data = {
									'action'	: 'dual_button',							// wp ajax action
									'security'	: '<?php echo $dual_button_nonce; ?>',		// nonce value created earlier
									'button_title'	: btn_title,	// fetch form data
									'button_position'	: 1
								};
								// fire ajax
							  	$.post( ajaxurl, data, function( response ) {
							  		// console.log(response);
							  		if( data.button_title != null ){
								  		// if nonce fails then not authorized else settings saved
								  		if( response === '-1' ){
									  		// do nothing
									  		alert('Something went wrong.. Try again!');
								  		} else {
								  			var id = $('#btnsx-preview').find('.btnsx-dual-first').attr('id');
								  			button( '.btnsx-dual-first', '#'+id, response, data.button_position );
								  			window.setTimeout( dcDisplay, 0 );
								  			window.setTimeout( changeDisplay, 0 );
								  		}
								  	}
							  	});
							};
							btnsxFirstButton();
							var btnsxSecondButton = function() {
								dualContainer.hide();
								previewLoader.show();
								var btn_title = $( '#btnsx_opt_dual_button_second' ).val();
								var data = {
									'action'			: 'dual_button',							// wp ajax action
									'security'			: '<?php echo $dual_button_nonce; ?>',		// nonce value created earlier
									'button_title'		: btn_title,	// fetch form data
									'button_position'	: 2
								};
								// fire ajax
							  	$.post( ajaxurl, data, function( response ) {
							  		if( data.button_title != null ){
							  			// if nonce fails then not authorized else settings saved
								  		if( response === '-1' ){
									  		// do nothing
									  		alert('Something went wrong.. Try again!');
								  		} else {
								  			var id = $('#btnsx-preview').find('.btnsx-dual-second').attr('id');
								  			button( '.btnsx-dual-second', '#'+id, response, data.button_position );
								  			window.setTimeout( dcDisplay, 0 );
								  			window.setTimeout( changeDisplay, 0 );
								  		}
								  	}
							  	});
							};
							btnsxSecondButton();
							$( '#btnsx_opt_dual_button_first' ).on( 'change', function( ev ) {
								ev.preventDefault();
							  	btnsxFirstButton();
							});
							$( '#btnsx_opt_dual_button_second' ).on( 'change', function( ev ) {
								ev.preventDefault();
							  	btnsxSecondButton();
							});

						// Button Full Width
							var fullWidthOpt = $('#btnsx_opt_dual_button_full_width');
							var fullWidthVal = $('#btnsx_opt_dual_button_full_width').val();
							var makeFullWidth = function( val ){
								if( val == '1' ){
									dualContainer.addClass('btnsx-dual-full-width');
									dualContainer.css('display','block');
								} else {
									dualContainer.removeClass('btnsx-dual-full-width');
								}
							}
							makeFullWidth(fullWidthVal);
							fullWidthOpt.on('change', function(){
								var val = $(this).val();
								makeFullWidth(val);
							});

						// Divider
							var divider = $('#btnsx-dual-divider');
							var enDivider = $('#btnsx_opt_dual_divider_enable');
							var enDividerVal = $('#btnsx_opt_dual_divider_enable').val();
							var showDivider = function( val ){
								if( val == '1' ){
									divider.css('display','inline-block');
								} else {
									divider.hide();
								}
							}
							showDivider(enDividerVal);
							enDivider.on('change', function(){
								var val = $(this).val();
								showDivider(val);
							});
							// Text
								var text = function( v ) {
									divider.text( v.val() );
								}
								var textOpt = $('#btnsx_opt_dual_divider_text');
								text(textOpt);
								textOpt.on('propertychange keyup input',function(){
									text($(this));
								});
							// Text Size
								var textSize = function( v ) {
									divider.css( 'font-size', v.val() + 'px' );
								}
								var textSizeOpt = $('#btnsx_opt_dual_divider_text_size');
								textSize(textSizeOpt);
								textSizeOpt.on('propertychange keyup input',function(){
									textSize($(this));
								});
							// Width
								var width = function( v ) {
									divider.css( 'width', v.val() + 'px' );
								}
								var widthOpt = $('#btnsx_opt_dual_divider_width');
								width(widthOpt);
								widthOpt.on('propertychange keyup input',function(){
									width($(this));
								});
							// height
								var height = function( v ) {
									divider.css( 'height', v.val() + 'px' );
								}
								var heightOpt = $('#btnsx_opt_dual_divider_height');
								height(heightOpt);
								heightOpt.on('propertychange keyup input',function(){
									height($(this));
								});
							// Position - Margin Left
								var posLeft = function( v ) {
									divider.css( 'margin-left', v.val() + 'px' );
								}
								var posLeftOpt = $('#btnsx_opt_dual_divider_position_left');
								posLeft(posLeftOpt);
								posLeftOpt.on('propertychange keyup input',function(){
									posLeft($(this));
								});
							// Position - Top
								var posTop = function( v ) {
									divider.css( 'top', v.val() + 'px' );
								}
								var posTopOpt = $('#btnsx_opt_dual_divider_position_top');
								posTop(posTopOpt);
								posTopOpt.on('propertychange keyup input',function(){
									posTop($(this));
								});
							// Position - Text Position
								var posText = function( v ) {
									divider.css( 'line-height', v.val() );
								}
								var posTextOpt = $('#btnsx_opt_dual_divider_text_position');
								posText(posTextOpt);
								posTextOpt.on('propertychange keyup input',function(){
									posText($(this));
								});
							// Border - Size
								var borderSize = function( v ) {
									divider.css( 'border-width', v.val() + 'px' );
								}
								var borderSizeOpt = $('#btnsx_opt_dual_divider_border_size');
								borderSize(borderSizeOpt);
								borderSizeOpt.on('propertychange keyup input',function(){
									borderSize($(this));
								});
							// Border - Style
								var borderStyle = function( v ) {
									divider.css( 'border-style', v.val() );
								}
								var borderStyleOpt = $('#btnsx_opt_dual_divider_border_style');
								borderStyle(borderStyleOpt);
								borderStyleOpt.on('change',function(){
									borderStyle($(this));
								});
							// Border - Color
								var borderColorOpt = $('#btnsx_opt_dual_divider_border_color');
								borderColorOpt.btnsxRGBA({
									targetElement: divider,
									css: 'border-color'
								});
								var borderColor = function( v ){
									divider.css('border-color',v.val());
									borderColorOpt.wpColorPicker('color', v.val());
								}
								borderColor( borderColorOpt );
							// Border - Radius
								var borderRadiusTopLeft = function( v ) {
									divider.css( 'border-top-left-radius', v.val() + 'px' );
								}
								var borderRadiusTopRight = function( v ) {
									divider.css( 'border-top-right-radius', v.val() + 'px' );
								}
								var borderRadiusBottomLeft = function( v ) {
									divider.css( 'border-bottom-left-radius', v.val() + 'px' );
								}
								var borderRadiusBottomRight = function( v ) {
									divider.css( 'border-bottom-right-radius', v.val() + 'px' );
								}
								var borderRadiusAllOpt				= $('#btnsx_opt_dual_divider_border_radius_all');
								var borderRadiusTopLeftOpt 			= $('#btnsx_opt_dual_divider_border_radius_top_left');
								borderRadiusTopLeft(borderRadiusTopLeftOpt);
								var borderRadiusTopRightOpt 		= $('#btnsx_opt_dual_divider_border_radius_top_right');
								borderRadiusTopRight(borderRadiusTopRightOpt);
								var borderRadiusBottomLeftOpt 		= $('#btnsx_opt_dual_divider_border_radius_bottom_left');
								borderRadiusBottomLeft(borderRadiusBottomLeftOpt);
								var borderRadiusBottomRightOpt 		= $('#btnsx_opt_dual_divider_border_radius_bottom_right');
								borderRadiusBottomRight(borderRadiusBottomRightOpt);
								var borderRadius = function( v ) {
									divider.css( 'border-radius', v.val() + 'px' );
									borderRadiusTopLeftOpt.val(v.val());
									borderRadiusTopRightOpt.val(v.val());
									borderRadiusBottomLeftOpt.val(v.val());
									borderRadiusBottomRightOpt.val(v.val());
								}
								borderRadiusAllOpt.on('propertychange keyup input',function(){
									borderRadius($(this));
								});
								borderRadiusTopLeftOpt.on('propertychange keyup input',function(){
									borderRadiusTopLeft($(this));
								});
								borderRadiusTopRightOpt.on('propertychange keyup input',function(){
									borderRadiusTopRight($(this));
								});
								borderRadiusBottomLeftOpt.on('propertychange keyup input',function(){
									borderRadiusBottomLeft($(this));
								});
								borderRadiusBottomRightOpt.on('propertychange keyup input',function(){
									borderRadiusBottomRight($(this));
								});
							// Background Color
								var backgroundColorOpt = $('#btnsx_opt_dual_divider_background_color');
								backgroundColorOpt.btnsxRGBA({
									targetElement: divider,
									css: 'background-color'
								});
								var backgroundColor = function( v ){
									divider.css('background-color',v.val());
									backgroundColorOpt.wpColorPicker('color', v.val());
								}
								backgroundColor( backgroundColorOpt );
							// Text Color
								var textColorOpt = $('#btnsx_opt_dual_divider_text_color');
								textColorOpt.btnsxRGBA({
									targetElement: divider,
									css: 'color'
								});
								var textColor = function( v ){
									divider.css('color',v.val());
									textColorOpt.wpColorPicker('color', v.val());
								}
								textColor( textColorOpt );
							// Divider Style
								var dividerStyleOpt = $('#btnsx_opt_dual_divider_style');
								var dividerStyle = function( v ){
									var val = v.val();
									switch( val ){
										case 'style_1':
											// set values
												textSizeOpt.val('11');
												widthOpt.val('34');
												heightOpt.val('34');
												posLeftOpt.val('-18');
												posTopOpt.val('11');
												posTextOpt.val('3.1');
												borderSizeOpt.val('0');
												borderStyleOpt.val('none');
												borderColorOpt.val('#fff');
												borderRadiusTopLeftOpt.val('35');
												borderRadiusTopRightOpt.val('35');
												borderRadiusBottomLeftOpt.val('35');
												borderRadiusBottomRightOpt.val('35');
												backgroundColorOpt.val('#fff');
												textColorOpt.val('#555');
											// trigger change
												textSize(textSizeOpt);
												width(widthOpt);
												height(heightOpt);
												posLeft(posLeftOpt);
												posTop(posTopOpt);
												posText(posTextOpt);
												borderSize(borderSizeOpt);
												borderStyle(borderStyleOpt);
												borderColor(borderColorOpt);
												borderRadiusTopLeft(borderRadiusTopLeftOpt);
												borderRadiusTopRight(borderRadiusTopRightOpt);
												borderRadiusBottomLeft(borderRadiusBottomLeftOpt);
												borderRadiusBottomRight(borderRadiusBottomRightOpt);
												backgroundColor(backgroundColorOpt);
												textColor(textColorOpt);
											break;
        								case 'style_2':
											// set values
												textSizeOpt.val('11');
												widthOpt.val('34');
												heightOpt.val('34');
												posLeftOpt.val('-18');
												posTopOpt.val('11');
												posTextOpt.val('2.9');
												borderSizeOpt.val('1');
												borderStyleOpt.val('solid');
												borderColorOpt.val('#9b9b9b');
												borderRadiusTopLeftOpt.val('35');
												borderRadiusTopRightOpt.val('35');
												borderRadiusBottomLeftOpt.val('35');
												borderRadiusBottomRightOpt.val('35');
												backgroundColorOpt.val('#fff');
												textColorOpt.val('#555');
											// trigger change
												textSize(textSizeOpt);
												width(widthOpt);
												height(heightOpt);
												posLeft(posLeftOpt);
												posTop(posTopOpt);
												posText(posTextOpt);
												borderSize(borderSizeOpt);
												borderStyle(borderStyleOpt);
												borderColor(borderColorOpt);
												borderRadiusTopLeft(borderRadiusTopLeftOpt);
												borderRadiusTopRight(borderRadiusTopRightOpt);
												borderRadiusBottomLeft(borderRadiusBottomLeftOpt);
												borderRadiusBottomRight(borderRadiusBottomRightOpt);
												backgroundColor(backgroundColorOpt);
												textColor(textColorOpt);
											break;
										case 'style_3':
											// set values
												textSizeOpt.val('11');
												widthOpt.val('34');
												heightOpt.val('34');
												posLeftOpt.val('-18');
												posTopOpt.val('11');
												posTextOpt.val('3.1');
												borderSizeOpt.val('0');
												borderStyleOpt.val('none');
												borderColorOpt.val('#fff');
												borderRadiusTopLeftOpt.val('0');
												borderRadiusTopRightOpt.val('0');
												borderRadiusBottomLeftOpt.val('0');
												borderRadiusBottomRightOpt.val('0');
												backgroundColorOpt.val('#fff');
												textColorOpt.val('#555');
											// trigger change
												textSize(textSizeOpt);
												width(widthOpt);
												height(heightOpt);
												posLeft(posLeftOpt);
												posTop(posTopOpt);
												posText(posTextOpt);
												borderSize(borderSizeOpt);
												borderStyle(borderStyleOpt);
												borderColor(borderColorOpt);
												borderRadiusTopLeft(borderRadiusTopLeftOpt);
												borderRadiusTopRight(borderRadiusTopRightOpt);
												borderRadiusBottomLeft(borderRadiusBottomLeftOpt);
												borderRadiusBottomRight(borderRadiusBottomRightOpt);
												backgroundColor(backgroundColorOpt);
												textColor(textColorOpt);
											break;
        								case 'style_4':
											// set values
												textSizeOpt.val('11');
												widthOpt.val('34');
												heightOpt.val('34');
												posLeftOpt.val('-18');
												posTopOpt.val('11');
												posTextOpt.val('2.9');
												borderSizeOpt.val('1');
												borderStyleOpt.val('solid');
												borderColorOpt.val('#9b9b9b');
												borderRadiusTopLeftOpt.val('0');
												borderRadiusTopRightOpt.val('0');
												borderRadiusBottomLeftOpt.val('0');
												borderRadiusBottomRightOpt.val('0');
												backgroundColorOpt.val('#fff');
												textColorOpt.val('#555');
											// trigger change
												textSize(textSizeOpt);
												width(widthOpt);
												height(heightOpt);
												posLeft(posLeftOpt);
												posTop(posTopOpt);
												posText(posTextOpt);
												borderSize(borderSizeOpt);
												borderStyle(borderStyleOpt);
												borderColor(borderColorOpt);
												borderRadiusTopLeft(borderRadiusTopLeftOpt);
												borderRadiusTopRight(borderRadiusTopRightOpt);
												borderRadiusBottomLeft(borderRadiusBottomLeftOpt);
												borderRadiusBottomRight(borderRadiusBottomRightOpt);
												backgroundColor(backgroundColorOpt);
												textColor(textColorOpt);
											break;
									}
								};
								dividerStyleOpt.on('change',function(){
									dividerStyle($(this));
								});
							// Divider Type
								var dividerTypeOpt = $('#btnsx_opt_dual_divider_type');
								var dividerType = function(v){
									var icon = $('#btnsx_opt_dual_divider_icon').val();
									if( v.val() == 'icon' ){
										$('#btnsx_opt_dual_divider_icon').closest('.m12').fadeIn('slow');
										$('#btnsx_opt_dual_divider_text').closest('.m12').hide();
										divider.text('');
										divider.attr('class',
						                	function (i, c) {
						                    	return c.replace(/\b fa-\S+/g, '');
						                });
										divider.addClass(icon);
									} else {
										$('#btnsx_opt_dual_divider_icon').closest('.m12').hide();
										$('#btnsx_opt_dual_divider_text').closest('.m12').fadeIn('slow');
										divider.removeClass('fa');
										divider.attr('class',
						                	function (i, c) {
						                    	return c.replace(/\b fa-\S+/g, '');
						                });
										text(textOpt);
									}
								}
								dividerType(dividerTypeOpt);
								dividerTypeOpt.on('change',function(){
									dividerType(dividerTypeOpt);
								});
							// Divider Icon
								var dividerIconOpt = $('#btnsx_opt_dual_divider_icon');
								dividerIconOpt.on('change',function(){
									dividerType(dividerTypeOpt);
								});
							// Show Container
								window.setTimeout( dcDisplay, 0 );

						// Animations
							var animations = function(){
					            // click animation
					            $('.btnsx-btn').on( 'click', function(){
					                var animation = $( this ).data( 'animation' );
					                if( animation != 'click' )
					                    return;
					                var animationType = $( this ).data( 'animationType' );
					                if( animationType != null ){
					                    $( this ).animation();
					                }
					            });

					            // hover animation
					            $('.btnsx-btn').on( 'mouseenter', function(e){
					              e.preventDefault();
					                var animation = $( this ).data( 'animation' );
					                if( animation != 'hover' )
					                    return;
					                var animationType = $( this ).data( 'animationType' );
					                if( animationType != null ){
					                    $( this ).animation();
					                }
					            });
						    };
						    var tooltip = function(){
								$( '.btnsx-btn' ).each(function() {
									var text = $(this).attr('data-tooltip-text');
									var position = $(this).attr('data-tooltip-position');
									var animation = $(this).attr('data-tooltip-animation');
									var theme = $(this).attr('data-tooltip-theme');
									if( text ) {
										$(this).tooltipster({
											content: text,
											animation: animation,
											position: position,
										   	delay: 100,
										   	theme: theme,
										   	touchDevices: true,
										   	trigger: 'hover',
										   	contentAsHTML: true,
										   	hideOnClick: true,
										   	interactive: true
										});
									}
								});
							}

						// Links
							var links = function( a, b, c, d, e, f, g, h ){
								if( $(h).val() == 'back_to_top' ){
						    		$(a).closest('.m12').hide();
						    		$(b).closest('.m12').hide();
						    		$(c).closest('.m12').hide();
						    		$(d).closest('.m12').hide();
						    		$(e).closest('.m12').hide();
						    		$(f).closest('.m12').hide();
						    		$(g).closest('.m12').hide();
						    	} else if( $(h).val() == 'menu' ){
						    		$(a).closest('.m12').hide();
						    		$(b).closest('.m12').hide();
						    		$(c).closest('.m12').fadeIn('slow');
						    		$(d).closest('.m12').fadeIn('slow');
						    		$(e).closest('.m12').hide();
						    		$(f).closest('.m12').hide();
						    		$(g).closest('.m12').hide();
						    	} else if( $(h).val() == 'post' ){
						    		$(a).closest('.m12').hide();
						    		$(b).closest('.m12').fadeIn('slow');
						    		$(c).closest('.m12').hide();
						    		$(d).closest('.m12').hide();
						    		$(e).closest('.m12').hide();
						    		$(f).closest('.m12').hide();
						    		$(g).closest('.m12').hide();
						    	} else if( $(h).val() == 'edd_checkout' ){
						    		$(a).closest('.m12').hide();
						    		$(b).closest('.m12').hide();
						    		$(c).closest('.m12').hide();
						    		$(d).closest('.m12').hide();
						    		$(e).closest('.m12').fadeIn('slow');
						    		$(f).closest('.m12').hide();
						    		$(g).closest('.m12').hide();
						    	} else if( $(h).val() == 'edd_staright_to_gateway' ){
						    		$(a).closest('.m12').hide();
						    		$(b).closest('.m12').hide();
						    		$(c).closest('.m12').hide();
						    		$(d).closest('.m12').hide();
						    		$(e).closest('.m12').fadeIn('slow');
						    		$(f).closest('.m12').hide();
						    		$(g).closest('.m12').hide();
						    	} else if( $(h).val() == 'login_redirect_custom_page' ){
						    		$(a).closest('.m12').hide();
						    		$(b).closest('.m12').hide();
						    		$(c).closest('.m12').hide();
						    		$(d).closest('.m12').hide();
						    		$(e).closest('.m12').hide();
						    		$(f).closest('.m12').fadeIn('slow');
						    		$(g).closest('.m12').hide();
						    	} else if( $(h).val() == 'logout_redirect_custom_page' ){
						    		$(a).closest('.m12').hide();
						    		$(b).closest('.m12').hide();
						    		$(c).closest('.m12').hide();
						    		$(d).closest('.m12').hide();
						    		$(e).closest('.m12').hide();
						    		$(f).closest('.m12').fadeIn('slow');
						    		$(g).closest('.m12').hide();
						    	} else if( $(h).val() == 'lost_password_redirect_custom_page' ){
						    		$(a).closest('.m12').hide();
						    		$(b).closest('.m12').hide();
						    		$(c).closest('.m12').hide();
						    		$(d).closest('.m12').hide();
						    		$(e).closest('.m12').hide();
						    		$(f).closest('.m12').fadeIn('slow');
						    		$(g).closest('.m12').hide();
						    	} else if( $(h).val() == 'url' ){
						    		$(a).closest('.m12').fadeIn('slow');
						    		$(b).closest('.m12').hide();
						    		$(c).closest('.m12').hide();
						    		$(d).closest('.m12').hide();
						    		$(e).closest('.m12').hide();
						    		$(f).closest('.m12').hide();
						    		$(g).closest('.m12').hide();
						    	} else if( $(h).val() == 'woocommerce_add_to_cart' ){
						    		$(a).closest('.m12').hide();
						    		$(b).closest('.m12').hide();
						    		$(c).closest('.m12').hide();
						    		$(d).closest('.m12').hide();
						    		$(e).closest('.m12').hide();
						    		$(f).closest('.m12').hide();
						    		$(g).closest('.m12').fadeIn('slow');
						    	} else {
						    		$(a).closest('.m12').hide();
						    		$(b).closest('.m12').hide();
						    		$(c).closest('.m12').hide();
						    		$(d).closest('.m12').hide();
						    		$(e).closest('.m12').hide();
						    		$(f).closest('.m12').hide();
						    		$(g).closest('.m12').hide();
						    	}
							}
							var a1 = '#btnsx_opt_dual_button_first_link';
							var b1 = '#btnsx_opt_dual_button_first_link_post';
							var c1 = '#btnsx_opt_dual_button_first_link_menu';
							var d1 = '#btnsx_opt_dual_button_first_link_menu_display';
							var e1 = '#btnsx_opt_dual_button_first_link_edd_id';
							var f1 = '#btnsx_opt_dual_button_first_link_redirect_url';
							var g1 = '#btnsx_opt_dual_button_first_link_woocommerce_id';
							var h1 = '#btnsx_opt_dual_button_first_link_type';

							links( a1,b1,c1,d1,e1,f1,g1,h1 );

							$('#btnsx_opt_dual_button_first_link_type').on('change',function(){
								links( a1,b1,c1,d1,e1,f1,g1,h1 );
							});

						// Button 1 Padding
							var padTop1 = $('#btnsx_opt_dual_button_first_padding_top');
							padTop1.on('propertychange keyup input',function(){
								if( $(this).val() != '' ){
									var val = $(this).val() + 'px';
								}else{
									var val = $(this).val();
								}
								$('.btnsx-dual-first').css('padding-top',val);
							});
							var padBottom1 = $('#btnsx_opt_dual_button_first_padding_bottom');
							padBottom1.on('propertychange keyup input',function(){
								if( $(this).val() != '' ){
									var val = $(this).val() + 'px';
								}else{
									var val = $(this).val();
								}
								$('.btnsx-dual-first').css('padding-bottom',val);
							});
							var padLeft1 = $('#btnsx_opt_dual_button_first_padding_left');
							padLeft1.on('propertychange keyup input',function(){
								if( $(this).val() != '' ){
									var val = $(this).val() + 'px';
								}else{
									var val = $(this).val();
								}
								$('.btnsx-dual-first').css('padding-left',val);
							});
							var padRight1 = $('#btnsx_opt_dual_button_first_padding_right');
							padRight1.on('propertychange keyup input',function(){
								if( $(this).val() != '' ){
									var val = $(this).val() + 'px';
								}else{
									var val = $(this).val();
								}
								$('.btnsx-dual-first').css('padding-right',val);
							});
							$('#btnsx_opt_dual_button_first_padding_all').on('propertychange keyup input',function(){
								var val = $(this).val();
								$('#btnsx_opt_dual_button_first_padding_top').val(val);
								$('#btnsx_opt_dual_button_first_padding_bottom').val(val);
								$('#btnsx_opt_dual_button_first_padding_left').val(val);
								$('#btnsx_opt_dual_button_first_padding_right').val(val);
								if( $(this).val() != '' ){
									var valu = $(this).val() + 'px';
								}else{
									var valu = $(this).val();
								}
								$('.btnsx-dual-first').css('padding-top',valu);
								$('.btnsx-dual-first').css('padding-bottom',valu);
								$('.btnsx-dual-first').css('padding-left',valu);
								$('.btnsx-dual-first').css('padding-right',valu);
							});

						// Links 2
							var a2 = '#btnsx_opt_dual_button_second_link';
							var b2 = '#btnsx_opt_dual_button_second_link_post';
							var c2 = '#btnsx_opt_dual_button_second_link_menu';
							var d2 = '#btnsx_opt_dual_button_second_link_menu_display';
							var e2 = '#btnsx_opt_dual_button_second_link_edd_id';
							var f2 = '#btnsx_opt_dual_button_second_link_redirect_url';
							var g2 = '#btnsx_opt_dual_button_second_link_woocommerce_id';
							var h2 = '#btnsx_opt_dual_button_second_link_type';

							links( a2,b2,c2,d2,e2,f2,g2,h2 );

							$('#btnsx_opt_dual_button_second_link_type').on('change',function(){
								links( a2,b2,c2,d2,e2,f2,g2,h2 );
							});

						// Button 2 Padding
							var padTop2 = $('#btnsx_opt_dual_button_second_padding_top');
							padTop2.on('propertychange keyup input',function(){
								if( $(this).val() != '' ){
									var val = $(this).val() + 'px';
								}else{
									var val = $(this).val();
								}
								$('.btnsx-dual-second').css('padding-top',val);
							});
							var padBottom2 = $('#btnsx_opt_dual_button_second_padding_bottom');
							padBottom2.on('propertychange keyup input',function(){
								if( $(this).val() != '' ){
									var val = $(this).val() + 'px';
								}else{
									var val = $(this).val();
								}
								$('.btnsx-dual-second').css('padding-bottom',val);
							});
							var padLeft2 = $('#btnsx_opt_dual_button_second_padding_left');
							padLeft2.on('propertychange keyup input',function(){
								if( $(this).val() != '' ){
									var val = $(this).val() + 'px';
								}else{
									var val = $(this).val();
								}
								$('.btnsx-dual-second').css('padding-left',val);
							});
							var padRight2 = $('#btnsx_opt_dual_button_second_padding_right');
							padRight2.on('propertychange keyup input',function(){
								if( $(this).val() != '' ){
									var val = $(this).val() + 'px';
								}else{
									var val = $(this).val();
								}
								$('.btnsx-dual-second').css('padding-right',val);
							});
							$('#btnsx_opt_dual_button_second_padding_all').on('propertychange keyup input',function(){
								var val = $(this).val();
								$('#btnsx_opt_dual_button_second_padding_top').val(val);
								$('#btnsx_opt_dual_button_second_padding_bottom').val(val);
								$('#btnsx_opt_dual_button_second_padding_left').val(val);
								$('#btnsx_opt_dual_button_second_padding_right').val(val);
								if( $(this).val() != '' ){
									var valu = $(this).val() + 'px';
								}else{
									var valu = $(this).val();
								}
								$('.btnsx-dual-second').css('padding-top',valu);
								$('.btnsx-dual-second').css('padding-bottom',valu);
								$('.btnsx-dual-second').css('padding-left',valu);
								$('.btnsx-dual-second').css('padding-right',valu);
							});

						// Preview Settings
							var btnPreviewContainer = $('#btnsx-preview .inside');
					    	var btnPreviewOverlay = $('#btnsx-preview-overlay');
					    	var btnPreviewContainerOverlay = $('#btnsx-preview .inside, #btnsx-preview-overlay');
							var previewBgColorOpt = $('#btnsx_opt_dual_preview_background');
							var previewBgColorVal = $('#btnsx_opt_dual_preview_background').val();
							var previewBgImageOpt = $('#btnsx_opt_dual_preview_background_image_image');
							var previewBgImageVal = $('#btnsx_opt_dual_preview_background_image_image').val();
							var previewBgImagePosOpt = $('#btnsx_opt_dual_preview_background_image_position');
							var previewBgImagePosVal = $('#btnsx_opt_dual_preview_background_image_position').val();
							var previewBgOverlayOpt = $('#btnsx_opt_dual_preview_background_overlay');
							var previewBgOverlayVal = $('#btnsx_opt_dual_preview_background_overlay').val();

							btnPreviewContainer.css( 'background-color', previewBgColorVal );
							btnPreviewOverlay.css( 'background-color', previewBgColorVal );
							previewBgColorOpt.btnsxRGBA({
								targetElement: btnPreviewContainerOverlay,
								css: 'background-color'
							});
							if( previewBgImageVal != '' ){
								btnPreviewContainer.css('background-image', 'url("' + previewBgImageVal + '")' );
							}
							previewBgImageOpt.on('propertychange keyup input',function(){
								var val = $(this).val();
								btnPreviewContainer.css('background-image', 'url("' + val + '")' );
							});
							if( previewBgImagePosVal != '' ){
								btnPreviewContainer.css('background-position', previewBgImagePosVal );
							}
							previewBgImagePosOpt.on('change',function(){
								var val = $(this).val();
								btnPreviewContainer.css('background-position', val );
							});
							if( previewBgOverlayVal != '' ){
								btnPreviewOverlay.css('opacity', previewBgOverlayVal );
							}
							previewBgOverlayOpt.on('propertychange keyup input',function(){
								var val = $(this).val();
								btnPreviewOverlay.css('opacity', val );
							});

					});
 					jQuery(window).load(function(){
 						jQuery('#btnsx-preview-loader').hide();
					  	jQuery('#btnsx-dual-preview-container').fadeIn('slow');
					});
				</script>
				<?php
			}
		}

		/**
		 * Function to reset button using ajax
		 * @since  1.2
		 * @return string
		 */
		public function reset_button_ajax() {
			// check for nonce
			check_ajax_referer( 'btnsx-reset-button', 'security' );

			if( $_POST['post_type'] == 'buttons-x' ){
				if( update_post_meta( $_POST['post_id'], 'btnsx', ''  ) ) {
					wp_die( __( 'Reset Successful', 'btnsx' ) );
				} 
			} elseif( $_POST['post_type'] == 'buttons-x-dual' ){
				if( update_post_meta( $_POST['post_id'], 'btnsx-dual', ''  ) ) {
					wp_die( __( 'Reset Successful', 'btnsx' ) );
				} 
			} else {
				wp_die( __( 'Setting fields are already at their default values. Reset not required.', 'btnsx' ) );
			}
		}
 		
		/**
		 * Function to reset a button
		 * @since  0.1
		 * @return string
		 */
		public function reset_button() {
			// create nonce
			$reset_button_nonce = wp_create_nonce( 'btnsx-reset-button' );
			// global $post; var_dump($post);
		    // if ( $post->post_type == 'buttons-x' ) {
				?>
			    <script type="text/javascript">
					jQuery( document ).ready( function( $ ) {
						$( '#btnsx_options_reset' ).on( 'click', function( ev ) {
							ev.preventDefault();
							// disble the button to avoid multiple clicks
							$( this ).attr( 'disabled', 'disabled' );
							// spin the icon
							if( confirm( '<?php _e( "Are you sure?", "btnsx" ); ?>' ) ) {
								$( '#btnsx_options_reset_icon' ).addClass( 'fa-spin' );
							  	var data = {
									'action'	: 'reset_button',							// wp ajax action
									'security'	: '<?php echo $reset_button_nonce; ?>',		// nonce value created earlier
									'post_id'	: $('#post_ID').val(),	// button ID
									'post_type'	: $('#post_type').val()	// button type
								};
								// fire ajax
							  	$.post( ajaxurl, data, function( response ) {
							  		// if nonce fails then not authorized else settings saved
							  		if( response === '-1' ){
								  		// do nothing
							  		} else {
							  			confirm( response );
							  			location.reload();
							  		}
							  	});
							}
						});  
					});
				</script>
				<?php
			// }
		}

		/**
		 * Function to check difference in multi-dimensional array - http://stackoverflow.com/a/16359538/2430413
		 * @since  0.1
		 * @param  array    $aArray1
		 * @param  array    $aArray2
		 * @return array
		 */
		public function multi_array_diff( $aArray1, $aArray2 ) {
		  	$aReturn = array();
		  	foreach ( $aArray1 as $mKey => $mValue ) {
		    	if ( array_key_exists( $mKey, $aArray2 ) ) {
		      		if ( is_array( $mValue ) ) {
		        		$aRecursiveDiff = $this->multi_array_diff( $mValue, $aArray2[ $mKey ] );
		        	if ( count( $aRecursiveDiff ) ) { $aReturn[ $mKey ] = $aRecursiveDiff; }
		      	} else {
		        	if ( $mValue != $aArray2[ $mKey ] ) {
		          	$aReturn[ $mKey ] = $mValue;
		        	}
		      	}
		    } else {
		      $aReturn[ $mKey ] = $mValue;
		    }
		  }
		  return $aReturn;
		}

		/**
		 * Function to save settings using ajax
		 * @since  0.1
		 * @return string
		 */
		public function settings_save_ajax() {
			ini_set('max_execution_time', 300); //300 seconds = 5 minutes
			// check for nonce
			check_ajax_referer( 'btnsx-settings', 'security' );
			// store form data
			parse_str( $_POST['value'], $form);
			// unset not required values 
			unset( $form['option_page'], $form['action'], $form['_wpnonce'], $form['_wp_http_referer'] );

			$form['tab'] = $_POST['tab'];
			
			if( !is_array( get_option('btnsx_settings') ) ) {
				$options = array();
			} else {
				$options = get_option( 'btnsx_settings' );
			}
			// 
			if( !empty( $form ) ) {
				$diff = $this->multi_array_diff( $options, $form );
				$diff2 = $this->multi_array_diff( $form, $options );
				$diff = array_merge( $diff, $diff2 );
			} else {
				$diff = array();
			}
			// if the value are changed update our options else do nothing
			if( !empty( $diff ) ) {	
				if( update_option( 'btnsx_settings', $form ) ) {
					if( $form[ 'css' ] === 'external' ) {
						$btnsx = new Btnsx();
						$btnsx->external_css('empty');
					}
					wp_die( __( 'Settings Saved', 'btnsx' ) );
				} else {
					wp_die( __( 'Settings Not Saved', 'btnsx' ) );
				}
			} else {
				wp_die( __( 'No change detected', 'btnsx' ) );
			}
		}

		/**
		 * Function to reset settings using ajax
		 * @since  0.1
		 * @return string
		 */
		public function settings_reset_ajax() {
			// check for nonce
			check_ajax_referer( 'btnsx-settings', 'security' );
			
			if( update_option( 'btnsx_settings', array() ) ) {
				wp_die( __( 'Reset Successful', 'btnsx' ) );
			} else {
				wp_die( __( 'Setting fields are already at their default values. Reset not required.', 'btnsx' ) );
			}
		}

		/**
		 * Function to output script on settings page
		 * @since  0.1
		 * @return string
		 */
		public function settings_jquery() {
			// create nonce
			$settings_nonce = wp_create_nonce( 'btnsx-settings' );
			$screen = get_current_screen();
		    if ( $screen->id == 'buttons-x_page_buttons-x-settings' ) {
				?>
			    <script type="text/javascript">
					jQuery( document ).ready( function( $ ) {
						$( '#btnsx-settings-reset' ).on( 'click', function( e ) {
							e.preventDefault();
							// $( '#btnsx-settings-form' ).clearForm();
							btnText = '<?php _e( "Reset", "btnsx" ); ?>';
							// disble the button to avoid multiple clicks
						  	$( this ).attr( 'disabled', 'disabled' ).html( '<i class="fa fa-refresh fa-spin"></i>' );
						  	var data = {
								'action'	: 'settings_reset',							// wp ajax action
								'security'	: '<?php echo $settings_nonce; ?>',			// nonce value created earlier
								'value'		: ''	// fetch form data
							};
							// fire ajax
						  	$.post( ajaxurl, data, function( response ) {
						  		// if nonce fails then not authorized else settings saved
						  		if( response === '-1' ){
							  		toast( '<?php _e( "Not Authorized!", "btnsx" ); ?>', '#btnsx-settings-reset', btnText );
						  		} else {
						  			toast( response, '#btnsx-settings-reset', btnText );
						  			location.reload();
						  			// console.log( response );
						  		}
						  	});
						});
						/**
						 * Function to clear all form data
						 * @since  0.1
						 */
						$.fn.clearForm = function() {
						  	return this.each( function() {
						    	var type = this.type, tag = this.tagName.toLowerCase();
						    	if (tag == 'form')
						      		return $( ':input', this).clearForm();
						    	if ( type == 'text' || type == 'password' || tag == 'textarea' )
						      		this.value = '';
						    	else if ( type == 'checkbox' || type == 'radio' )
						      		this.checked = false;
						    	else if ( tag == 'select' )
						      		this.selectedIndex = -1;
						  	});
						};

						$( '#btnsx-settings-submit' ).on( 'click', function( e ) {
							e.preventDefault();
							btnText = '<?php _e( "Save", "btnsx" ); ?>';
							css = $('input[name=css]:checked').val();
							var spinText = '';
							if( css == 'external' ){
								spinText = '<?php _e( "Generating External CSS..", "btnsx" ); ?>';
							}
							// disble the button to avoid multiple clicks
						  	$( this ).attr( 'disabled', 'disabled' ).html( '<i class="fa fa-refresh fa-spin"></i><span>'  + spinText + '</span>' );
						  	$( this ).after( '<span style="font-size:10px;color:#ababab;">'  + spinText + '</span>' );
							var data = {
								'action'	: 'settings_save',							// wp ajax action
								'security'	: '<?php echo $settings_nonce; ?>',			// nonce value created earlier
								'value'		: $( '#btnsx-settings-form' ).serialize(),		// fetch form data
								'tab'		: $( '#btnsx-tabs-0' ).find('nav ul .tab-current').index()
							};
							// fire ajax
						  	$.post( ajaxurl, data, function( response ) {
						  		// if nonce fails then not authorized else settings saved
						  		if( response === '-1' ){
							  		toast( '<?php _e( "Not Authorized!", "btnsx" ); ?>', '#btnsx-settings-submit', btnText );
						  		} else {
						  			// console.log(response);
						  			toast( response, '#btnsx-settings-submit', btnText );
						  			location.reload(); // reload page
						  		}
						  	});
						});
						/**
					  	 * Dialog box
					  	 * @since  0.1
					  	 * @param  {string}  dialogText text to be displayed inside dialog
					  	 * @param  {string}  buttonText text to be displayed inside button
					  	 * @return {string}
					  	 */
					  	function toast( dlgText, btnId, btnText ){
					  		Materialize.toast( dlgText, 2000, '', function(){
					  			$( btnId ).removeAttr( 'disabled' ).html( btnText );
					  		});
					  	}
					});
				</script>
				<?php
			}
		}

		

		
	} // Ajax Class
}

/**
 *  Kicking this off
 */

$btn_options = new BtnsxAjax();
$btn_options->init();