/**
 * Main WPSyncSheetsGravityForms namespace.
 *
 * @since 1.0.0
 * @package wpsyncsheets-gravity-forms
 */

( function ( $ ) {
		$( document ).ready(
			function () {
				$( '#gform_google_revoke_button' ).on(
					'click',
					function ( e ) {
						e.preventDefault();
						changeAuthToken( '' );
					}
				);
				function changeAuthToken( token ) {
					$( 'input#authToken' ).val( token );
					$( '#gform-settings #gform-settings-save' ).trigger( 'click' );
				}
			}
		);
} )( jQuery );
// Create new Google Spreadsheet and Sheet Name.
( function ( $ ) {
		$( document ).ready(
			function () {
				$( '#clearloader' ).hide();
				$( '#cleartext' ).hide();
				var spreedSheets = $( "select#spreedsheets" ).val();
				$( "#gform_google_view_button" ).attr( 'href',"https://docs.google.com/spreadsheets/d/" + spreedSheets );
				$( "#gform_google_download_button" ).attr( 'href',"https://docs.google.com/spreadsheets/d/" + spreedSheets + "/export?format=xlsx" );

				$( '#gform_google_new_spreadsheet_button' ).on(
					'click',
					function ( e ) {
						e.preventDefault();
						var newspreadsheettext = $( '#newspreadsheetlabel' ).val();
						var newsheettext       = $( '#sheetlabel' ).val();
						if (newspreadsheettext == '') {
							alert( 'Please add spreadsheet name' ); return false; }
						if (newsheettext == '') {
							alert( 'Please add sheet name' ); return false; }
						var createnewspreadsheet = $( '<input type=\"hidden\" name=\"createnewspreadsheet\" value=\"yes\" />' );
						$( '#gform-settings' ).append( createnewspreadsheet );
						$( '#gform-settings #gform-settings-save' ).trigger( 'click' );
					}
				);
				$( '#gform_google_clear_button' ).on(
					'click',
					function ( e ) {
						e.preventDefault();

						var formId   = getUrlParameter( 'id' );
						var feedId   = getUrlParameter( 'fid' );
						var _wpnonce = $( "#wpsslgf_general_settings" ).val();
						var wpssg_admin_ajax_object;
						if (typeof admin_ajax_object === 'undefined') {
							wpssg_admin_ajax_object = ajaxurl;
						} else {
							wpssg_admin_ajax_object = admin_ajax_object.ajaxurl;
						}
						$.ajax(
							{
								url : wpssg_admin_ajax_object,
								type : 'post',
								data :"action=wpsslgf_clear_spreadsheet&form_id=" + formId + "&fid=" + feedId + "&_wpnonce=" + _wpnonce,
								beforeSend:function () {
									if (confirm( "Are you sure? You want to enable Clear Spreadsheet this is clear all your entries within the spreadsheet and you would be remained only with sheet headers." )) {
										$( '#clearloader' ).show();
										$( '#gform_google_clear_button' ).hide();
									} else {
										return false;
									}
								},
								success : function ( response ) {
									if (response === 'successful') {
										alert( 'Spreadsheet Cleared successfully' );
									} else {
										alert( response );
									}
									$( '#clearloader' ).hide();
									document.getElementById( "gform_google_clear_button" ).style.display = "inline-block";
								},
								error: function (s) {
									alert( 'Error' );
									$( '#clearloader' ).hide();
									document.getElementById( "gform_google_clear_button" ).style.display = "inline-block";
								}
							}
						);
					}
				);
			}
		);
} )( jQuery );
// Sync all entries button.
( function ( $ ) {
		$( document ).ready(
			function () {
				$( '#gform_google_sync_button' ).on(
					'click',
					function ( e ) {
						e.preventDefault();
						$( '#gform_google_sync_button' ).hide();
						$( '#note' ).hide();
						$( '#syncloader' ).show();
						$( '#synctext' ).show();
						syncfun();
					}
				);
				function syncfun() {
					var synccallbutton = $( '<input type=\"hidden\" name=\"synccall\" value=\"yes\" />' );
					$( '#gform-settings' ).append( synccallbutton );
					$( '#gform-settings #gform-settings-save' ).trigger( 'click' );
				}
			}
		);
} )( jQuery );
// Set Default Google Spreadsheet Headers.
( function ( $ ) {
		"use strict";
		$( document ).ready(
			function () {
				$( '#gform_google_header_button' ).on(
					'click',
					function ( e ) {
						if ( '' == $( '#newsheetlabel' ).val() && 'newsheet' == $( '#sheetselect' ).val() ) {
							alert( 'Please enter sheet name.' );
							$( '#newsheetlabel' ).focus();
							return false;
						}
						if ( '' == $( '#sheetselect' ).val() ) {
							alert( 'Please select sheet.' );
							$( '#sheetselect' ).focus();
							return false;
						}
						$( '#wpssg_set_default_headers' ).val( 1 );
						e.preventDefault();
						changeAuthToken();
					}
				);
				function changeAuthToken() {
					var headerSet = $( '<input type=\"hidden\" name=\"headerset\" value=\"yes\" />' );
					$( '#gform-settings' ).append( headerSet );
					$( '#gform-settings #gform-settings-save' ).trigger( 'click' );
				}
			}
		);
} )( jQuery );


function getUrlParameter(sParam) {
	var sPageURL            = window.location.search.substring( 1 ),
		sURLVariables       = sPageURL.split( '&' ),
		sURLVariableslength = sURLVariables.length,
		sParameterName,
		i;
	for (i = 0; i < sURLVariableslength; i++) {
		sParameterName = sURLVariables[i].split( '=' );

		if (sParameterName[0] === sParam) {
			return sParameterName[1] === undefined ? true : decodeURIComponent( sParameterName[1] );
		}
	}
};
jQuery( document ).ready(
	function () {
		$firsttime = true;

		var spreadsheet;
		var sheet;
		spreadsheet = 'wpssgdefault';
		sheet       = 'wpssgdefault';

		jQuery( "#_gform_setting_mappedFields_entry_id" ).attr( 'readonly', true );
		jQuery( "#syncallentries0" ).prop( "checked", true );
		jQuery( '.wpssg-support' ).parent().attr( 'target','_blank' );
		jQuery( 'input[name=_gform_setting_spreadsheet_option]' ).change(
			function () {
				displayinput( false );
				$firsttime = false;
			}
		);
		jQuery( document ).on(
			'change',
			'#spreedsheets',
			function () {
				var src    = jQuery( '#existingloader' ).attr( 'src' );
				var loader = '<img src="' + src + '" id="wpsyncloader">';
				jQuery( '#gform_setting_newsheet' ).hide();
				jQuery( '#gform_setting_sheetselect button' ).after( loader );
				var sid = jQuery( this ).val();
				if ( sid == '') {
					jQuery( "#sheetselect" ).empty();
				}
				viewclear();
				displaysheet( sid );
			}
		);
		jQuery( document ).on(
			'change',
			'#sheetselect',
			function () {
				var sheetname = jQuery( this ).val();
				if ( sheetname == 'newsheet' ) {
					var headerSet = jQuery( '<input type=\"hidden\" id="headerset" name=\"headerset\" value=\"yes\" />' );
					jQuery( '#gform-settings' ).append( headerSet );
					jQuery( '#gform_setting_newsheet' ).show();
				} else {
					jQuery( '#gform_setting_newsheet' ).hide();
					jQuery( '#headerset' ).remove();
				}

				if ( sheetname != 'newsheet' && sheetname != '' && sheetname != sheet ) {
					var src    = jQuery( '#existingloader' ).attr( 'src' );
					var loader = '<img src="' + src + '" id="wpsyncloader">';
					jQuery( '#gform_setting_sheetselect button' ).after( loader );
					var sid    = jQuery( '#spreedsheets' ).val();
					var formId = getUrlParameter( 'id' );
					var feedId = getUrlParameter( 'fid' );
					setheaders( sid, sheetname, formId, feedId );
				} else if ( sheetname == 'newsheet' ) {
					jQuery( '.gform-settings-field__headers_button' ).show();
					jQuery( '.gform-settings-field__note_ins' ).show();
				} else {
					jQuery( '.gform-settings-field__headers_button' ).hide();
					jQuery( '.gform-settings-field__note_ins' ).hide();
				}
				viewclear();
			}
		);

		jQuery( ".cronjobselectbtn" ).on(
			"click",
			function (e) {
				e.preventDefault();
				var setting = jQuery( '#generate_cron_url_option' ).val();
				if (setting.length > 0) {

					jQuery( '.cronjobselectbtn' ).hide();
					jQuery( '#cronjobselectloader' ).fadeIn();
					jQuery( '.wpssg_cronjob_url_ul' ).hide();
					var formId = getUrlParameter( 'id' );
					var feedId = getUrlParameter( 'fid' );

					jQuery.ajax(
						{
							url: admin_ajax_object.ajaxurl,
							type: "post",
							data: {
								action  : "wpssg_generate_cron_url",
								setting : setting,
								form_id  : formId,
								feed_id  : feedId,
							},
							success: function (response) {
								if (response.success) {
									jQuery( '#wpssg_cronjob_url' ).html( response.data );
									jQuery( '.wpssg_cronjob_url_ul' ).fadeIn();
								} else if (response.error) {
									alert( response.data );
								} else {
									alert( response );
								}
								jQuery( '.cronjobselectbtn' ).fadeIn();
								jQuery( '#cronjobselectloader' ).hide();
							},
							error: function (s) {
								alert( "Something went wrong while generating the URL. Please refresh the page and try again." );
								jQuery( '.cronjobselectbtn' ).fadeIn();
								jQuery( '#cronjobselectloader' ).hide();
							},
						}
					);
				} else {
					alert( 'Please select an action from the dropdown.' );
					return false;
				}
			}
		);
		jQuery( "#wpssg_cronjob_url_span" ).on(
			"click",
			function (e) {
				var data_id     = jQuery( this ).attr( 'data-id' );
				var data_target = jQuery( this ).attr( 'data-target' );
				wpssgCopy( data_id, data_target );
			}
		);

		function viewclear(){
			currentspreadsheet = jQuery( "#spreedsheets" ).val();
			currentsheet       = jQuery( "#sheetselect" ).val();
			if ( currentspreadsheet == '' || currentsheet == '' || currentsheet == 'newsheet' || currentspreadsheet != spreadsheet || currentsheet != sheet ) {
				jQuery( '.gform-settings-field__view_clear_button' ).hide();
			} else {
				jQuery( '.gform-settings-field__view_clear_button' ).show();
			}
		}

		if ( jQuery( '#spreedsheets' ).length ) {
			initilizedropdown();
			displayinput( true );
			displaysheet( 'onload' );
		}

		function initilizedropdown(){
			var _wpnonce = jQuery( "#wpsslgf_general_settings" ).val();
			if (typeof admin_ajax_object === 'undefined') {
				wpssg_admin_ajax_object = ajaxurl;
			} else {
				wpssg_admin_ajax_object = admin_ajax_object.ajaxurl;
			}
			var id  = getUrlParameter( 'id' );
			var fid = getUrlParameter( 'fid' );
			jQuery.ajax(
				{
					url : wpssg_admin_ajax_object,
					type : 'post',
					data :"action=wpssg_list_googlespreadsheet_ajax&id=" + id + "&fid=" + fid + "&_wpnonce=" + _wpnonce,
					success : function ( response ) {
						jQuery( '#spreedsheets' ).empty();
						data = JSON.parse( response );
						jQuery.each(
							data['sheetnames'],
							function (key, val) {
								var name = val['label'];
								var id   = val['value'];
								if ( id == data['id'] ) {
									if ( spreadsheet == 'wpssgdefault' ) {
										spreadsheet = data['id'];
									}
									jQuery( '.gform-settings-field__view_clear_button' ).show();
									jQuery( '#spreedsheets' ).append( '<option value="' + id + '" selected>' + name + '</option>' );
								} else {
									jQuery( '#spreedsheets' ).append( '<option value="' + id + '">' + name + '</option>' );
								}
							}
						);
						displaysheet();
						var spreedSheets = jQuery( "select#spreedsheets" ).val();
						jQuery( "#gform_google_view_button" ).attr( 'href',"https://docs.google.com/spreadsheets/d/" + spreedSheets );
						jQuery( "#gform_google_download_button" ).attr( 'href',"https://docs.google.com/spreadsheets/d/" + spreedSheets + "/export?format=xlsx" );

					},
					error: function (s) {
					}
				}
			);
		}
		function displayinput( $firsttime ){
			if ($firsttime) {
				var id  = getUrlParameter( 'id' );
				var fid = getUrlParameter( 'fid' );
				if (fid == 0) {
					jQuery( 'input[name=_gform_setting_spreadsheet_option][value="new"]' ).prop( 'checked', true );
				}
			}

			var value = jQuery( 'input[name=_gform_setting_spreadsheet_option]:checked' ).val();
			if (jQuery.inArray( value, ['new', 'existing' ] ) === -1) {
				value = 'new';
			}
			if ( 'new' == value ) {
				jQuery( '#gform_setting_newspreedsheets' ).show();
				jQuery( '#gform_setting_spreedsheets' ).hide();
				jQuery( '#gform_setting_sheetselect' ).hide();
				jQuery( '.gform-settings-field__headers_button' ).hide();
				jQuery( '.gform-settings-field__note_ins' ).hide();
				jQuery( '.gform-settings-field__view_clear_button' ).hide();
				jQuery( '#gform_setting_newsheet' ).hide();

			} else if ( 'existing' == value ) {
				jQuery( '#gform_setting_spreedsheets' ).show();
				jQuery( '#gform_setting_sheetselect' ).show();
				jQuery( '.gform-settings-field__headers_button' ).hide();
				jQuery( '.gform-settings-field__note_ins' ).hide();
				jQuery( '.gform-settings-field__view_clear_button' ).show();
				jQuery( '#gform_setting_newspreedsheets' ).hide();

				var sheetname = jQuery( '#sheetselect' ).val();
				if ( sheetname == 'newsheet' ) {
					jQuery( '#gform_setting_newsheet' ).show();
					jQuery( '.gform-settings-field__headers_button' ).show();
					jQuery( '.gform-settings-field__note_ins' ).show();
				} else {
					jQuery( '#gform_setting_newsheet' ).hide();
				}
			} else {
				jQuery( '#gform_setting_newspreedsheets' ).hide();
				jQuery( '#gform_setting_spreedsheets' ).hide();
				jQuery( '#gform_setting_sheetselect' ).hide();
				jQuery( '.gform-settings-field__headers_button' ).hide();
				jQuery( '.gform-settings-field__note_ins' ).hide();
				jQuery( '.gform-settings-field__view_clear_button' ).hide();
			}
		}
		function displaysheet( value ){
			if ( '' == value || value === undefined ) {
				jQuery( document ).find( '#wpsyncloader' ).remove();
				return;
			}
			var _wpnonce = jQuery( "#wpsslgf_general_settings" ).val();
			if (typeof admin_ajax_object === 'undefined') {
				wpssg_admin_ajax_object = ajaxurl;
			} else {
				wpssg_admin_ajax_object = admin_ajax_object.ajaxurl;
			}
			var id  = getUrlParameter( 'id' );
			var fid = getUrlParameter( 'fid' );
			jQuery.ajax(
				{
					url : wpssg_admin_ajax_object,
					type : 'post',
					data :"action=wpssg_list_googlesheet_ajax&sid=" + value + "&id=" + id + "&fid=" + fid + "&_wpnonce=" + _wpnonce,
					success : function ( response ) {
						var temp = false;
						jQuery( '#sheetselect' ).empty();
						data = JSON.parse( response );
						jQuery.each(
							data['sheetnames'],
							function (key, val) {
								var name = val['label'];
								var id   = val['value'];
								if ( data['name'] == name ) {
									temp = true;
									if ( sheet == 'wpssgdefault' ) {
										sheet = data['name'];
									}
									jQuery( '#sheetselect' ).append( '<option value="' + id + '" selected>' + name + '</option>' );
								} else {
									jQuery( '#sheetselect' ).append( '<option value="' + id + '">' + name + '</option>' );
								}
							}
						);
						jQuery( document ).find( '#wpsyncloader' ).remove();
						if ( temp ) {
							jQuery( '#gform_setting_sheetselect' ).show();
							var val = jQuery( 'input[name="_gform_setting_spreadsheet_option"]:checked' ).val();
							if ( typeof val === 'undefined' ) {
								jQuery( "#spreadsheet_option1" ).prop( "checked", true );
								displayinput( false );
							}
						}
					},
					error: function (s) {
					}
				}
			);
		}
		function setheaders( sid, sheetname, formId, feedId ){
			if (typeof admin_ajax_object === 'undefined') {
				wpssg_admin_ajax_object = ajaxurl;
			} else {
				wpssg_admin_ajax_object = admin_ajax_object.ajaxurl;
			}
			var _wpnonce = jQuery( "#wpssg_general_settings" ).val();
			jQuery.ajax(
				{
					url : wpssg_admin_ajax_object,
					type : 'post',
					data :"action=wpssg_check_headers_exists&sid=" + sid + "&sheetname=" + sheetname + "&_wpnonce=" + _wpnonce + "&form_id=" + formId + "&feed_id=" + feedId,
					success : function ( response ) {
						if ( response ) {
							if (response.success) {
								jQuery( '.gform-settings-field__note_ins' ).html( 'The first column in the sheet must be the ' + response.data.idlabel + '.' );
								jQuery( '.gform-settings-field__note_ins' ).show();
								jQuery( '.gform-settings-field__note_ins' ).css( 'background-color','rgb(255 0 0 / 13%)' );
								jQuery( "#sheetselect" ).val( jQuery( "#sheetselect option:first" ).val() );
							} else {
								jQuery( '.gform-settings-field__headers_button' ).show();
								jQuery( '.gform-settings-field__note_ins' ).show();
							}
						} else {
							jQuery( 'button#gform-settings-save' ).trigger( 'click' )
						}
						jQuery( document ).find( '#wpsyncloader' ).remove();
					},
					error: function (s) {
					}
				}
			);
		}
		function getUrlParameter(sParam) {
			var sPageURL            = window.location.search.substring( 1 ),
				sURLVariables       = sPageURL.split( '&' ),
				sParameterName,
				i;
			var sURLVariablesLength = sURLVariables.length;
			for (i = 0; i < sURLVariablesLength; i++) {
				sParameterName = sURLVariables[i].split( '=' );

				if (sParameterName[0] === sParam) {
					return sParameterName[1] === undefined ? true : decodeURIComponent( sParameterName[1] );
				}
			}
			return false;
		};
	}
);