
/**
 * Blank definition for PCAFieldDefs
 * Solely for reference
 */
function PCAFieldDefs(){
    this.txtPostcode = null;
    this.imgGettingAddress = null;
    this.txtAddress1 = null;
    this.txtAddress2 = null;
    this.txtAddress3 = null;
    this.txtAddress4 = null;
    this.lblAddressQ1 = null;
    this.lblAddressQ2 = null;
    this.lblAddressQ3 = null;
    this.lblAddressQ4 = null;
    this.lstAddresses = null;
}

/**
 * Global request object
 */
var request = null;

/**
 * Global machine ID string
 */
var machine_id = '';

/**
 * Global fields object
 */
var oFields = null;

/**
 * Starting point for the lookup
 */
function pcaByPostcodeBegin(account_code, license_code, oPCAFieldDefs) {
    oFields = oPCAFieldDefs;
    var postcode = obi(oFields.txtPostcode).value;
    var scriptTag = obi("pcaScriptTag");
    var headTag = document.getElementsByTagName("head").item(0);
    var strUrl = "";
    
    showAnimation(true, oPCAFieldDefs);
    clearAddress(oPCAFieldDefs);
    
    strUrl = "https://services.postcodeanywhere.co.uk/inline.aspx?";
    strUrl += "&action=lookup";
    strUrl += "&type=by_postcode";
    strUrl += "&postcode=" + escape(postcode);
    strUrl += "&account_code=" + escape(account_code);
    strUrl += "&license_code=" + escape(license_code);
    strUrl += "&machine_id=" + escape(machine_id);
    strUrl += "&callback=pcaByPostcodeEnd";
    
    if (scriptTag){
        headTag.removeChild(scriptTag);
    }
    scriptTag = document.createElement("script");
    scriptTag.src = strUrl
    scriptTag.type = "text/javascript";
    scriptTag.id = "pcaScriptTag";
    headTag.appendChild(scriptTag);
}

/**
 * Show or Hide the animated gif for lookup
 */
function showAnimation(state) {
    if (state) {
        obi(oFields.imgGettingAddress).style.visibility = 'visible';
        obi(oFields.imgGettingAddress).style.display = 'block';
    } else {
        obi(oFields.imgGettingAddress).style.visibility='hidden';
    }
}

/**
 * Clear out any existing address info
 */
function clearAddress() {
    document.getElementById(oFields.txtAddress1).value="";
    document.getElementById(oFields.txtAddress2).value="";
    document.getElementById(oFields.txtAddress3).value="";
    document.getElementById(oFields.txtAddress4).value="";
    document.getElementById(oFields.lblAddressQ1).innerHTML="";
    document.getElementById(oFields.lblAddressQ2).innerHTML="";
    document.getElementById(oFields.lblAddressQ3).innerHTML="";
    document.getElementById(oFields.lblAddressQ4).innerHTML="";
}


function pcaByPostcodeEnd() {        
    if (pcaIsError) {
        document.getElementById(oFields.lstAddresses).style.visibility='hidden';
        showAnimation(false);
        // alert(pcaErrorMessage);
        // to allow multilingual error messages
        if(pcaErrorNumber==27){
            alert(errorMessages.completePostCode);
        }
        else{
            alert(errorMessages.pcaBadAccount);
            console.log("Error number:"+pca_error_number[0]+" Error text:"+pcaErrorMessage);
        }
    }
    else {
        if (pcaRecordCount==0) {
            document.getElementById(oFields.lstAddresses).style.visibility='hidden';
            showAnimation(false);
            alert(errorMessages.noMatchTryAagin);
        }
        else {
            
            for (i=obi(oFields.lstAddresses).options.length-1; i>=0; i--){
                obi(oFields.lstAddresses).options[i] = null;
            }
            for (i=0; i<pca_id.length; i++){
                obi(oFields.lstAddresses).options[obi(oFields.lstAddresses).length] = new Option(pca_description[i], pca_id[i]);
            }
            obi(oFields.lstAddresses).style.visibility='visible';
            obi(oFields.lstAddresses).style.display='block';
            obi(oFields.lstAddresses).focus();
            showAnimation(false);
        }
    }
}

/**
 * Get address details for the chosen item
 */
function pcaFetchBegin(account_code, license_code) {
    var address_id = obi(oFields.lstAddresses).value;
    var scriptTag = obi("pcaScriptTag");
    var headTag = document.getElementsByTagName("head").item(0);
    var strUrl = "";
    
    if(address_id.length > 0){
        showAnimation(true);
        
        strUrl = "https://services.postcodeanywhere.co.uk/inline.aspx?";
        strUrl += "&action=fetch";
        strUrl += "&id=" + escape(address_id);
        strUrl += "&account_code=" + escape(account_code);
        strUrl += "&license_code=" + escape(license_code);
        strUrl += "&machine_id=" + escape(machine_id);
        strUrl += "&callback=pcaFetchEnd";
        
        if (scriptTag) {
            headTag.removeChild(scriptTag);
        }
        scriptTag = document.createElement("script");
        scriptTag.src = strUrl
        scriptTag.type = "text/javascript";
        scriptTag.id = "pcaScriptTag";
        headTag.appendChild(scriptTag);
        
        obi(oFields.lstAddresses).style.visibility='hidden';
        
        focusNext(obi(oFields.txtAddress4));
    }
}

/**
 * Callback from the fetch
 */ 
function pcaFetchEnd() {
    if (pcaIsError) {
        showAnimation(false);
        // alert(pcaErrorMessage);
        // to allow multilingual error messages
        if(pca_error_number[0] == "27"){
            alert(errorMessages.completePostCode);
        }
        else{
            alert(errorMessages.pcaBadAccount);
            console.log("Error number:"+pca_error_number[0]+" Error text:"+pcaErrorMessage);
         }
    }
    else {
        //Check if there were any items found
        if (pcaRecordCount==0) {
            showAnimation(false);
            alert(errorMessages.sorryNoMatch);
        }
        else {
            var strAddress = "";
            var address = "";
            var postCode = "";
            if (pca_line1[0] != '') strAddress += pca_line1[0]+','
            if (pca_line2[0] != '') strAddress += pca_line2[0]+','
            if (pca_line3[0] != '') strAddress += pca_line3[0]+','
            if (pca_line4[0] != '') strAddress += pca_line4[0]+','
            if (pca_line5[0] != '') strAddress += pca_line5[0]+','
            if (pca_post_town[0] != '') strAddress += pca_post_town[0]+','
            if (pca_county[0] != '') strAddress += pca_county[0]
            if (pca_postcode[0] != '') postCode = pca_postcode[0]
            
            
            try{
                document.getElementById("form1:hidPayAddr1").value = pca_line1[0];
            }catch(e){}
            try{
                document.getElementById("form1:hidPayAddr2").value = pca_post_town[0];
            }catch(e){}
            try{
                document.getElementById("form1:hidPayAddr3").value = pca_county[0];
            }catch(e){}
            try{
                document.getElementById("form1:hidPayAddr4").value = pca_postcode[0];
            }catch(e){}                       
            
            if (strAddress!='') strAddress = strAddress.substring(0,strAddress.length);
            
            var formatter = strAddress.split(",");
            var position = 0;
            var elements = formatter.length;
            var maxLines = 4;
            for (i = 0; i < elements; i++) {
                if (elements > maxLines && (i+2) < elements) {
                    if ((formatter[i].length + formatter[i+1].length) < 29) {
                        address += formatter[i] + ", " + formatter[i + 1] + "|";
                        position++;
                        i++;
                    } else {
                        address += formatter[i] + "|";
                        position++;
                    }
                } else {
                    address += formatter[i] + "|";
                    position++;
                }    
            }
            for (i=position+1; i < maxLines; i++) {
                addressOut += "|";
            }
            populatePCAAddress(address, postCode);
            customPostCodeAction(postCode);
        }
    }
}

function customPostCodeAction(postCode) {
}

function checkEnter(e, account_code, license_code){ 
    var characterCode;
    if(e && e.which){ 
        e = e;
        characterCode = e.which;
    } else {
        e = event;
        characterCode = e.keyCode;
    }
    if(characterCode == 13){ 
        pcaFetchBegin(account_code, license_code);
    }
}

/**
 * Populate the fields with the address
 */
function populatePCAAddress(val, postCode) { 
    var addressArray=val.split("|");
    
    obi(oFields.txtAddress1).value = trim(addressArray[0]);
    obi(oFields.txtAddress2).value = trim(addressArray[1]);
    obi(oFields.txtAddress3).value = trim(addressArray[2]);
    obi(oFields.txtAddress4).value = trim(addressArray[3]);
    obi(oFields.lblAddressQ1).innerHTML = trim(addressArray[0]);
    obi(oFields.lblAddressQ2).innerHTML = trim(addressArray[1]);
    obi(oFields.lblAddressQ3).innerHTML = trim(addressArray[2]);
    obi(oFields.lblAddressQ4).innerHTML = trim(addressArray[3]);
    obi(oFields.txtPostcode).value = trim(postCode);
    
    showAnimation(false);
    
    focusNext(obi(oFields.txtAddress4));
}

function focusNext(oField){
    var oParent = oField.parentNode;
    if(oParent != null){
        var oSibling = oParent.nextSibling;
        if(oSibling != null){
            var aInputs = oSibling.getElementsByTagName('input');
            if(aInputs.length > 0){
                aInputs[0].focus();
            }else{
                var aSelects = oSibling.getElementsByTagName('select');
                if(aSelects.length > 0){
                    aSelects[0].focus();
                }
            }
        }else{
            oParent = oParent.parentNode;
            if(oParent != null){
                oSibling = oParent.nextSibling;
                if(oSibling != null){
                    var aInputs = oSibling.getElementsByTagName('input');
                    if(aInputs.length > 0){
                        aInputs[0].focus();
                    }else{
                        var aSelects = oSibling.getElementsByTagName('select');
                        if(aSelects.length > 0){
                            aSelects[0].focus();
                        }
                    }
                }
            }
        }
    }
}

/**
 * Trim left and right of whitespace
 */
function trim(stringToTrim) {
    return stringToTrim.replace(/^\s+|\s+$/g,"");
}
