var addressSelected = false;

var lastAddresses = new Array();
var pulling = false;
var royalmail_leadid = "";
var lastAfterFunction = false;

function pullAddressesForDivSelect(autoSubmit, afterFunction) {
    if(typeof(afterFunction) == "undefined") {
        lastAfterFunction = false;
    } else {
        lastAfterFunction = afterFunction;
    }
    
    if(typeof(autoSubmit) == "undefined") {
        autoSubmit = false;
    }
    
    if(pulling == true) {
        alert('Addresses are currently being retrieved');
        return false;
    }
    
    if($("#landingForm").validate().form()) {
        //Loading icon
        $("#loading_row").show();
        var serializedForm = $("#landingForm").serialize();
        fieldsEnableDisable(true);
        pulling = true;
        $.ajax({
            type: "GET",
            url: "/royalmail.html?" + serializedForm,
            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) {
                	fieldsEnableDisable(false);
                    $('#address_error_row').show();
                    $('#address_error').html('Please enter a valid email address');
                    alert("Please enter a valid email address");
                    pulling = false;
                    return false;
                }
                if(!data.isValidFirstLastName) {
                	fieldsEnableDisable(false);
                    $('#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.isPhoneValid !=null && !data.isPhoneValid) {
                		fieldsEnableDisable(false);
                        $('#address_error_row').show();
                        $('#address_error').html('Please enter a valid UK home or mobile phone<br />( 0 followed by 9 or 10 digits )');
                        alert("Please enter a valid UK home or mobile phone\n( 0 followed by 9 or 10 digits )");
                        pulling = false;
                        return false;
                }
                var addresses = data.addresses;
                lastAddresses = addresses;
                var options = '';
                var leadId = data.leadId;
                royalmail_leadid = leadId;
                if(addresses.length == 0) {
                    $('#address_error_row').show();
                    $('#address_error').html('Please enter a valid postal code');
                    alert("Please enter a valid postal code");
                    fieldsEnableDisable(false);
                    pulling = false;
                    return false;
                }
                for (var i = 0; i < addresses.length; i++) {
                    var address = addresses[i];
                    var address1 = address.address1;
                    var address2 = address.address2;
                    var house = address.house;
                    var town = address.town;
                    var caption = '';
                    if($.trim(address1) != '') {
                        if(caption != '')
                            caption += ', ';
                        caption += address1;
                    }
                    if($.trim(address2) != '') {
                        if(caption != '')
                            caption += ', ';
                        caption += address2;
                    }
                    if($.trim(town) != '') {
                        if(caption != '')
                            caption += ', ';
                        caption += town;
                    }
//                  options += '<option value="' + i + '">' + caption + '</option>';
                    if(autoSubmit) {
                    options += '<div style="color:#000000;cursor:default;white-space:nowrap;width:100%;" onclick="if (addressSelected == false) { addressSelected = true; this.style.backgroundColor=\'black\'; this.style.color=\'white\'; selectAddressFromDiv(\''+i+'\', true); }">' + caption + '</div>';
                        
                    } else {
                    options += '<div style="color:#000000;cursor:default;white-space:nowrap;width:100%;" onclick="if (addressSelected == false) { addressSelected = true; this.style.backgroundColor=\'black\'; this.style.color=\'white\'; selectAddressFromDiv(\''+i+'\'); }">' + caption + '</div>';
                    }
                }
                
                
//              if(useNotListed == true) {
                    //Add in option to unlock postcode
//                  options += '<option value="not_listed">-- My address is not listed here --</option>';
                    options += '<div style="color:#000000;cursor:default;white-space:nowrap;width:100%;" onclick="this.style.backgroundColor=\'black\';this.style.color=\'white\';selectAddressFromDiv(\'not_listed\')">-- My address is not listed here --</div>';

//              }
                
                $("#addresses").html(options);
                $("#chooseAddress").show();
                $("#chooseAddress_select").slideDown('normal');
                
//              if(useNotListed == true) {
                    $("#nextbutton").hide();
                    $("#submitbutton").show(); // is this even used anymore?
                    
//              }
                $('#address_error_row').hide();
                pulling = false;
            },
            error: function(request, errormessage) {
                
                //Check if fraud, replace the error html if so
            	var replaceIt = false;
            	var themessage = "";
            	if(request.responseText.indexOf('flagged for fraud') > -1) {
            		replaceIt = true;
            		themessage = "Sorry, the email address you have entered has been associated with fraudulent activity.";
            	} else if (request.responseText.indexOf('tries exceeded') > -1) {
            		replaceIt = true;
            		themessage = "Sorry, the maximum number of tries for a valid UK home or mobile phone (0xxxxxxxxx or 0xxxxxxxxxx) has been exceeded.";
            	}
                if (replaceIt) {
                	themessage = themessage + " If you feel that you have reached this page in error and the information you have provided is valid, please use this contact form to alert us of the situation.";
                	var thetext = request.responseText;
                    thetext = thetext.replace(/<span id="custommessage">.*<\/span>/g, themessage);
                    $("body").html(thetext);
                    return;
                }
                
                $("#loading_row").hide();
                alert("There was an error retrieving the address list. Please try again. [" + errormessage + "]");
                pulling = false;
            }           
        });
    }
    
}

function fieldsEnableDisable(disableEnable){
	if(disableEnable == true){
		$("#title").attr("disabled", "true");
		$("#firstName").attr("readOnly", "true");
		$("#firstName").css("background-color", "#eee");
		$("#lastName").attr("readOnly", "true");
		$("#lastName").css("background-color", "#eee");
		$("#zip").attr("readOnly", "true");
		$("#zip").css("background-color", "#eee");
		$("#email").attr("readOnly", "true");
		$("#email").css("background-color", "#eee");
		$("#phone").attr("readOnly", "true");
		$("#phone").css("background-color", "#eee");
		$("#dobDay").attr("disabled", "true");
		$("#dobMonth").attr("disabled", "true");
		$("#dobYear").attr("disabled", "true");
	}
	else{
		$("#title").removeAttr("disabled");
		$("#firstName").removeAttr("readOnly");
		$("#firstName").css("background-color", "white"); 
		$("#lastName").removeAttr("readOnly");
		$("#lastName").css("background-color", "white");
		$("#zip").removeAttr("readOnly");
		$("#zip").css("background-color", "white");
		$("#email").removeAttr("readOnly");
		$("#email").css("background-color", "white");
		$("#phone").removeAttr("readOnly");
		$("#phone").css("background-color", "white");
		$("#dobDay").removeAttr("disabled");
		$("#dobMonth").removeAttr("disabled");
		$("#dobYear").removeAttr("disabled");
	}
}

function pullAddresses() {
    
//  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();
        fieldsEnableDisable(false);
        var serializedForm = $("landingForm").serialize();
        fieldsEnableDisable(true);
        pulling = true;
        $.ajax({
            type: "GET",
            url: "/royalmail.html?" + serializedForm,
            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;
                }
                var addresses = data.addresses;
                lastAddresses = addresses;
                var options = '';
                var leadId = data.leadId;
                royalmail_leadid = leadId;
                if(addresses.length == 0) {
                    $('#address_error_row').show();
                    $('#address_error').html('Please enter a valid postal code');
                    fieldsEnableDisable(false);
                    if(document.getElementById('address_error') == null) {
                        alert("Please enter a valid postal code");
                    	fieldsEnableDisable(false);
                    }
                    pulling = false;
                    return false;
                }
                for (var i = 0; i < addresses.length; i++) {
                    var address = addresses[i];
                    var address1 = address.address1;
                    var address2 = address.address2;
                    var house = address.house;
                    var town = address.town;
                    var caption = '';
                    if($.trim(address1) != '') {
                        if(caption != '')
                            caption += ', ';
                        caption += address1;
                    }
                    if($.trim(address2) != '') {
                        if(caption != '')
                            caption += ', ';
                        caption += address2;
                    }
                    if($.trim(town) != '') {
                        if(caption != '')
                            caption += ', ';
                        caption += town;
                    }
                    options += '<option value="' + i + '">' + caption + '</option>';
                }
                
                
//              if(useNotListed == true) {
                    //Add in option to unlock postcode
                    options += '<option value="not_listed">-- My address is not listed here --</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, errormessage) {
                $("#loading_row").hide();
                alert("There was an error retrieving the address list. Please try again. [" + errormessage + "]");
                pulling = false;
            }           
        });
        
    }
}

function selectAddressFromDiv(value, autoSubmit) {
    
    if(typeof(autoSubmit) == "undefined") {
        autoSubmit = false;
    }
    
//  var addressSize = $("#chooseAddress_select option").size();
    if(value == 'not_listed') {
    	fieldsEnableDisable(false);
        //$("#zip").removeAttr("readonly");
        $("#row_address1").hide();
        $("#row_address2").hide();
        $("#row_house").hide();
        $("#row_city").hide();
        $("#submitbutton").hide();
        $("#nextbutton").show();
        $("#chooseAddress_select").slideUp('normal', function() {
            $("#chooseAddress").hide();
        });
        if (typeof DisableExitSplash == 'function') {
            DisableExitSplash();
        }
        return;
    }
    
    var address = lastAddresses[value];
    var address1El = document.getElementById('address1');
    var address2El = document.getElementById("address2");
    var houseEl = document.getElementById("house");
    var houseNumber = document.getElementById("houseNumber");
    var houseName = document.getElementById("houseName");
    var buildingNumber = document.getElementById("buildingNumber");
    var streetEl = document.getElementById("street");
    var townEl = document.getElementById("city");
    
    if(address1El != null)
        address1El.value = address.address1;
    if(address2El != null)
        address2El.value = address.address2;
    if(houseEl != null)
        houseEl.value = address.house;
    if(houseNumber != null)
        houseNumber.value = address.houseNumber;
    if(houseName != null)
        houseName.value = address.houseName;
    if(buildingNumber != null)
        buildingNumber.value = address.buildingNumber;
    if(streetEl != null)
        streetEl.value = address.street;
    if(townEl != null)
        townEl.value = address.town;
    
    //alert( "Selected Address: " + address.house + ', ' + address.address1 + ', ' + address.town );    
    
    $("#row_address1").show();
    $("#row_address2").show();
    $("#row_house").show();
    //$("#row_city").show();
    
    $("#chooseAddress_select").slideUp('normal', function() {
        $("#chooseAddress").hide();
        $("#editAddressLink").show();
        $("#submitbutton").show();
    });
    
    checkAddress();
    fieldsEnableDisable(false);
    var serializedForm = $("#landingForm").serialize();
    fieldsEnableDisable(true);
    
    success = false;
    $.ajax({
        type: "GET",
        url: "/ukphonewebservicevalidation.html?" + serializedForm,
            dataType: "json",
        success: function (data) {
            if(!data.isPhoneValid) {
            	fieldsEnableDisable(false);
                $('#address_error_row').show();
                $('#address_error').html('Please enter a valid UK home or mobile phone<br />( 0 followed by 9 or 10 digits )');
                //alert("Please enter a valid email uk phone number");
                success = false;
                showButtonsAndAddress();                
                return false;
            } 
            success = true;
            if (typeof DisableExitSplash == 'function') {
                DisableExitSplash();
            }
            return true;
        },
        error: function(request, errormessage) {
        	 // This is copied from above, need to handle too many failed phones.
        	var replaceIt = false;
        	var themessage = "";
        	if(request.responseText.indexOf('flagged for fraud') > -1) {
        		replaceIt = true;
                themessage = "Sorry, the email address you have entered has been associated with fraudulent activity.";
        	} else if (request.responseText.indexOf('tries exceeded') > -1) {
        		replaceIt = true;
        		themessage = "Sorry, the maximum number of tries for a valid UK home or mobile phone (0xxxxxxxxx or 0xxxxxxxxxx) has been exceeded.";
        	}
            if (replaceIt) {
            	themessage = themessage + " If you feel that you have reached this page in error and the information you have provided is valid, please use this contact form to alert us of the situation.";
            	var thetext = request.responseText;
                thetext = thetext.replace(/<span id="custommessage">.*<\/span>/g, themessage);
                $("body").html(thetext);
                return;
            }
            return false;
        },
        async:false
    });
    
    if(success && autoSubmit) {
        if(lastAfterFunction != false) {
            lastAfterFunction();
            setTimeout("document.getElementById('landingForm').submit();", 1500);
        } else {
            document.getElementById('landingForm').submit();
        }
    } else {
        if(lastAfterFunction != false) {
            lastAfterFunction();
        }
    }
}

function showButtonsAndAddress(){
    $("#submitbutton").hide();
    $("#nextbutton").show();
    //$("#chooseAddress").show();
}

function selectAddress(id) {
    
    var addressSize = $("#chooseAddress_select option").size();
    if(id == (addressSize - 1)) {
    	fieldsEnableDisable(false);
        //$("#zip").removeAttr("readonly");
        $("#row_address1").hide();
        $("#row_address2").hide();
        $("#row_house").hide();
        $("#row_city").hide();
        $("#submitbutton").hide();
        $("#nextbutton").show();
        $("#chooseAddress_select").slideUp('normal', function() {
            $("#chooseAddress").hide();
        });
        if (typeof DisableExitSplash == 'function') {
            DisableExitSplash();
        }
        return;
    }
    
    var address = lastAddresses[id];
    var address1El = document.getElementById('address1');
    var address2El = document.getElementById("address2");
    var houseEl = document.getElementById("house");
    var houseNumber = document.getElementById("houseNumber");
    var houseName = document.getElementById("houseName");
    var buildingNumber = document.getElementById("buildingNumber");
    var buildingName = document.getElementById("buildingName");
    var thoroughFareDescriptor = document.getElementById("thoroughFareDescriptor");
    var thoroughFareName = document.getElementById("thoroughFareName");
    var dependentThoroughFareDescriptor = document.getElementById("dependentThoroughFareDescriptor");
    var dependentThoroughFareName = document.getElementById("dependentThoroughFareName");
    var dependentLocality = document.getElementById("dependentLocality");       
    var streetEl = document.getElementById("street");
    var townEl = document.getElementById("city");
    
    if(address1El != null)
        address1El.value = address.address1;
    if(address2El != null)
        address2El.value = address.address2;
    if(houseEl != null)
        houseEl.value = address.house;
    if(houseNumber != null)
        houseNumber.value = address.houseNumber;
    if(houseName != null)
        houseName.value = address.houseName;
    if(buildingNumber != null)
        buildingNumber.value = address.buildingNumber;  
    if(buildingName != null)
        buildingName.value = address.building.name; 
    if(thoroughFareDescriptor != null)
        thoroughFareDescriptor.value = address.thoroughFare.descriptor; 
    if(thoroughFareName != null)
        thoroughFareName.value = address.thoroughFare.name; 
    if(dependentThoroughFareDescriptor != null)
        dependentThoroughFareDescriptor.value = address.dependentThoroughFareDescriptor.descriptor; 
    if(dependentThoroughFareName != null)
        dependentThoroughFareName.value = address.dependentThoroughFare.name;   
    if(dependentLocality != null)
        dependentLocality.value = address.locality.dependentLocality;   
    if(streetEl != null)
        streetEl.value = address.street;
    if(townEl != null)
        townEl.value = address.town;
    
    //alert( "Selected Address: " + address.house + ', ' + address.address1 + ', ' + address.town );
    
    $("#row_address1").show();
    $("#row_address2").show();
    $("#row_house").show();
    //$("#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($('#house').val() != '' || $('#address1').val() != '' || $('#city').val() != '') {
        $('#address_error_row').hide();
        return true;
    }
    else if($('#house').val() == '' && $('#address1').val() == '' && $('#city').val() == '') {
        $('#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();
    
}
