var type_inputs ='input[type="text"], input[type="hidden"], input[type="password"], input[type="checkbox"]:checked, input[type="radio"], select, textarea';
var steps_to_validate = ['identification', 'addresses', 'shipping', 'payment'];
var containers_to_validate = ['identification', 'addresses', 'shipping', 'payment', 'confirm'];

$(document).on('focus', '.remodal input, .remodal textarea, .poc_form input, .poc_form textarea, div.confirm_terms input', function(){
	$(this).closest('div.poc_form-group').removeClass('has-error').removeClass('has-error-simple').removeClass('poc_autocompleted');
});

$(document).on('change', '.remodal select, .poc_form select', function(){
	$(this).closest('div.poc_form-group').removeClass('has-error').removeClass('has-error-simple').removeClass('poc_autocompleted');
});

$(document).on('confirmation', '.remodal.login', function () {
	login();
});

$(document).on('confirmation', '.remodal.billing_address', function () {
	set_address_guest('payment_address');
});

$(document).on('confirmation', '.remodal.delivery_address', function () {
	set_address_guest('shipping_address');
});

$(document).on('confirmation', '.remodal.new_address', function () {
	new_address();
});

$(document).on('confirmation', '.remodal.register', function () {
	register();
});

var finishTypingInterval = 1000;
var typingTimer;

$(document).on('keyup', 'textarea[name="comment"]', function () {
	clearTimeout(typingTimer);
  	typingTimer = setTimeout(ajax_set_order_comment, finishTypingInterval);
});

$(document).on('keydown', 'textarea[name="comment"]', function () {
	clearTimeout(typingTimer);
});

window.setInterval(function(){
	validate_form();
}, 500);

function validate_form() {
	var container_error = _get_confirm_error_message();
	if(!container_error.attr("data-error_register"))
		container_error.hide();

	$('a.confirm_register_button').hide();

	var container_payment = _get_payment_info_container();
	container_payment.show();

	//First error - Form uncompleted
	if(!is_logged) {
		var form = _get_billing_form();
		var billing_form_correct = _validate_form(form, false);
		if (!billing_form_correct) {
            hide_payment_info(confirm_error_billing);
            return false;
        }

		var form = _get_delivery_form();
		var delivery_form_correct = _validate_form(form, false);
		if (!delivery_form_correct) {
            hide_payment_info(confirm_error_shipping);
            return false;
        }
	}

	//Second error - Not selected shipping method
	if(_get_shipping_method() == '') {
        hide_payment_info(confirm_error_shipping_method);
        return false;
    }

	//Third error - Not selected payment method
	if(_get_payment_method() == '') {
        hide_payment_info(confirm_error_payment_method);
        return false;
    }

	//Four error - Didnt accept therms and conditions
	var form = _get_confirm_form();
	var confirm_form_correct = _validate_form(form, false);
	if (!confirm_form_correct) {
		hide_payment_info(confirm_error_panel_confirm);
		return false;
	}

	if($('input[name="register"]').val() == 1) {
		$('a.confirm_register_button').show();

		if(!container_error.hasClass('error_register'))
			hide_payment_info('', true);
		else
			hide_payment_info(container_error.find('span.message').html(), false, true);

		return false;
	} else {
		$('a.confirm_register_button').hide();
	}
}

function register() {
	if(poc_modals_in_forms) {
        var modal_openned = $('div.remodal.register');
        var validate_address = _validate_form(modal_openned);
    }else{
        var modal_openned = _get_billing_form();
        var validate_address = true;
	}

	if(validate_address) {
        if (poc_modals_in_forms) {
            var inst = $('[data-remodal-id=modal_register]').remodal();
            var button_confirm = $('div.remodal.remodal-is-opened').find('button[data-remodal-action="confirm"]');
            var text_button_confirm = button_confirm.html();
        }

        var data = modal_openned.find(type_inputs).serialize();

        var container_payment_info = _get_payment_info_container();

        $.ajax({
            url: 'index.php?route=extension/module/perfect_one_checkout/ajax_register',
            data: data,
            type: "POST",
            dataType: 'json',
            beforeSend: function () {

            },
            success: function (data) {
                if (!data.error) {
                	if(!poc_modals_in_forms) {
                		if (data.redirect)
                            window.location.href = data.redirect;
                		else {
                            $('div.panel_addresses div.panel_poc-body').hide();
                            $('a.confirm_register_button').hide();
                            var payment_info_container = _get_payment_info_container();
                            payment_info_container.show();
                            $('input[name="register"]').val(0);
                            is_logged = 1;
                        }
                    } else {
                		if (data.redirect)
                            window.location.href = data.redirect;
                        else
                            location.reload();
					}
                }
                else {
                    hide_payment_info(data.message, false, true);
                    return false;
                }
            },
            error: function (error) {
                hide_payment_info(confirm_error_register, false, true);
                return false;
            }
        });
    }
}

function _get_shipping_method() {
	var radio_shipping = $('div.panel_shipping').find('input[name="shipping_method"]');

	if(!radio_shipping.length)
		return '';

	return radio_shipping.val();
}

function _get_payment_method() {
	var radio_payment = $('div.panel_payment').find('input[name="payment_method"]');
	if(!radio_payment.length)
		return '';

	return radio_payment.val();
}
function _get_confirm_error_message() {
	return $('div.panel_confirm div.confirm_error');
}

function same_address_checked() {
	var is_checked = $('input[name="shipping_address"]').is(':checked');
	return is_checked;
}

$(document).on('closed', '.remodal.privacy_policy', function () {
	var prev_modal_id = $('.remodal.privacy_policy').data('frommodal');
	var inst = $('[data-remodal-id='+prev_modal_id+']').remodal();
	inst.open();
});

$(document).on('ready', function(){
	construct_layout();

	if(poc_hide_uncompleted_panels == 1)
	{
		var some_complete_step = $('div.poc_steps div.step.completed').last();

		if(some_complete_step.length == 0)
			$('div.perfect_one_checkout_main_container div.panel_container:not(.panel_identification)').hide();
	}
	if(more_oc_2 == 0)
	{
		$(document).on('click', 'div.poc_alert button.close', function(){
			var alert_panel = $(this).parent('.poc_alert');

			alert_panel.fadeOut('fast', function(){
			});
		});
	}
	validate_addresses_on_ready();

	if(!poc_modals_in_forms)
	{
        $(document).on('change', 'div.poc_form.form_billing_address input, div.poc_form.form_billing_address select', function () {
            ajax_set_address_guest('payment_address');
            validate_addresses_no_modals(false);
        });
        $(document).on('change', 'div.poc_form.form_register input, div.poc_form.form_register select', function () {
            ajax_set_address_guest('payment_address');
            validate_addresses_no_modals(false);
        });
        $(document).on('change', 'div.poc_form.form_delivery_address input, div.poc_form.form_delivery_address select', function () {
            ajax_set_address_guest('shipping_address');
            validate_addresses_no_modals(false);
        });
	}

	//Devman Extensions - info@devmanextensions.com - 2017-11-30 21:32:10 - Remodal problem input focus in safari fix
		if (navigator.userAgent.match(/iPhone|iPad|iPod/i)) {
	        $(document).on('opened', '.remodal', function (e) {

	            $('.remodal-wrapper')
	            .css({
	                position: 'absolute',
	                marginTop: $(window).scrollTop() + 'px',
	                bottom: 'auto'
	            });

	            setTimeout(function () {
	                $('.remodal-overlay').css({
	                    position: 'absolute',
	                    top: 0,
	                    left: 0,
	                    width: '100%',
	                    height: Math.max(
	                    document.body.scrollHeight, document.documentElement.scrollHeight,
	                    document.body.offsetHeight, document.documentElement.offsetHeight,
	                    document.body.clientHeight, document.documentElement.clientHeight
	                ) + 'px'
	                });
	            }, 0);


	        });
	    }
	//END
});

function hide_payment_info(message, hide_message, error_register) {
	var container_error = _get_confirm_error_message();
	var container_error_message = container_error.find('span.message');
	var link = container_error.find('a');

	hide_message = typeof hide_message == 'undefined' ? false : hide_message;
	error_register = typeof error_register == 'undefined' ? false : true;

	if(error_register)
		container_error.addClass('error_register');
	else
		container_error.removeClass('error_register');

	container_error_message.html(message);

	if(hide_message)
		container_error.hide();
	else
		container_error.show();

	var payment_info_container = _get_payment_info_container();

	payment_info_container.hide();
}


function new_address()
{
	var modal_openned = $('div.remodal.new_address')
	var validate_address = _validate_form(modal_openned);

	if(validate_address)
	{
		var inst = $('[data-remodal-id=modal_new_address]').remodal();
		var button_confirm = $('div.remodal.remodal-is-opened').find('button[data-remodal-action="confirm"]');
		var text_button_confirm = button_confirm.html();
		var data = modal_openned.find(type_inputs).serialize();

		$.ajax({
			url: 'index.php?route=extension/module/perfect_one_checkout/ajax_new_address',
			data: data,
			type: "POST",
			dataType: 'json',
			beforeSend:function()
			{
				button_confirm.html('<i class="fa fa-refresh fa-spin" aria-hidden="true"></i>');
				button_confirm.attr('disabled', 'disabled');
			},
			success: function(data) {
				if(!data.error)
				{
					if(data.redirect)
						window.location.href = data.redirect;
					else
						location.reload();
				}
				else
				{
					_restore_button(button_confirm, text_button_confirm);
					_insert_alert_in_modal(modal_openned, data.message);
				}
			},
			error: function(data) {
				_restore_button(button_confirm, text_button_confirm);
			},
		});
	}
}

function login()
{
	var modal_openned = $('.remodal.login');

	//Devman Extensions - info@devmanextensions.com - 2017-02-21 20:09:04 - Test errors
		var error = false;
		var input_email = modal_openned.find('input[name="email"]');
		var input_email_val = input_email.val();

		var input_password = modal_openned.find('input[name="password"]');
		var input_password_val = input_password.val();

		if(input_email_val == '')
		{
			_put_input_error(input_email);
			error = true;
		}
		if(input_password_val == '')
		{
			_put_input_error(input_password);
			error = true;
		}
	//END

	if(!error)
	{
		var inst = $('[data-remodal-id=modal_login]').remodal();
		var button_confirm = $('div.remodal.remodal-is-opened').find('button[data-remodal-action="confirm"]');
		var text_button_confirm = button_confirm.html();

		var data = {
			email: input_email_val,
			password: input_password_val
		};

		$.ajax({
			url: 'index.php?route=extension/module/perfect_one_checkout/ajax_login',
			data: data,
			type: "POST",
			dataType: 'json',
			beforeSend:function()
			{
				button_confirm.html('<i class="fa fa-refresh fa-spin" aria-hidden="true"></i>');
				button_confirm.attr('disabled', 'disabled');
			},
			success: function(data) {
				if(!data.error)
					location.reload();
				else
				{
					_restore_button(button_confirm, text_button_confirm);
					_insert_alert_in_modal(modal_openned, data.message);
				}
			},
			error: function(data) {
				_restore_button(button_confirm, text_button_confirm);
			},
		});
	}
}


function validate_addresses_on_ready()
{
	if(!is_logged)
	{
		var same_address = $('input[name="shipping_address"]').is(':checked');

		var billing_address_modal = poc_modals_in_forms ? $('div.remodal.billing_address') : $('div.panel_container.panel_addresses div.poc_form.form_billing_address');
		var validate_billing_address = _validate_form(billing_address_modal, false);

		var delivery_address_modal = poc_modals_in_forms ? $('div.remodal.delivery_address') : $('div.panel_container.panel_addresses div.poc_form.form_delivery_address');
		var validate_delivery_address = _validate_form(delivery_address_modal, false);

		var validate_step_addresses = (same_address && validate_billing_address) || (!same_address && validate_billing_address && validate_delivery_address);
		if(validate_step_addresses)
			_complete_step('addresses');

		_clean_form_of_validate_errors(billing_address_modal);
		_clean_form_of_validate_errors(delivery_address_modal);
		ajax_get_payment_info();
	}
}
function guest()
{
    $('div.show_on_guest').fadeIn('fast');
    $('input[name="guest"]').val(1);
    $('input[name="register"]').val(0);

    if(!poc_modals_in_forms){
        var guest_payment_form = $('div.poc_form.form_billing_address');
        var register_form = $('div.poc_form.form_register');
        guest_payment_form.show();
        register_form.hide();
    }
    var button_guest = $('div.panel_identification').find('button.button_guest');
    button_guest.attr('disabled', 'disabled');

    var button_register = $('div.panel_identification').find('button.button_register');
    button_register.removeAttr('disabled', 'disabled');

    _complete_step('identification');

    $('div.panel_addresses span.not_address').remove();

    $.ajax({
        url: 'index.php?route=extension/module/perfect_one_checkout/ajax_set_guest',
        type: "POST",
        dataType: 'json'
    });
}

//Only call when modals are disabled
function register_mode()
{
	var guest_payment_form = $('div.poc_form.form_billing_address');
    var register_form = $('div.poc_form.form_register');

    guest_payment_form.hide();
    register_form.show();

    $('input[name="guest"]').val(0);
    $('input[name="register"]').val(1);

    var button_register = $('div.panel_identification').find('button.button_register');
    button_register.attr('disabled', 'disabled');

    var button_guest = $('div.panel_identification').find('button.button_guest');
    button_guest.removeAttr('disabled', 'disabled');

    _complete_step('identification');

    $('div.panel_addresses span.not_address').remove();

    $.ajax({
        url: 'index.php?route=extension/module/perfect_one_checkout/ajax_set_register',
        type: "POST",
        dataType: 'json'
    });
}

function set_address(select_address)
{
	var select_name = select_address.attr('name');
	var address_id = select_address.val();

	$.ajax({
		url: 'index.php?route=extension/module/perfect_one_checkout/ajax_set_address',
		data: {
			select_name: select_name,
			address_id : address_id
		},
		type: "POST",
		dataType: 'json',
		success: function(data) {
			if($(window).width() <= 768)
				$("html, body").animate({ scrollTop: $('div.panel_container.panel_addresses').offset().top - 50 }, 100);

			if(select_name == 'shipping_address')
				ajax_get_shipping_methods();
			else if(select_name == 'payment_address')
				ajax_get_payment_methods();
		}
	});
}

function set_address_guest(type_address)
{
	var real_class_modal = type_address == 'shipping_address' ? 'delivery' : 'billing';

    if(poc_modals_in_forms) {
        var inst = $('[data-remodal-id=modal_' + real_class_modal + '_address]').remodal();
        var modal_openned = $('div.remodal.' + real_class_modal + '_address');
    }
    else {
        var modal_openned = $('div.panel_container.panel_addresses div.poc_form.form_' + real_class_modal + '_address');
    }
    var same_address = $('input[name="shipping_address"]').is(':checked');

	var validate_address = _validate_form(modal_openned);

	if(validate_address)
	{
		var address_data = modal_openned.find(type_inputs).serialize();

		$.ajax({
			url: 'index.php?route=extension/module/perfect_one_checkout/ajax_set_address_guest',
			data: address_data,
			type: "POST",
			dataType: 'json',
			success: function(data) {
				var modal_openned = poc_modals_in_forms ? $('div.remodal.billing_address') : $('div.panel_container.panel_addresses div.poc_form.form_billing_address');
				var validate_billing_address = _validate_form(modal_openned);

				if(type_address == 'shipping_address')
				{
					ajax_get_shipping_methods();

					//Validate billing address also
						if(validate_billing_address)
							_complete_step('addresses');
					//END
				}
				else if(type_address == 'payment_address')
				{
					ajax_get_payment_methods();
					if(same_address && validate_billing_address)
					{
						ajax_get_shipping_methods();
						_complete_step('addresses');
					}
				}

                if(poc_modals_in_forms) {
                    inst.close();
                    if ($(window).width() <= 768)
                        $("html, body").animate({scrollTop: $('div.panel_container.panel_addresses').offset().top - 50}, 100);
                }
			}
		});
	}
}
//Devman Extensions - info@devmanextensions.com - 5/12/17 9:28 - Only call this when modals are disabled
function ajax_set_address_guest(type_address)
{
	var register = $('input[name="register"]').val() == 1;

    var class_container = type_address == 'shipping_address' ? 'delivery_address' : (register ? 'register' : 'billing_address');
    var modal_openned = $('div.panel_container.panel_addresses div.poc_form.form_' + class_container);
    var address_data = modal_openned.find(type_inputs).serialize();

    $.ajax({
        url: 'index.php?route=extension/module/perfect_one_checkout/ajax_set_address_guest',
        data: address_data,
        type: "POST",
        dataType: 'json',
        success: function(data) {
        	//Get shipping methods if selected country and zone
			var also_check_shipping_methods = false;

            var country_id = modal_openned.find('select[name="country_id"]').val();
            var zone_id = modal_openned.find('select[name="zone_id"]').val();
			var exists_zone_id = modal_openned.find('select[name="zone_id"]').length;

			var get_methods = country_id != '' && (!exists_zone_id || (exists_zone_id && zone_id != ''));

            if(type_address == 'payment_address' && get_methods) {
                	ajax_get_payment_methods();
                var also_check_shipping_methods = $('input[name="shipping_address"]').is(':checked');
            }
            if((type_address == 'shipping_address' || also_check_shipping_methods) && get_methods) {
                    ajax_get_shipping_methods();
            }
        }
    });
}

function ajax_get_shipping_methods(skip)
{
	var shipping_methods_container = $('div.panel_shipping').find('div.panel_poc-body');
	$.ajax({
		url: 'index.php?route=extension/module/perfect_one_checkout/ajax_get_shipping_methods',
		type: "POST",
		dataType: 'json',
		beforeSend:function()
		{
			_block_panel_loading(shipping_methods_container);
		},
		success: function(data) {
			_unblock_panel_loading(shipping_methods_container);
			shipping_methods_container.html(data.data);
			ajax_update_cart();
		},
		error: function() {
		}
	});
}

function set_shipping_method(radio_shipping_method)
{
	var shipping_method = radio_shipping_method.val();
	if(shipping_method != '')
	{
		$.ajax({
			url: 'index.php?route=extension/module/perfect_one_checkout/ajax_set_shipping_method',
			data: {
				shipping_method: shipping_method
			},
			type: "POST",
			dataType: 'json',
			beforeSend: function() {
				_disable_payment_info_zone();
			},
			success: function(data) {
				ajax_update_cart();
			}
		});
		_complete_step('shipping');
	}
	else
		_uncomplete_step('shipping');
}

function ajax_get_payment_methods()
{
	var payment_methods_container = $('div.panel_payment').find('div.panel_poc-body');

	$.ajax({
		url: 'index.php?route=extension/module/perfect_one_checkout/ajax_get_payment_methods',
		type: "POST",
		dataType: 'json',
		beforeSend:function()
		{
			_block_panel_loading(payment_methods_container);
		},
		success: function(data) {
			_unblock_panel_loading(payment_methods_container);
			payment_methods_container.html(data.data);

			var payment_method_selected = $('div.panel_payment input[name="payment_method"]').val();

			if(!payment_method_selected || payment_method_selected == '')
				_uncomplete_step('payment');
			else
				ajax_get_payment_info();
		},
		error: function() {
			_unblock_panel_loading(payment_methods_container);
		},
	});
}

function ajax_get_payment_info(from_cart)
{
	from_cart = typeof(from_cart) == 'undefined' ? '' : from_cart;
	var payment_info_container = _get_payment_info_container();
	var payment_method_code = $('input[name="payment_method"]:checked').val();

	if(payment_method_code)
	{
		$.ajax({
			url: 'index.php?route=extension/module/perfect_one_checkout/ajax_get_payment_info',
			data: {
				payment_method_code: payment_method_code
			},
			type: "POST",
			dataType: 'json',
			beforeSend:function()
			{
				_disable_payment_info_zone();
			},
			success: function(data) {
				_enable_payment_info_zone();

				if(!data.error)
				{
					payment_info_container.html(data.data);
					if(!from_cart)
						ajax_update_cart();
				}
			},
			error: function() {
				_enable_payment_info_zone();
			},
		});
	}
}

function set_payment_method(radio_payment_method)
{
	var payment_method = radio_payment_method.val();

	if(payment_method != '')
	{
		$.ajax({
			url: 'index.php?route=extension/module/perfect_one_checkout/ajax_set_payment_method',
			data: {
				payment_method: payment_method
			},
			type: "POST",
			dataType: 'json',
			beforeSend: function()
			{
				_disable_payment_info_zone();
			},
			success: function(data) {
				_complete_step('payment');
				ajax_get_payment_info();
				_enable_payment_info_zone();
			},
			error: function ()
			{
				_enable_payment_info_zone();
			}
		});

	}
	else
		_uncomplete_step('payment');
}

function validate_steps() {
	var error = false;
	$.each(steps_to_validate, function (key, step_name) {
		var step_container = $('div.poc_steps div.step.' + step_name);
		var panel_container = $('div.panel_' + step_name);
		var validate_step = step_container.hasClass('completed');

		if (!validate_step) {
			errors = true;
			step_container.addClass('error');
			panel_container.addClass('error');
			_show_error_complete_steps_message();
		}
	});

	if(!error)
		error = _validate_form($('div.panel_confirm'));

	return error;
}


function validate_addresses_no_modals(show_errors)
{
	var billing_address = _get_billing_form();
	var billing_validate =_validate_form(billing_address, show_errors);

    var same_address = $('input[name="shipping_address"]').is(':checked');

    if(!same_address) {
        var delivery_address = _get_delivery_form();
        var delivery_validate = _validate_form(delivery_address, show_errors);
    }
    else
        delivery_validate = billing_validate;

    if(!billing_validate || !delivery_validate)
        _uncomplete_step('addresses');
    else
        _complete_step('addresses');
}

function ajax_set_terms_accepted(checked)
{
	var datas = {
		checked : checked
	};

	_simple_ajax('index.php?route=extension/module/perfect_one_checkout/ajax_set_terms_accepted', datas);
}

function ajax_set_order_comment () {
	var comment = $('div.panel_confirm textarea[name="comment"]').val();
	$.ajax({
		url: 'index.php?route=extension/module/perfect_one_checkout/ajax_set_order_comment',
		type: "POST",
		dataType: 'json',
		data: {
			comment: comment
		},
		success: function (data) {
		},
		error: function () {
		}
	});
}


function same_address(checkbox)
{
	var checked = checkbox.is(":checked");
	var button_delivery = $('button.delivery_address');
    var button_billing = $('button.billing_address');
    var modal_address = poc_modals_in_forms ? $('div.remodal.billing_address') : $('div.panel_container.panel_addresses div.form_billing_address');
    var h2_same_addresses = modal_address.find((poc_modals_in_forms ? 'h2':'h3')+'.sames_addresses');
    var h2_differents_addresses = modal_address.find((poc_modals_in_forms ? 'h2':'h3')+'.differents_addresses');

    if(poc_modals_in_forms) {
        var buttons_delivery_and_billing = $('button.delivery_address, button.billing_address').parent('div');
        var buttons_same_delivery_billing = $('div.same_address_container');
    }else{
    	var delivery_form = $('div.panel_container.panel_addresses div.poc_form.form_delivery_address');
	}

	if(checked)
	{
		if(poc_modals_in_forms) {
            buttons_delivery_and_billing.fadeOut('fast', function () {
                buttons_same_delivery_billing.fadeIn('fast');
            });
        }else{
            delivery_form.hide();
		}

		h2_same_addresses.show();
		h2_differents_addresses.hide();

		if(poc_modals_in_forms)
		{
            var billing_address_modal = $('div.remodal.billing_address');
            var validate_address = _validate_form(billing_address_modal);
            _clean_form_of_validate_errors(billing_address_modal);
            //If validate billing address complete step addresses and update shipping methods
            if(validate_address)
            {
                _complete_step('addresses');
            }
            else //If not validate billing address uncumplete billing step and show modal of billing and delivery form
            {
                _uncomplete_step('addresses');
                var inst = $('[data-remodal-id=modal_billing_address]').remodal();
                inst.open();
            }
        }
	}
	else
	{
		if(poc_modals_in_forms) {
            buttons_same_delivery_billing.fadeOut('fast', function () {
                buttons_delivery_and_billing.fadeIn('fast');
            });
        }else {
            delivery_form.show();
		}

		h2_same_addresses.hide();
		h2_differents_addresses.show();

        if(poc_modals_in_forms) {
            var billing_address_modal = $('div.remodal.billing_address')
            var validate_billing_address = _validate_form(billing_address_modal);
            _clean_form_of_validate_errors(billing_address_modal);
            var delivery_address_modal = $('div.remodal.delivery_address');
            var validate_delivery_address = _validate_form(delivery_address_modal);
            _clean_form_of_validate_errors(delivery_address_modal);

            if (!validate_billing_address || !validate_delivery_address) {
                _uncomplete_step('addresses');
            }
        }
	}

	if(!poc_modals_in_forms)
        validate_addresses_no_modals(false);

	$.ajax({
		url: 'index.php?route=extension/module/perfect_one_checkout/ajax_same_address',
		data: {checked: checked},
		type: "POST",
		dataType: 'json',
		success: function(data) {
            var form = checked ? _get_billing_form() : _get_delivery_form();
            var address_data = form.find(type_inputs).serialize();
			_simple_ajax('index.php?route=extension/module/perfect_one_checkout/ajax_same_address_update_address', address_data, 'ajax_get_shipping_methods');
		},
	});
}

function _get_billing_form()
{
	if(!poc_modals_in_forms)
	{
        var register = $('input[name="register"]').val() == 1;
        if(register)
        	return $('div.poc_form.form_register');
        else {
            return $('div.poc_form.form_billing_address');
        }
	}
	else
	{
        return $('div.remodal.billing_address');
	}
}
function _get_delivery_form()
{
    var same_address = same_address_checked();

    if(same_address)
	{
		delivery_form = _get_billing_form();
		return delivery_form;
	}
	else {
        if (!poc_modals_in_forms) {
        	return $('div.poc_form.form_delivery_address');
        }
        else {
            return $('div.remodal.delivery_address');
        }
    }
}
function _get_confirm_form() {
	return $('div.panel_confirm div.panel_poc-body');
}
function _get_payment_info_container()
{
	return $('div.perfect_one_checkout_main_container div.panel_confirm div.payment_info');
}
function _get_main_container()
{
	return $('div.perfect_one_checkout_main_container');
}
function _get_cart_container() {
	return $('div.panel_cart').find('div.panel_poc-body');
}
function _get_panel_container_selector(container_class)
{
	return $('div.perfect_one_checkout_main_container div.panel_'+container_class);
}
function _simple_ajax(url, data, function_after_success)
{
	$.ajax({
		url: url,
		data: data,
		type: "POST",
		dataType: 'json',
		success: function (data) {
			if (function_after_success && typeof window[function_after_success] === 'function'){
		        window[function_after_success]();
		    }
		}
	});
}

function ajax_get_zones(country_select, zone_id)
{
	zone_id = typeof(zone_id) == 'undefined' ? '' : zone_id;
	var modal_openned = !poc_modals_in_forms && !country_select.closest('div.remodal').hasClass('new_address') ? country_select.closest('div.poc_form') : country_select.closest('div.remodal_container');
	var zones_select = modal_openned.find('select[name="zone_id"]');
	var country_id = country_select.val();
	var option_empty = '<option value="">'+zones_select.find('option[value=""]').text()+'</option>';
	var no_zones = '<option selected value="0">'+none_state+'</option>';

	if(country_id == '')
	{
		zones_select.html(option_empty);
		return true;
	}

	$.ajax({
		url: 'index.php?route=checkout/checkout/country&country_id='+country_id,
		type: "POST",
		dataType: 'json',
		beforeSend:function()
		{
		},
		success: function(data) {
			if(data.zone.length == 0)
			{
				var html_select_zone = option_empty
				html_select_zone += no_zones;
				zones_select.html(html_select_zone);
			}
			else
			{
				var html_select_zone = option_empty
				$.each(data.zone, function( key, value ) {
					html_select_zone += '<option value="'+value.zone_id+'">'+value.name+'</option>';
				});
				zones_select.html(html_select_zone);

				if(zone_id != '')
					zones_select.val(zone_id).trigger('change');
			}
		},
		error: function(data) {

		},
	});
}


function _disable_payment_info_zone()
{
	var panel_info_container = _get_payment_info_container();
	_block_panel_loading(panel_info_container);
}

function _enable_payment_info_zone()
{
	var panel_info_container = _get_payment_info_container();
	_unblock_panel_loading(panel_info_container);
}

function _restore_button(button, message)
{
	button.removeAttr('disabled');
	button.html(message);
}


function _put_input_error(input)
{
	if(!poc_popup_form_validations)
		input.closest('div.poc_form-group').addClass('has-error');
	else
		input.closest('div.poc_form-group').addClass('has-error-simple');

}
function _remove_input_error(input)
{
	input.closest('div.poc_form-group').removeClass('has-error');
	input.closest('div.poc_form-group').removeClass('has-error-simple');
}
function _show_input_error_message(input)
{
	input.closest('div.poc_form-group').find('span.error_message').show();
}
function _hide_input_error_message(input)
{
	input.closest('div.poc_form-group').find('span.error_message').hide();
}

function _complete_step(step_class)
{
	var step = $('div.poc_steps').find('div.step.'+step_class);
	step.addClass('completed');

	var panel = $('div.panel_'+step_class);
	panel.removeClass('error');

	if(step_class == 'identification')
		var panel_next = $('div.panel_addresses');
	else if(step_class == 'addresses')
		var panel_next = $('div.panel_shipping');
	else if(step_class == 'shipping')
		var panel_next = $('div.panel_payment');
	else if(step_class == 'payment')
		var panel_next = $('div.panel_confirm');

	panel_next.fadeIn('fast');
}

function _uncomplete_step(step_class)
{
	var step = $('div.poc_steps').find('div.step.'+step_class);
	step.removeClass('completed');
}

function _insert_alert_in_modal(modal, message, class_alert)
{
	modal.find('div.poc_alert').remove();
	var modal_container = modal.find('div.remodal_container');

	if(typeof(class_alert) == 'undefined')
		class_alert = 'danger';

	var alert_html = '<div class="poc_alert poc_alert-'+class_alert+'" role="alert"><button type="button" class="poc_close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button><i class="fa fa-warning"></i><span class="message">'+message+'</span></div>';

	modal_container.after(alert_html);
}

function _insert_alert_manual(container, message, class_alert, position, no_margin_bottom)
{
    position = typeof(class_alert) == 'undefined' ? 'inside' : position;
    no_margin_bottom = typeof(no_margin_bottom) == 'undefined' ? '' : 'style="margin-bottom: 0px !important;"';

    if(position == 'inside')
		container.find('div.poc_alert_container').remove();
    else if(position == 'before')
	{
		if(container.prev().hasClass('poc_col-12') && container.prev('.poc_col-12').find('div.poc_alert').length)
            container.prev().remove();
	}

	icon = 'warning';

	if(typeof(class_alert) == 'undefined')
	{
        class_alert = 'danger';
    }

    if(class_alert == 'success')
	{
		icon= 'check';
	}

	var alert_html = '<div class="poc_col-md-12 poc_alert_container"><div '+no_margin_bottom+' class="poc_alert poc_alert-'+class_alert+'" role="alert"><button type="button" class="poc_close" data-dismiss="alert" aria-label="Close" onclick="$(this).closest(\'div.poc_alert_container\').remove();"><span aria-hidden="true">&times;</span></button><i class="fa fa-'+icon+'"></i><span class="message">'+message+'</span></div></div>';

    if(position == 'inside')
        container.prepend(alert_html);
    else if(position == 'before')
        container.before(alert_html);
}

function _show_error_complete_steps_message()
{
	if(!is_logged) {
		var form = _get_billing_form();
		_validate_form(form, true);

		var form = _get_delivery_form();
		_validate_form(form, true);
	}

	var panel_error = $('div.panel_confirm').find('div.poc_alert.confirm_error');

	panel_error.show();

	var go_to = $('div.poc_steps').length && $(window).width() > 633 ? $('div.poc_steps') : $('div.panel_identification');

	setTimeout(function(){
		$('html, body').animate({
	        scrollTop: go_to.offset().top - 25
	    }, 800);
	},0);
}

function _validate_form(form_container, show_errors) {
	var show_errors = typeof show_errors != 'undefined' ? show_errors : true;

	var elements_to_validate = ['input', 'select', 'textarea'];
	var validate = true;
	var errors_string = '<ul class="poc_error_list">';

	$.each( elements_to_validate, function( key, element ) {
		form_container.find(element).each(function(){
			var input = $(this);
			var validation_rule = input.data('validationrule');
			//input.closest('div.poc_form-group').removeClass('has-error').removeClass('has-error-simple');
			if(validation_rule)
			{
				var input_type = input.attr('type');
				var input_name = input.attr('name');

				var input_value = input.val();
				var input_length = parseInt(input_value.length);

				var is_custom_field = input.parents('div.poc_form-group').hasClass('custom_field');

				input_error = false;
				if(validation_rule == 'not_empty' && input_value == '')
					input_error = true;
				else if(validation_rule == 'between_1_32' && (input_length < 1 || input_length > 32))
					input_error = true;
				else if(validation_rule == 'between_2_10' && (input_length < 2 || input_length > 10))
					input_error = true;
				else if(validation_rule == 'between_3_32' && (input_length < 3 || input_length > 32))
					input_error = true;
				else if(validation_rule == 'between_4_20' && (input_length < 4 || input_length > 20))
					input_error = true;
				else if(validation_rule == 'between_2_128' && (input_length < 2 || input_length > 128))
					input_error = true;
				else if(validation_rule == 'between_3_128' && (input_length < 3 || input_length > 128))
					input_error = true;
				else if(validation_rule == 'valid_email' && !_validate_email(input_value))
					input_error = true;

				//Exception to password confirm
					if(!input_error && input_type == 'password' && input_name == 'confirm' && form_container.find('input[name="password"]') && form_container.find('input[name="password"]').val() != input_value)
						input_error = true;
				//END

				//Exception to checkbox inputs
					if(input_type =='checkbox' && !is_custom_field && !input.is(':checked'))
						input_error = true;
				//END

				//Exception to radio inputs
					if(input_type =='radio' || (input_type =='checkbox' && is_custom_field))
					{
						//Foreach all radios with same name and check if some of this radios is checked
						var container_inputs = input.parents('div.poc_form-group');

						input_error = true;

						container_inputs.find('input[type="'+input_type+'"]').each(function(){
							if($(this).is(':checked'))
								input_error = false;
						});
					}
				//END

				if(input_error)
				{
					if(show_errors)
						_put_input_error(input);

                    if(show_errors && !poc_popup_form_validations) {
                        _show_input_error_message(input);
                    } else if(show_errors && poc_popup_form_validations){
						var error_message = input.closest('div.poc_form-group').find('span.error_message').html();
						errors_string += '<li>'+error_message+'</li>';
					}
					validate = false;
				}
			}
		});
	});

	if(!validate && show_errors && poc_popup_form_validations && errors_string != '') {
		errors_string = errors_string + '</ul>';
		$('[data-remodal-id=modal_form_validations]').find('div.remodal_container').html(errors_string);
		var inst = $('[data-remodal-id=modal_form_validations]').remodal();
		inst.open();
	}
	return validate;
}

function _clean_form_of_validate_errors(form_container)
{
	var elements_to_clean = ['input', 'select', 'textarea'];
	var validate = true;

	$.each( elements_to_clean, function( key, element ) {
		form_container.find(element).each(function(){
			var input = $(this);
			_remove_input_error(input);
			_hide_input_error_message(input);
		});
	});
}

function _check_term_accepted()
{
	var checkbox = $('div.confirm_terms').find('input[type="checkbox"]');

	if(!checkbox)
		return true;

	var form_validated = _validate_form($('div.panel_confirm'));
	if(!form_validated)
		return false;
	else
		return true;
}
function _validate_email(email) {
	var regex = /^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
	return regex.test(email);
}

function _block_panel_loading(panel)
{
	var panel_height = panel.height();
	panel.height(panel_height);
	panel.addClass('loading');
}

function _unblock_panel_loading(panel)
{
	panel.css('height', 'auto').removeClass('loading');
}

function _autocomplete_field(field, value, add_class)
{
	field.val(value);
	_put_autocompleted_class(field);
}

function _put_autocompleted_class(field)
{
	field.closest('div.poc_form-group').addClass('poc_autocompleted');
}

function cart_change_quantity(button, operation)
{
	var input = button.closest('td.quantity_td').find('input');
	var current_quantity = parseInt(input.val());
	var from_small_table = button.closest('table').hasClass('small-only');

	if(operation == '+')
		input.val(current_quantity+1);
	else
		input.val(current_quantity-1);

	ajax_update_cart(true, from_small_table);
}

function cart_delete_product(button)
{
	var tr = button.closest('tr');
	tr.hide();

	var input = button.closest('td.quantity_td').find('input');
	input.val(0);

	var from_small_table = button.closest('table').hasClass('small-only');

	ajax_update_cart(true, from_small_table);
}

function cart_delete_insert_error(error)
{
	error_in_cart = true;
	var button_confirm_order = $('a.confirm_order_button');
	button_confirm_order.attr('disabled', 'disabled');

	var table_cart = $('form#cart_info');
	_insert_alert_manual(table_cart, error);
}

function ajax_update_cart(get_shipping_payment_methods, from_small_table)
{
	error_in_cart = false;
	var cart_container = $('div.panel_cart').find('div.panel_poc-body');
	var cart_heading = $('div.panel_cart').find('div.panel-heading span.cart_heading');

	if(from_small_table)
		var data = $('div.panel_cart').find('form#cart_info table.small-only input');
	else
		var data = $('div.panel_cart').find('form#cart_info table.large-only input');

	$.ajax({
		url: 'index.php?route=extension/module/perfect_one_checkout/ajax_update_cart',
		data: data,
		type: "POST",
		dataType: 'json',
		beforeSend:function()
		{
			_disable_payment_info_zone();
			_block_panel_loading(cart_container);
		},
		success: function(data) {
			_unblock_panel_loading(cart_container);

			if(data.html != '')
			{
				//Heading
					if(data.heading != '')
						cart_heading.html(data.heading);
				//END

				cart_container.html(data.html);

				//Devman Extensions - info@devmanextensions.com - 2017-09-21 19:04:40 - Update cart module information
				if(more_oc_2)
				{
					$('#cart-total').html(data.total);
					$('#cart > button').html('<span id="cart-total"><i class="fa fa-shopping-cart"></i> ' + data.total + '</span>');
					$('#cart > ul').load('index.php?route=common/cart/info ul li');
				}

				if(more_oc_2 == 0)
					$('#cart-total').html(data.total);

				if(typeof get_shipping_payment_methods != 'undefined')
				{
					ajax_get_shipping_methods();
					ajax_get_payment_methods();
				}

				_enable_payment_info_zone();
				ajax_get_payment_info(true);
			}
			else
				window.location.href = data.redirect;
		},
		error: function(data) {
			_unblock_panel_loading(cart_container);
			_enable_payment_info_zone();
		},
	});
}

function apply_coupon(coupon_code)
{
	var discount_container = $('div.discount_zone');
	$.ajax({
		url: url_coupon,
		data: {coupon : coupon_code},
		type: "POST",
		dataType: 'json',

		beforeSend:function() {
			_disable_payment_info_zone();
		},
		success: function(data) {
			if(data.error)
				_insert_alert_manual(discount_container, data.error);
			else
				ajax_update_cart(true);

			_enable_payment_info_zone();
		},
		error: function(data) {
			_enable_payment_info_zone();
		},
	});
}

function apply_reward(reward)
{
	var discount_container = $('div.discount_zone');
	$.ajax({
		url: url_reward,
		data: {reward : reward},
		type: "POST",
		dataType: 'json',

		beforeSend:function() {
			_disable_payment_info_zone();
		},
		success: function(data) {
			if(data.error)
				_insert_alert_manual(discount_container, data.error);
			else
				ajax_update_cart(true);

			_enable_payment_info_zone();
		},
		error: function(data) {
			_enable_payment_info_zone();
		},
	});
}


function apply_voucher(voucher_code)
{
	var discount_container = $('div.discount_zone');
	$.ajax({
		url: url_voucher,
		data: {voucher : voucher_code},
		type: "POST",
		dataType: 'json',
		beforeSend:function() {
			_disable_payment_info_zone();
		},
		success: function(data) {
			if(data.error)
				_insert_alert_manual(discount_container, data.error);
			else
				ajax_update_cart(true);

			_enable_payment_info_zone();
		},
		error: function(data) {
			_enable_payment_info_zone();
		},
	});
}

function remove_cart_discount(type)
{
	var discount_container = $('div.discount_zone');
	$.ajax({
		url: 'index.php?route=extension/module/perfect_one_checkout/ajax_remove_cart_discount',
		data: {type : type},
		type: "POST",
		dataType: 'json',

		beforeSend:function() {
			_disable_payment_info_zone();
		},
		success: function(data) {
			ajax_update_cart(true);
			_enable_payment_info_zone();
		},
		error: function(data) {
			_enable_payment_info_zone();
		},
	});
}

function construct_layout()
{
	var poc_container = $('div.perfect_one_checkout_main_container');
	for (var i = layout_columns+1; i <= 3; i++) {
		poc_container.find('div.col_'+i).remove();
	}

	for (var i =1; i <= layout_columns; i++) {
		poc_container.find('div.col_'+i).addClass('poc_col-'+layout_colspans[i]);
	}

	insert_panels();
}

function insert_panels()
{
	var poc_container = $('div.perfect_one_checkout_main_container');

	$.each(panels, function(key, panel_name) {
		var status = panels[panel_name]['status'];
		if(status)
		{
			var panel = $('div.panels').find('div.panel_'+panel_name);
			var colspan = panels[panel_name]['colspan'];
			var col = panels[panel_name]['col'];
			panel.addClass('poc_col-'+colspan);
			poc_container.find('div.col_'+col).append(panel);
		}
	});

	$('div.panels').remove();
}

//Devman Extensions - info@devmanextensions.com - 9/12/17 15:35 - Google Maps API
	function initAutocomplete() {
		//var acInputs = document.getElementsByClassName("payment_address_address_1");
		var acInputs = $(".payment_address_address_1");

		for (var i = 0; i < acInputs.length; i++) {
			autocomplete = new google.maps.places.Autocomplete(
            	(acInputs[i]),
            	{types: ['geocode']});
			autocomplete.inputId = acInputs[i].id;
			autocomplete.addListener('place_changed', fillInAddress);
        }

        var acInputs = document.getElementsByClassName("shipping_address_address_1");

		for (var i = 0; i < acInputs.length; i++) {
			autocomplete = new google.maps.places.Autocomplete(
            	(acInputs[i]),
            	{types: ['geocode']});
			autocomplete.inputId = acInputs[i].id;
			autocomplete.addListener('place_changed', fillInAddress);
        }
	}

	function fillInAddress() {
		var place = this.getPlace();
		var input_id = this.inputId;
		var input_address = $('#'+input_id);


		var input_container = !poc_modals_in_forms && !input_address.closest('div.remodal').hasClass('new_address') ? input_address.closest('div.poc_form') : input_address.closest('div.remodal');
		var city_input = input_container.find('input[name="city"]');
		var postcode_input = input_container.find('input[name="postcode"]');
		var country_id_input = input_container.find('select[name="country_id"]');
		var zone_id_input = input_container.find('select[name="zone_id"]');

		var country_iso_code = '';
		var zone_name = '';

		var componentForm = {
			route: 'long_name', //Street
	        locality: 'long_name', //City
			administrative_area_level_1: 'short_name', //Zone (sometimes it is the good)
			administrative_area_level_2: 'short_name', //Zone (sometimes it is the good)
			country: 'short_name', //Country
			postal_code: 'short_name', //Post code
			street_number: 'long_name'
		};

		var zone_code_1 = '';
		var zone_name_1 = '';
		var zone_code_2 = '';
		var zone_name_2 = '';
		var street_number = '';

		for (var i = 0; i < place.address_components.length; i++) {
			var addressType = place.address_components[i].types[0];

			if (componentForm[addressType]) {
				var val = place.address_components[i][componentForm[addressType]];

				if(addressType == 'route') {
					input_address.val(val);
				}
				else if(addressType == 'street_number') {
					street_number = val;
				}
				else if (addressType == 'locality' && city_input) {
					city_input.val(val);
				}
				else if (addressType == 'administrative_area_level_1') {
					zone_code_1 = place.address_components[i]['short_name'];
					zone_name_1 = place.address_components[i]['long_name'];
				}else if (addressType == 'administrative_area_level_2') {
					zone_code_2 = place.address_components[i]['short_name'];
					zone_name_2 = place.address_components[i]['long_name'];
				}else if (addressType == 'country') {
					country_iso_code = val;
				}else if (addressType == 'postal_code' && postcode_input) {
					postcode_input.val(val);
				}
			}
		}

		if(input_address && street_number != '')
		{
			var current_street = input_address.val();
			input_address.val(current_street+', '+street_number);
		}

		if(country_iso_code != '')
			auto_fill_country_and_zone(country_id_input, zone_id_input, country_iso_code, zone_code_1, zone_name_1, zone_code_2, zone_name_2);
		else
		{
			if(input_address)
				input_address.trigger('change');
			else if(city_input)
				city_input.trigger('change');
			else if(postcode_input)
				postcode_input.trigger('change');
		}
	}
//END

function auto_fill_country_and_zone(country_selector, zone_selector, country_iso_code, zone_code_1, zone_name_1, zone_code_2, zone_name_2)
{
	$.ajax({
		url: 'index.php?route=extension/module/perfect_one_checkout/get_country_id_and_zone_id',
		data: {country_iso_code : country_iso_code, zone_code_1 : zone_code_1, zone_name_1 : zone_name_1, zone_code_2 : zone_code_2, zone_name_2 : zone_name_2},
		type: "POST",
		dataType: 'json',
		beforeSend:function() {
		},
		success: function(data) {
			if(data.country_id != '') {
                country_selector.val(data.country_id);
                if(data.zone_id != '')
                	ajax_get_zones(country_selector, data.zone_id);
                else
                	country_selector.trigger('change');
            }
		},
		error: function(data) {
		},
	});
	return '';
}