var RSMembership = {};

RSMembership.parseJSON = function (data) {
	if (typeof data != 'object') {
		var match = data.match(/{.*}/);
		return jQuery.parseJSON(match[0]);
	}
	return jQuery.parseJSON(data);
};

RSMembership.utils = {
	format_decimals : 2,
	format_decimals_point: '.',
	format_thousands_sep: '',

	random: function(){
		return Math.ceil(10000*Math.random());
	},

	magnificModal: function(modal_id) {
		if (typeof jQuery == 'undefined')
		{
			alert(Joomla.JText._('COM_RSMEMBERSHIP_JQUERY_NOT_FOUND'));
		}
		else {
			jQuery.magnificPopup.open({
				type: 'inline',
				preloader: true,
				overflowY: 'scroll',
				items: {
					src: modal_id,
					callbacks: {
						beforeOpen: function () {
							jQuery(modal_id).show();
						},
						close: function () {
							jQuery(modal_id).hide();
						}
					}
				}
			});
		}
	},

	tooltipster: function (){
		if (typeof jQuery == 'undefined')
		{
			alert(Joomla.JText._('COM_RSMEMBERSHIP_JQUERY_NOT_FOUND'));
		}
		else {
			jQuery('.hasRsmemTooltip').tooltipster({
				functionInit: function(instance, helper){

					var $origin = jQuery(helper.origin),
						dataOptions = $origin.attr('data-tooltipster');

					if(dataOptions){

						dataOptions = JSON.parse(dataOptions);

						jQuery.each(dataOptions, function(name, option){
							instance.option(name, option);
						});
					}
				}
			});
		}
	},

	number_format: function(number) {
		var decimals = RSMembership.utils.format_decimals;
		var dec_point = RSMembership.utils.format_decimals_point;
		var thousands_point = RSMembership.utils.format_thousands_sep;

		if (number == null || !isFinite(number)) {
			console.log('number is not valid');
			return number;
		}

		if (!decimals) {
			var len = number.toString().split('.').length;
			decimals = len > 1 ? len : 0;
		}

		if (!dec_point) {
			dec_point = '.';
		}

		if (!thousands_point) {
			thousands_point = ',';
		}

		number = parseFloat(number).toFixed(decimals);

		number = number.replace(".", dec_point);

		var splitNum = number.split(dec_point);
		splitNum[0] = splitNum[0].replace(/\B(?=(\d{3})+(?!\d))/g, thousands_point);
		number = splitNum.join(dec_point);

		return number;
	}
};


RSMembership.subscribe = {
	init: {
		ajax_wait			: false,
		timeout				: false,
		captcha_url			: '',
		validations			: [],
		field_validations	: [],
		err_html_class		: 'rsm_field_error',
		check_user_url		: ''
	},

	// Username related function
	ajax_flag: function() {
		if (RSMembership.subscribe.init.timeout) {
			clearTimeout(RSMembership.subscribe.init.timeout);
		}
		RSMembership.subscribe.init.ajax_wait = true;
		RSMembership.subscribe.init.timeout = setTimeout(function () {
			RSMembership.subscribe.init.ajax_wait = false;
			RSMembership.subscribe.check_username(document.getElementById('rsm_username'));
		} , 2000);
	},

	validate_username: function(username) {
		var regex = new RegExp("[\<|\>|\"|\'|\%|\;|\(|\)|\&]", "i");

		if(username.length < 2 || regex.test(username)) {
			return false;
		}

		return true;
	},

	check_username: function(what) {
		// convert to jQuery object
		what = jQuery(what);
		var regex = new RegExp("[\<|\>|\"|\'|\%|\;|\(|\)|\&]", "i");
		var clean_value = what.val().replace(regex, '');

		what.val(clean_value);
		username = what.val();

		var message = jQuery('#rsm_username_message');

		if (!RSMembership.subscribe.validate_username(username)) {
			message.show('fast');
			message.addClass('rsm_error');
			message.html(Joomla.JText._('COM_RSMEMBERSHIP_PLEASE_TYPE_USERNAME'));
			return false;
		}

		message.hide('fast');
		message.removeClass('rsm_error');
		message.html('');

		if (RSMembership.subscribe.init.ajax_wait) {
			return true;
		}

		var params = {
			username : jQuery('#rsm_username').val().trim(),
			name : jQuery('#name').val(),
			email : jQuery('#email').val()
		};

		jQuery.ajax({
			type    	: 'POST',
			url     	: RSMembership.subscribe.init.check_user_url,
			dataType  	: 'html',
			data      	: params,
			beforeSend	: function () {
				jQuery('#rsm_loading').show('fast');
			}
		}).done(function (response) {
				jQuery('#rsm_loading').hide('fast');
				RSMembership.subscribe.init.ajax_wait = false;

				if (jQuery('#rsm_suggestions_ol li').length) {
					jQuery.each(jQuery('#rsm_suggestions_ol > li'), function(){
						jQuery(this).remove();
					});
				}

				var is_available = false;
				var suggestions = response.split('|');
				for (var i=0; i<suggestions.length; i++) {
					if (suggestions[i] == what.val().trim()) {
						is_available = true;
					}

					var a = jQuery('<a>', {'href' : 'javascript: void(0);'});
					a.html(suggestions[i]);
					a.bind('click', function(){
						RSMembership.subscribe.add_username(jQuery(this).html());
					});

					var li = jQuery('<li>');
					li.append(a);

					jQuery('#rsm_suggestions_ol').append(li);
				}

				message.show('fast');
				var suggestions_container = jQuery('#rsm_suggestions');

				if (is_available)
				{
					suggestions_container.hide('fast');
					message.removeClass('rsm_error').addClass('rsm_ok');
					message.html(Joomla.JText._('COM_RSMEMBERSHIP_USERNAME_IS_OK'));
				}
				else
				{
					suggestions_container.css({'opacity': 1, 'filter' : 'alpha(opacity = 100)'}).fadeIn('fast');
					message.removeClass('rsm_ok').addClass('rsm_error');
					message.html(Joomla.JText._('COM_RSMEMBERSHIP_USERNAME_NOT_OK'));
				}

		});
	},

	add_username: function(username) {
		var message = jQuery('#rsm_username_message');

		jQuery('#rsm_username').val(username);
		jQuery('#rsm_suggestions').hide('fast');

		message.hide('fast');
		message.removeClass('rsm_error').addClass('rsm_ok');
		message.html(Joomla.JText._('COM_RSMEMBERSHIP_USERNAME_IS_OK'));
	},

	// Captcha functions
	refresh_captcha: function() {
		var url = RSMembership.subscribe.init.captcha_url.replace(/#SID#/, 'captcha' + RSMembership.utils.random());
		jQuery('#submit_captcha_image').attr('src', url);

		return false;
	},

	// Form validation function
	validate_subscribe: function(form) {
		var form = jQuery(form);
		var msg = new Array();

		// Clear the previous error fields
		form.find('.rsm_field_error').removeClass('rsm_field_error');

		// default validations: membershipterms, username, password, name
		if (RSMembership.subscribe.init.validations.length)
		{
			jQuery.each(RSMembership.subscribe.init.validations, function(i, validation) {
				if (typeof RSMembership.subscribe[validation] == 'function')
				{
					RSMembership.subscribe[validation](form, msg);
				}
			});
		}

		if (RSMembership.subscribe.init.field_validations.length)
		{
			jQuery.each(RSMembership.subscribe.init.field_validations, function(i, field) {
				field.required = parseInt(field.required);

				if (field.field_type == 'checkbox' || field.field_type == 'radio')
				{
					if (field.required) {
						var is_checked = false;
						for(var j = 0; j < field.field_id.length; j++)
						{
							if (form.find('#'+field.field_id[j]).is(':checked')){
								is_checked = true;
								break;
							}
						}

						if (!is_checked) {
							msg.push(field.err_msg);
						}
					}
				}
				else
				{
					if (field.required && form.find('#'+field.field_id).val().length == 0){
						msg.push(field.err_msg);
						form.find('#'+field.field_id).addClass('rsm_field_error');
					}

					if (typeof field.rule != 'undefined') {
						var field_value = form.find('#'+field.field_id).val();
						if (field_value.length > 0) {
							if (typeof RSMembership.subscribe[field.rule] == 'function')
							{
								var msg_set = (typeof field.err_msg_rule != 'undefined' ? field.err_msg_rule : field.err_msg);
								RSMembership.subscribe[field.rule](form, msg, field.field_id, msg_set);
							}
						}
					}
				}
			});
		}

		if (msg.length > 0) {
			// Build the error messages container
			var msg_container = jQuery('<div>', {
				'class': 'rsm_modal_error_container',
				'style': 'margin-top:20px;'
			});
			msg_container.append('<div class="alert alert-danger rsmemgrid-alert"><strong>'+Joomla.JText._('COM_RSMEMBERSHIP_THERE_WAS_AN_ERROR')+'</strong><ol><li>' + msg.join('</li><li>') + '</li></ol></div>');


			// Add it to the modal
			jQuery('#rsmembershipModal').empty().append(msg_container);

			// Force the modal to not be wider
			jQuery('#rsmembershipModal').width(msg_container.outerWidth());

			// Open the modal
			try {
				RSMembership.utils.magnificModal('#rsmembershipModal');
			} catch(err) {
				alert(msg.join("\n"));
			}

			return false;
		}

		return true;
	},

	numeric: function(form, msg, field_id, msg_set) {
		var regex = /^([0-9]{1,3}(?:,?[0-9]{3})*(?:\.[0-9]+?)?)$/;
		var value = form.find('#'+field_id).val();
		value = value.replace(/(?:\r\n|\r|\n)/g, '');

		if (!regex.test(value)) {
			msg.push(msg_set);
			form.find('#'+field_id).addClass('rsm_field_error');
		}
	},

	alpha: function(form, msg, field_id, msg_set) {
		var regex = /([^a-zA-Z ])/;
		var value = form.find('#'+field_id).val();
		value = value.replace(/(?:\r\n|\r|\n)/g, '');

		if (regex.test(value)) {
			msg.push(msg_set);
			form.find('#'+field_id).addClass('rsm_field_error');
		}
	},

	alphanumeric: function(form, msg, field_id, msg_set) {
		var regex = /([^a-zA-Z0-9 ])/;
		var value = form.find('#'+field_id).val();
		value = value.replace(/(?:\r\n|\r|\n)/g, '');

		if (regex.test(value)) {
			msg.push(msg_set);
			form.find('#'+field_id).addClass('rsm_field_error');
		}
	},

	email: function(form, msg, field_id, msg_set) {
		var regex=/.*@.*/;
		if (!regex.test(form.find('#'+field_id).val())) {
			msg.push(msg_set);
			form.find('#'+field_id).addClass('rsm_field_error');
		}
	},

	website: function(form, msg, field_id, msg_set) {
		var regex = /^(http|https):\/\/([\w-]+\.)+[\w-]+(\/[\w- ./?%&=]*)?$/;
		if (!regex.test(form.find('#'+field_id).val())) {
			msg.push(msg_set);
			form.find('#'+field_id).addClass('rsm_field_error');
		}
	},

	membershipterms: function(form, msg) {
		if (!form.find('#rsm_checkbox_agree').is(':checked') )
		{
			msg.push(Joomla.JText._('COM_RSMEMBERSHIP_PLEASE_AGREE_MEMBERSHIP'));
		}
	},

	username: function (form, msg) {
		if (!RSMembership.subscribe.validate_username(form.find('#rsm_username').val()))
		{
			msg.push(Joomla.JText._('COM_RSMEMBERSHIP_PLEASE_TYPE_USERNAME'));
			form.find('#rsm_username').addClass('rsm_field_error');
		}

		if (form.find('#rsm_username_message').attr('class') == 'rsm_error')
		{
			msg.push(Joomla.JText._('COM_RSMEMBERSHIP_USERNAME_NOT_OK'));
			form.find('#rsm_username').addClass('rsm_field_error');
		}
	},

	password: function (form, msg) {
		if (form.find('#rsm_password').val().length == 0)
		{
			msg.push(Joomla.JText._('COM_RSMEMBERSHIP_PLEASE_TYPE_PASSWORD'));
			form.find('#rsm_password').addClass('rsm_field_error');
		}
		else if (form.find('#rsm_password').val() != form.find('#rsm_password2').val())
		{
			msg.push(Joomla.JText._('COM_RSMEMBERSHIP_PLEASE_CONFIRM_PASSWORD'));
			form.find('#rsm_password2').addClass('rsm_field_error');
		}
	},

	name: function(form, msg) {
		if (form.find('#name').val().length == 0) {
			msg.push(Joomla.JText._('COM_RSMEMBERSHIP_PLEASE_TYPE_NAME'));
			form.find('#name').addClass('rsm_field_error');
		}

		var regex=/.*@.*/;
		if (form.find('#email').val().length == 0 || !regex.test(form.find('#email').val()))
		{
			msg.push(Joomla.JText._('COM_RSMEMBERSHIP_PLEASE_TYPE_EMAIL'));
			form.find('#email').addClass('rsm_field_error');
		}
	}
};


RSMembership.removeData = function(button) {
	jQuery(button).fadeOut({
		complete: function() {
            jQuery('#rsmembership_remove_data_and_close_account').fadeIn();
        }
	});
};

RSMembership.requestRemoveData = function(button) {
	jQuery(button).prop('disabled', true).addClass('disabled');
	var container = jQuery('#rsmembership_remove_data_and_close_account');

    var url = Joomla.getOptions('system.paths').root + '/index.php';
    var token = Joomla.getOptions('csrf.token');
    var data = {
        'option': 'com_rsmembership',
        'task': 'removedata.request'
    };
    data[token] = 1;
    jQuery.post(url, data, function(response){
    	container.fadeOut({
			complete: function() {
                container.find('.alert-warning').removeClass('alert-warning').addClass('alert-info');
                container.find('.alert').text(response);
                container.fadeIn();
			}
		})
    });
};

RSMembership.buildTotal = {
	format: '{price} {currency}',
	show_free: false,
	currency: '',
	iscoupon: false,
	delay_timer: null,

	remake_total: function (isPressed) {
		var total_field = jQuery('#rsm_grand_total');

		// if no total field found do not run
		if (total_field.length == 0) {
			return;
		}

		var total_value = parseFloat(total_field.data('fixedvalue'));

		// check if there is an extra value (this should be available only in one page checkout)
		var extras_total_value = 0;

		// change the percentage for the payments if extras are present
		var extras_present = false;

		// get all selected extras
		if (jQuery('.rsm_extra').length) {
			jQuery('.rsm_extra').each(function () {
				var element = jQuery(this);

				if (typeof element[0].type !== 'undefined') {
					switch (element[0].type) {
						case 'select-one':

							var price_value = element.find('option:selected').data('pricevalue');
							if (typeof price_value === 'undefined') {
								price_value = 0;
							}
							extras_total_value += parseFloat(price_value);
							break;

						case 'radio':
						case 'checkbox':
							if (element.is(':checked')) {
								extras_total_value += parseFloat(element.data('pricevalue'));
							}
							break;
					}
				}
			});

			if (extras_total_value > 0) {
				total_value += extras_total_value;
			}

			extras_present = true;
		}

		var selected_tax = 0;

		jQuery("input[id^='payment']").each(function(){
			// this means the initial total has changed and the taxes should be changed if percent is used
			if (extras_present || RSMembership.buildTotal.iscoupon) {
				var processor = jQuery(this).next().find('.rsm_tax_value');
				if (typeof processor !== 'undefined' && processor.data('ispercent')) {
					var percent_value = parseFloat(jQuery(this).next().find('.rsm_percent_value').text());

					// change the current rowvalue
					var new_tax = (total_value * percent_value) / 100;
					processor.data('rawvalue', new_tax);

					// display the with defined format
					var format_tax = RSMembership.buildTotal.format.replace('{price}', RSMembership.utils.number_format(new_tax));
					format_tax = format_tax.replace('{currency}', RSMembership.buildTotal.currency);
					processor.html(format_tax);
				} else if (typeof processor !== 'undefined' && !processor.data('ispercent') && processor.length) {
					var rawvalue =  processor.data('rawvalue');
					var new_tax = 0;
					if (total_value == 0) {
						processor.data('initialvalue', rawvalue);
					} else {
						if (processor.data('initialvalue')) {
							new_tax = processor.data('initialvalue');
						} else {
							new_tax = processor.data('rawvalue');
						}
					}
					// change the current rowvalue
					processor.data('rawvalue', new_tax);

					// display the with defined format
					var format_tax = RSMembership.buildTotal.format.replace('{price}', RSMembership.utils.number_format(new_tax));
					format_tax = format_tax.replace('{currency}', RSMembership.buildTotal.currency);
					processor.html(format_tax);

				}
			}

			if (jQuery(this).is(':checked')) {
				selected_tax = jQuery(this).next().find('.rsm_tax_value').data('rawvalue');
				selected_tax = typeof selected_tax !== 'undefined' ? parseFloat(selected_tax) : 0;
			}
			// bind the radios
			if (typeof isPressed === 'undefined') {
				jQuery(this).on('click', function(){
					RSMembership.buildTotal.remake_total(true);
				});
			}
		});

		total_value = total_value + selected_tax;

		if (total_value == 0 && RSMembership.buildTotal.show_free) {
			total_field.html(Joomla.Text._('COM_RSMEMBERSHIP_FREE'));
		} else {
			var format = RSMembership.buildTotal.format.replace('{price}', RSMembership.utils.number_format(total_value));
			format = format.replace('{currency}', RSMembership.buildTotal.currency);
			total_field.html(format);
		}
	},

	set_coupon: function(coupon, id) {
		if (coupon.length == 0) {
			return;
		}

		jQuery('#rsm_coupon_loading').show();
		if (RSMembership.buildTotal.timeout) {
			clearTimeout(RSMembership.buildTotal.timeout);
		}

		RSMembership.buildTotal.timeout = setTimeout(function() {
			jQuery.ajax({
				url: 'index.php?option=com_rsmembership&task=setcoupon',
				type: 'post',
				dataType: 'json',
				data: {membership_id: id, coupon: coupon}
			}).done(function( response ) {
				jQuery('#rsm_coupon_loading').hide();

				var coupon_input  = jQuery('#coupon');
				var discount = parseFloat(response.discount);
				if (discount > 0) {
					var total_field = jQuery('#rsm_grand_total');
					var total_value = parseFloat(total_field.data('fixedvalue'));
					total_field.data('initialvalue', total_value);

					total_value = total_value - discount;
					if (total_value < 0) {
						total_value = 0;
					}
					total_field.data('fixedvalue', total_value);

					RSMembership.buildTotal.iscoupon = true;

					RSMembership.buildTotal.remake_total();

					var format = RSMembership.buildTotal.format.replace('{price}', RSMembership.utils.number_format(discount));
					format = format.replace('{currency}', RSMembership.buildTotal.currency);

					jQuery('#rsm_discount_value').html(format);
					jQuery('#rsm_discount_value_container').show();
					jQuery('#rsm-coupon-ok').html(coupon_input.val());
					jQuery('#rsm-coupon-clear').show();
					coupon_input.hide();
				} else {
					coupon_input.addClass('rsm_coupon_error');
					RSMembership.buildTotal.clear_coupon();
				}
			});
		}, 1000);
	},

	clear_coupon: function(isPressed){
		if (typeof isPressed !== 'undefined') {
			jQuery('#rsm_coupon_loading').hide();

			var coupon  = jQuery('#coupon');
			jQuery('#rsm-coupon-ok').html('');
			jQuery('#rsm-coupon-clear').hide();
			coupon.removeClass('rsm_coupon_error');
			coupon.val('');
			coupon.show();
		}

		jQuery('#rsm_discount_value').html('');
		jQuery('#rsm_discount_value_container').hide();
		jQuery('#rsm-set-coupon').prop('disabled', false);

		var total_field = jQuery('#rsm_grand_total');
		if (total_field.data('initialvalue')) {
			var total_value_initial = parseFloat(total_field.data('initialvalue'));
			total_field.data('fixedvalue', total_value_initial);
			RSMembership.buildTotal.remake_total();
		}
		RSMembership.buildTotal.iscoupon = false;
	}
};