/**
 * @package     VP Advanced User
 * @author      Abhishek Das <info@virtueplanet.com>
 * @copyright   Copyright (C) 2012-2019 VirtuePlanet Services LLP. All rights reserved.
 * @license     GNU General Public License version 2 or later; see LICENSE.txt
 * @link        https://www.virtueplanet.com
 */
var VPAUbuttons = window.VPAUbuttons || {};

(function($, window, document, VPAUbuttons, VPAU) {
	"use strict";

	VPAUbuttons.cache = {};
	VPAUbuttons.ajaxPool = null;

	VPAUbuttons.init = function() {
		this.socialLogin();
		this.autoRefresh();
	};

	VPAUbuttons.socialLogin = function() {
		var $buttons = this.cache.$loginButtons,
			$loginButtons = $buttons.find('.vpau-btn'),
			$acceptanceBtn = $('#btn-vp-social-acceptance'),
			$acceptanceModal = $('#vp-social-acceptance-modal'),
			$acceptanceTitle = $('#vp-social-acceptance-title'),
			$acceptanceForm = $('#vp-social-acceptance-form');

		$('[data-vpautarget]').each(function() {
			$(this).attr('target', '_newwindow');
		});

		// Prevent automatic form submission
		$loginButtons.each(function() {
			var $thisForm = $(this).closest('form');
			if ($thisForm.length && !$thisForm.data('protected')) {
				$thisForm.on('submit', function(e) {
					var $provider = $(this).find('input[name="provider"]:hidden');
					if ($provider.length && !$provider.val()) {
						e.preventDefault();
						return false;
					}
				});
			}
		});

		// Login popups
		$loginButtons.off('click').on('click', function(e) {
			e.preventDefault();

			var $el = $(this),
				$form = $el.closest('form'),
				$provider_input = $form.find('input[name="provider"]:hidden'),
				provider = $el.data('provider'),
				title = $el.attr('title') || $el.data('original-title');

			if (!$form.length) {
				alert('Login form not found');
				return false;
			}

			if (!$provider_input.length) {
				alert('Provider input element not found.');
				return false;
			}

			if (!provider) {
				alert('Provider data attribute not set for the button.');
				return false;
			}

			if ($acceptanceBtn.length && $acceptanceForm.length && $acceptanceForm.find('input', 'select', 'textarea').length) {
				if (title) {
					$acceptanceTitle.text(title);
				}

				$acceptanceForm.data('socialbtn', this);
				$acceptanceBtn.trigger('click');
			} else {
				VPAUbuttons.submit($provider_input, $form, provider);
			}

			return false;
		});

		// Custom fields form submission
		$acceptanceForm.off('submit').on('submit', function(e) {
			e.preventDefault();

			var socialBtn = $(this).data('socialbtn'),
				$el = socialBtn ? $(socialBtn) : null;

			if (!$el || !$el.length) {
				alert('Social button not set for the acceptance form.');
				return false;
			}

			var $form = $el.closest('form'),
				$provider_input = $form.find('input[name="provider"]:hidden'),
				provider = $el.data('provider'),
				that = this,
				$messageBox = $acceptanceModal.find('.vpau-system-message');

			if (VPAUbuttons.ajaxPool && VPAUbuttons.ajaxPool.readyState != 4) {
				VPAUbuttons.ajaxPool.abort();
			}

			VPAUbuttons.ajaxPool = $.ajax({
				type: 'POST',
				dataType: 'JSON',
				url: VPAU._('base_url') + '/index.php?option=com_vpadvanceduser&format=json&task=user.saveCustomFields',
				cache: false,
				beforeSend: function() {
					VPAU.showPageLoader();
					$(that).find('button[type="submit"], input[type="submit"]').attr('disabled', true);
					VPAU.hideAlert($messageBox);
				},
				data: $(this).serialize(),
				success: function(output) {
					if (!output || !output.result) {
						$(that).find('button[type="submit"], input[type="submit"]').removeAttr('disabled');
						VPAU.hidePageLoader();
						if (output.message) {
							VPAU.showAlert($messageBox, output.message, 'error');
						}
					} else {
						if (output.message) {
							VPAU.showAlert($messageBox, output.message, 'success');
						}
						VPAUbuttons.submit($provider_input, $form, provider);
					}
				},
				error: function() {
					$(that).find('button[type="submit"], input[type="submit"]').removeAttr('disabled');
					VPAU.hidePageLoader();
					console.error('Ajax error generated.');
				}
			});
		});
	};

	VPAUbuttons.submit = function($provider_input, $form, provider) {
		$provider_input.val(provider);

		if ($form.data('vpautarget')) {

			var popup = $el.attr('class').replace('-', '_'),
				link = $form.attr('action'),
				w = 700,
				h = 400,
				t = 80,
				l = 0;

			// Set popup sizes
			switch (popup) {
				case 'vpau-btn-twitter':
					h = 300;
					break;
				case 'vpau-btn-fancy':
					w = 480;
					l = w / 2;
					h = 720;
					break;
				case 'vpau-btn-google':
					w = 500;
					l = w / 2;
					break;
			}

			// Horizontally Center
			l = (screen.width / 2) - (w / 2);

			var win = window.open(link, '_newwindow', 'width=' + w + ', height=' + h + ', top=' + t + ', left = ' + l);
		}

		$form.submit();

		setTimeout(function() {
			$provider_input.val('');
		}, 100);
	};

	VPAUbuttons.refresh = function() {
		window.opener.location.reload();
		setTimeout(function() {
			window.close();
		}, 100);
		return false;
	};

	VPAUbuttons.autoRefresh = function() {
		if ($('[data-vpaureload]').length) {
			setTimeout(function() {
				window.opener.location.reload();
				window.close();
			}, 4000);
		}
	};

	$(function() {
		VPAUbuttons.cache = {
			$loginButtons: $('.vpau-social-buttons')
		};

		VPAUbuttons.init();
	});

})(jQuery, window, document, VPAUbuttons, VPAU);