
var pulling = false;
var lastAfterFunction = false;
var lastAddresses = new Array();
var pulling = false;
var mail_leadid = "";
var leadId = "";

function validateEmail(autoSubmit, afterFunction) {
	
    success = false;
    //BELOW, THE STRING, "afterFunction", WAS JUST SITTING THERE WITHOUT A END SEMICOLON I'M TAKING IT OUT AND SEEING IF ANY PROBLEMS ARISE, IF NOT THEN WE CAN TAKE IT OUT COMPLETELY NEXT PUSH
    //ED WINCE 1/3/12
    //afterFunction
    if(typeof(afterFunction) == "undefined") {
        lastAfterFunction = false;
    } else {
        lastAfterFunction = afterFunction;
    }
    
    if(typeof(autoSubmit) == "undefined") {
        autoSubmit = false;
    }
    
    if($("#landingForm").validate().form()) {
        success = false;
        //Loading icon
        //$("#loading_row").show();
        $("#submitloadingspinner").show();
        $.ajax({
            type: "GET",
            url: "/emailvalidation.html?" + $("#landingForm").serialize(),
                dataType: "json",
            success: function (data) {
                $("#submitloadingspinner").hide();
                if (data.redirect) {
                    if (typeof DisableExitSplash == 'function') {
                        DisableExitSplash();
                    }
                    window.location.replace(data.redirect);
                    pulling = false;
                    return false;
                }
                if(!data.emailValid || data.isEmailFraud) {
                    $('#address_error_row').show();
                    $('#address_error').html('Please enter a valid email address');
                    alert($.i18n.prop("valid.email"));
                    return false;
                } 
                if(!data.isValidFirstLastName && data.isValidFirstLastName !== undefined && data.isValidFirstLastName !== null){
                    alert($.i18n.prop("valid.name"));
                    return false;
                }
                if(!data.isValidUkPhone &&data.isValidUkPhone !== undefined && data.isValidUkPhone !== null){
                    alert("Phone is not valid.");
                    return false;
                }
                if(!data.isValidUkAltPhone &&data.isValidUkPhone !== undefined && data.isValidUkAltPhone !== null){
                    alert("Alt Phone is not valid.");
                    return false;
                }
                if(!data.isValidPhone) {
                    $('#address_error_row').show();
                    $('#address_error').html('Please enter a valid phone number');
                    alert($.i18n.prop("valid.phone"));
                    return false;
                }
                if(!data.postCodeValid) {
                    $('#address_error_row').show();
                    $('#address_error').html($.i18n.prop("add.postcode"));
                    if(document.getElementById('address_error') == null) {
                        alert($.i18n.prop("add.postcode"));
                    }
                    pulling = false;
                    return false;
                }
                leadId = data.leadId;
                mail_leadid = leadId;
                success = true;
                return true;
            },
            error: function(request, errormessage) {
                $("#submitloadingspinner").hide();
                //Check if fraud
                if(request.responseText.indexOf('flagged for fraud') > -1) {
                    var thetext = request.responseText;
                    //var themessage = "Sorry, the email address you have entered has been associated with fraudulent activity. If you feel that you have reached this page in error and the address you have provided is valid, please use this contact form to alert us of the situation.";
                    var themessage = $.i18n.prop("field.email_error");
                    thetext = thetext.replace(/<span id="custommessage">.*<\/span>/g, themessage);
                    $("body").html(thetext);
                    return false;
                }
                
                return false;
            },
            async:false
        });
    }
    if(lastAfterFunction != false) {

    }
    return success;
}

function displayAddresses() {
    
//    if(typeof(useNotListed) == "undefined") {
//        useNotListed = true;
//    }
    
    if(pulling == true) {
        alert('Addresses are currently being retrieved');
        return false;
    }
    if($("#landingForm").validate().form()) {
        //Loading icon
        $("#loading_row").show();
        
        pulling = true;
        $.ajax({
            type: "GET",
            url: "emailvalidation.html?" + $("#landingForm").serialize(),
            dataType: "json",
            success: function (data) {
                $("#loading_row").hide();
                if (data.redirect) {
                    if (typeof DisableExitSplash == 'function') {
                        DisableExitSplash();
                    }
                    window.location.replace(data.redirect);
                    pulling = false;
                    return false;
                }
                if(!data.emailValid || data.isEmailFraud) {
                    $('#address_error_row').show();
                    $('#address_error').html('Please enter a valid email address');
                    alert("Please enter a valid email address");
                    pulling = false;
                    return false;
                }    
                else if(!data.isValidFirstLastName) {
                    $('#address_error_row').show();
                    $('#address_error').html('Please enter a valid first/last name');
                    alert("Please enter a valid  first/last name");
                    pulling = false;
                    return false;
                }
                if(!data.isValidPhone) {
                    $('#address_error_row').show();
                    $('#address_error').html('Please enter a valid phone number');
                    alert($.i18n.prop("valid.phone"));
                    return false;
                }
                var addresses = data.addresses;
                lastAddresses = addresses;
                var options = '';
                leadId = data.leadId;
                mail_leadid = leadId;
                if(addresses.length == 0 || !data.postCodeValid) {
                    $('#address_error_row').show();
                    $('#address_error').html($.i18n.prop("add.postcode"));
                    if(document.getElementById('address_error') == null) {
                        alert($.i18n.prop("add.postcode"));
                    }
                    pulling = false;
                    return false;
                }
                for (var i = 0; i < addresses.length; i++) {
                    var address = addresses[i];
                    var town = address.town;
                    var state = address.state;
                    var caption = '';
                    if($.trim(town) != '') {
                        if(caption != '')
                            caption += ', ';
                        caption += town;
                    }
                    if($.trim(state) != '') {
                        if(caption != '')
                            caption += ', ';
                        caption += state;
                    }
                    options += '<option value="' + i + '">' + caption + '</option>';
                }
                
                    //Add in option to unlock postcode
                    options += '<option value="not_listed">'+$.i18n.prop("add.town")+'</option>';

                $("#addresses").html(options);
                $("#chooseAddress").show();
                $("#chooseAddress_select").slideDown('normal');
                
//                if(useNotListed == true) {
                    $("#nextbutton").hide();
                    $("#submitbutton").show();
                    $("#zip").attr("readonly", "true");
//                }
                $('#address_error_row').hide();
                pulling = false;
            },
            error: function(request, settings) {
                if(request.responseText.indexOf('flagged for fraud') > -1) {
                    var thetext = request.responseText;
                    var themessage = "Sorry, the email address you have entered has been associated with fraudulent activity. If you feel that you have reached this page in error and the address you have provided is valid, please use this contact form to alert us of the situation.";
                    thetext = thetext.replace(/<span id="custommessage">.*<\/span>/g, themessage);
                    $("html").html(thetext);
                    return;
                }
                $("#loading_row").hide();
                alert('There was an error retrieving the address list. Please try again.');
                pulling = false;
            }            
        });
        
        
    }
}

function selectAddress(id) {
    
    var addressSize = $("#chooseAddress_select option").size();
    if(id == (addressSize - 1)) {
        $("#zip").removeAttr("readonly");
        $("#row_city").hide();
        $("#row_state").hide();
        $("#submitbutton").hide();
        $("#nextbutton").show();
        $("#chooseAddress_select").slideUp('normal', function() {
            $("#chooseAddress").hide();
        });
        return;
    }
    
    var address = lastAddresses[id];

    var townEl = document.getElementById("city");
    var stateEl = document.getElementById("state");
    var provinciaEl = document.getElementById("provincia");

    if(townEl != null){
        townEl.value = address.town;
    }    
    if(stateEl != null) {
        stateEl.value = address.state;
        $("#state").change();
    }
    if(provinciaEl != null) {
        provinciaEl.value = address.state;
    }
    
    //$("#row_city").show();

    $("#chooseAddress_select").slideUp('normal', function() {
        $("#chooseAddress").hide();
        $("#editAddressLink").show();
        $("#submitbutton").show();
    });
    
    checkAddress();
}

function checkAddress() {    
    
    //If there is a value in either of the fields, then success.
    if($('#city').val() != '' || $('#state').val() != '') {
        $('#address_error_row').hide();
        return true;
    }
    else {
        $('#address_error_row').show();
        $('#address_error').html('You didn\'t select your address');
        enableButton();
        return false;
    }    
}

function editAddress() {
    //Hide the edit link
    $("#editAddressLink").hide();
    //This will unlock/show the address selection area.
    $("#chooseAddress").show();
    $("#chooseAddress_select").slideDown();
}

function showButton()            
{
    if($('#landingForm').validate().form())
    {
      $("#realbutton").hide();
      $("#fakebutton").show();
    }
}

function enableButton()
{
    $("#fakebutton").hide();
    $("#realbutton").show();
}

