function closeTheForm(e){
    e.stopPropagation();
	e.preventDefault();
    $(this).parent().fadeOut();
}

function openTheForm(e){
	e.preventDefault();
    $('.ruta').find('.close').click();
    $('#theForm').fadeIn();
}

function submitTheForm(e){
	e.preventDefault();
    var error = false;
	_this = $('#theForm');
    _this.find('.required').each(function () {
        if ($(this).val() == '') {
            $(this).addClass('error');
            error = true;
        } else {
            $(this).removeClass('error');
        }
    });
    _this.find('.mail').each(function () {
        if (!isValidEmailAddress($(this).val())) {
            $(this).addClass('error');
            error = true;
        } else {
            $(this).removeClass('error');
        }
    });
    if (!error) {
        var firstName = 'Swedbank! ' + $('input[id$=firstName]', _this).val();
        var lastName = $('input[id$=lastName]', _this).val();
        var address = $('input[id$=address]', _this).val();
        var zip = $('input[id$=zip]', _this).val();
        var city = $('input[id$=city]', _this).val();
        var mail = $('input[id$=mail]', _this).val();
        var phone = $('input[id$=phone]', _this).val();
        var newsletter = $('input[id$=newsletter]', _this).attr('checked');
        var amount = $('select[id$=amount] option:selected', _this).val();
        var data = 'firstname=' + firstName + '&lastname=' + lastName + '&address=' + address + '&zip=' + zip + '&city=' + city + '&mail=' + mail + '&phone=' + phone + '&newsletter=' + newsletter + '&amount=' + amount;
        $.ajax({
            type: 'GET',
            url: 'http://friends.se/blivanskapare/default.aspx',
            data: data,
            dataType: "json",
            success: function (response) {
                document.location.href = 'http://friends.se/?id=8112';
            }
        });
    }
	return false;
}
function isValidEmailAddress(emailAddress) {
    var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
    return pattern.test(emailAddress);
}

$(document).ready(function () {
    $('.oppnaBliVanskapare').click(openTheForm);
    $('.close').click(closeTheForm);
    $('#submitTheForm').click(submitTheForm);

    $('#theForm, #vanskapareFormSuccess').hide();
});
