function populatePCAAddress(val, postCode) { 
    var addressArray=val.split("|");
    
    document.getElementById('form1:txtAddress1').value=trim(addressArray[0]);
    document.getElementById('form1:txtAddress2').value=trim(addressArray[1]);
    document.getElementById('form1:txtAddress3').value=trim(addressArray[2]);
    document.getElementById('form1:txtAddress4').value=trim(addressArray[3]);
    document.getElementById('form1:lblAddressQ1').innerHTML=trim(addressArray[0]);
    document.getElementById('form1:lblAddressQ2').innerHTML=trim(addressArray[1]);
    document.getElementById('form1:lblAddressQ3').innerHTML=trim(addressArray[2]);
    document.getElementById('form1:lblAddressQ4').innerHTML=trim(addressArray[3]);
    document.getElementById('form1:txtPostcode').value=trim(postCode);
    
    showAnimation(false);
    
    focusNext(document.getElementById('form1:txtAddress4'));
}

function populateAddress(val) { 
    
    var params=val.split("$$");
    var addressArray=params[1].split("|");
    
    document.getElementById('form1:txtAddress1').value=trim(addressArray[0]);
    document.getElementById('form1:txtAddress2').value=trim(addressArray[1]);
    document.getElementById('form1:txtAddress3').value=trim(addressArray[2]);
    document.getElementById('form1:txtAddress4').value=trim(addressArray[3]);
    document.getElementById('form1:txtPostcode').value=trim(addressArray[4]);
    document.getElementById('form1:txtAddressMoniker').value=trim(params[0]);
    document.getElementById('form1:lstAddresses').style.visibility='hidden';
    
    focusNext(document.getElementById('form1:txtAddress4'));
    
}

function clearAddress() {
    document.getElementById('form1:txtAddress1').value="";
    document.getElementById('form1:txtAddress2').value="";
    document.getElementById('form1:txtAddress3').value="";
    document.getElementById('form1:txtAddress4').value="";
    document.getElementById('form1:lblAddressQ1').innerHTML="";
    document.getElementById('form1:lblAddressQ2').innerHTML="";
    document.getElementById('form1:lblAddressQ3').innerHTML="";
    document.getElementById('form1:lblAddressQ4').innerHTML="";
}

function trim(stringToTrim) {
    return stringToTrim.replace(/^\s+|\s+$/g,"");
}

function showAnimation(state) {
    if (state) {
        document.getElementById('form1:imgGettingAddress').style.visibility='visible';
        document.getElementById('form1:imgGettingAddress').style.display='block';
    }
    else {
        document.getElementById('form1:imgGettingAddress').style.visibility='hidden';
    }
}

var machine_id='';

function pcaByPostcodeBegin(account_code, license_code) {
    var postcode = document.getElementById('form1:txtPostcode').value;
    var scriptTag = document.getElementById("pcaScriptTag");
    var headTag = document.getElementsByTagName("head").item(0);
    var strUrl = "";
    
    showAnimation(true);
    clearAddress();
    
    //Build the url
    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);
}

function pcaByPostcodeEnd() {        
    if (pcaIsError) {
        document.getElementById('form1:lstAddresses').style.visibility='hidden';
        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 {
        if (pcaRecordCount==0) {
            document.getElementById('form1:lstAddresses').style.visibility='hidden';
            showAnimation(false);
            alert(errorMessages.noMatchTryAagin);
        }
        else {
            
            for (i=document.forms[0]["form1:lstAddresses"].options.length-1; i>=0; i--){
                document.forms[0]["form1:lstAddresses"].options[i] = null;
            }
            for (i=0; i<pca_id.length; i++){
                document.forms[0]["form1:lstAddresses"].options[document.forms[0]["form1:lstAddresses"].length] = new Option(pca_description[i], pca_id[i]);
            }
            document.getElementById('form1:lstAddresses').style.visibility='visible';
            document.getElementById('form1:lstAddresses').style.display='block';
            document.getElementById('form1:lstAddresses').focus();
            showAnimation(false);
        }
    }
}

function pcaFetchBegin(account_code, license_code) {
    var address_id = document.forms[0]["form1:lstAddresses"].value;
    var scriptTag = document.getElementById("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);
        
        document.getElementById('form1:lstAddresses').style.visibility='hidden';
        
        focusNext(document.getElementById('form1:txtAddress4'));
        
    }
}

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 {
        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);
    }
}

/**
 *Focus the next field after a given field
 *@param DOM Object
 */
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();
                        }
                    }
                }
            }
        }
    }
}
