var jsaddressList = null;
var which_address = null;

function copyAddress() {
	document.getElementById('delivery_postcode').value = document.getElementById('billing_postcode').value
	document.getElementById('delivery_name').value = document.getElementById('billing_name').value
	document.getElementById('delivery_addr_line1').value = document.getElementById('billing_addr_line1').value
	document.getElementById('delivery_addr_line2').value = document.getElementById('billing_addr_line2').value
	document.getElementById('delivery_town').value = document.getElementById('billing_town').value
	document.getElementById('delivery_county').value = document.getElementById('billing_county').value
	document.getElementById('delivery_country').value = document.getElementById('billing_country').value
	return false;
}

function find_address(postcode_elm, type) {
	if(postcode_elm.value == "") return false;
	if(which_address != null) return false;
	if(document.getElementById('addresses_list_container')) {
		document.getElementById('addresses_list_container').style.display = "none";
	}
	if(document.getElementById('billing_addresses_list_container')) {
		document.getElementById('billing_addresses_list_container').style.display = "none";
	}
	if(document.getElementById('delivery_addresses_list_container')) {
		document.getElementById('delivery_addresses_list_container').style.display = "none";
	}
	if(type!=''){
		which_address = type+'_';
	}else{
		which_address = type;
	}
	document.getElementById(which_address+'address_button').className = "btnLoadingAddress";
	postcode_elm.onaddresslookup = function(e) { display_addresses(e); };
	RPC("address", "lookup_postcode", postcode_elm, "onaddresslookup", Array(postcode_elm.value));
	return false;
}

function display_addresses(e) {
	document.getElementById(which_address+'address_button').className = "btnFindAddress";

	if(typeof(e) == "string") {
		alert(e);
		which_address = null;
		return false;
	}

	document.getElementById(which_address+'addresses_list').options.length = 0;
	for(i=0; i<e.length; i++) {
		txt = "";
		for(j=0; j<e[i].length; j++) {
			if(e[i][j] != "") {
				txt = txt + e[i][j] + ' ';
			}
		}
		document.getElementById(which_address+'addresses_list').options[i] = new Option(txt, i);
	}
	document.getElementById(which_address+'addresses_list_container').style.display = "block";
	jsaddressList = e;
	which_address = null;
}

function complete_address(num, w_addr)
{
	if(isNaN(num)) return false;

	/*
	 Tidy the address to fit into 4 lines (plus town, county, postcode) & fill the fields from the top.
	 Arrange the premise information according to it's content. (e.g. add numbers to the street).
	*/

	var count = 0;
	var firstlinecount = 0;
	var address = ['','','','',''];
	var fullAddLines = false;
	var premIsNum = isNum(jsaddressList[num][1]);
	var splitcomplete = false;

	// determine if all the address lines contain data
	if (jsaddressList[num][1] != '' && jsaddressList[num][2] != '' && jsaddressList[num][3] != '' && jsaddressList[num][4] != '' && jsaddressList[num][5] != ''){
		fullAddLines = true;
	}

	// sometimes the premise line will contain flat or unit information seperated from the
	// premise number by a comma ( AB39 2HS ). Or it may contain two address lines
	// ( HD7 5UZ ). The premise number should appear on the next line with the street.
	// Extra address lines should appear on their own line (if one is free).

	var premiseSplit = jsaddressList[num][1].split(",");

	if (premiseSplit.length > 1){
		// more than one address element in the premise field.

		// if the second element is a number, move it to the beginning of the next occupied line.
		if (isNum(premiseSplit[1])){
			jsaddressList[num][1] = premiseSplit[0];
			for (i=2;i<6;i++){
				if (jsaddressList[num][i] != ''){
					jsaddressList[num][i] = premiseSplit[1]+' '+jsaddressList[num][i];
					break;
				}
			}
			splitcomplete = true;
		}
		// if all address lines aren't full, move the fields down to make room
		// for the extra element found in the premise line.
		if (fullAddLines == false && splitcomplete == false){
			// find the first gap in the top 4 address lines
			for (i=2;i<6;i++){
				if (jsaddressList[num][i] == ''){
					gap = i;
					break;
				}
			}
			// all content above the gap must be moved down, starting from 1 above the gap.
			for (i=gap;i>2;i--)	{
				jsaddressList[num][i] = jsaddressList[num][i-1];
			}

			// let the premise line contain the first part of the split
			jsaddressList[num][1] = premiseSplit[0];

			// move the second part of the split into the new blank space.
			jsaddressList[num][2] = premiseSplit[1];
		}
	}



	// loop through the address lines, rearrange the premise and move numbers to the street field
	// fill the array 'address', with the correct data from the top down.
	for (i=1;i<6;i++){
		if (jsaddressList[num][i] != ''){
			if(count == 0){ // if on the first line of the address
				address[0] += jsaddressList[num][i];
				if (fullAddLines == true){
					address[0] += ', ';
				}
				else{
					address[0] += ' ';
				}
				firstlinecount++;

				if ((premIsNum == false && fullAddLines == false) || firstlinecount == 2){
					count++; // proceed to the next address line
				}
			}
			else{
				address[count++] += jsaddressList[num][i];
			}
		}
	}

	addr1 = "";
	if(jsaddressList[num][0] != "") {
		addr1 = addr1 + jsaddressList[num][0].replace(/\s+$/,"") + ', ';
	}
	if(address[0] != "") {
		addr1 = addr1 + address[0].replace(/\s+$/,"") + ', ';
	}
	if(jsaddressList[num][0] == "") {
		if(address[1] != "") {
			addr1 = addr1 + address[1].replace(/\s+$/,"") + ', ';
		}
	}
	addr1 = addr1.replace(/,\s$/,"");

	addr2 = "";
	if(jsaddressList[num][0] != "") {
		if(address[1] != "") {
			addr2 = addr2 + address[1].replace(/\s+$/,"") + ', ';
		}
	}
	if(address[2] != "") {
		addr2 = addr2 + address[2].replace(/\s+$/,"") + ', ';
	}
	if(address[3] != "") {
		addr2 = addr2 + address[3].replace(/\s+$/,"") + ', ';
	}
	addr2 = addr2.replace(/,\s$/,"");

	document.getElementById(w_addr+'_addr_line1').value = addr1;
	document.getElementById(w_addr+'_addr_line2').value = addr2;
	document.getElementById(w_addr+'_town').value = jsaddressList[num][6];
	document.getElementById(w_addr+'_county').value = jsaddressList[num][7];

	document.getElementById(w_addr+'_addresses_list_container').style.display = "none";
}

function isNum(inString) {
	// returns true if inString is in the following form:  23   23A   22-23  23/24. This allows
	// a premise number such as 72A to appear on the same line as the street name.
    if (inString.length == 0)
        return false;
    for (var i=0;i < (inString.length-1);i++){
		var testchar = inString.substring(i,i+1);
        if (((testchar < '0') || (testchar > '9')) && (testchar != '-' ) && (testchar != '/' )){
            return false;
		}
	}
    return true;
}

function updateBillingAddress(){

	elm = document.getElementById('billing_address');

	elm.updateBillingAddressResponse = function(e) {
		elm.innerHTML = e;
	}

	var selectBox = document.changeAddress.bill_address;

	for (var i = 0; i < selectBox.options.length; i++){
		if(selectBox.options[i].selected ){
			var address_id = selectBox.options[i].value;

		}
	}

	RPC("customer", "updateBillingAddress", elm, "updateBillingAddressResponse", Array(address_id));
}

function updateDeliveryAddress(){
	elm = document.getElementById('delivery_address');

	elm.updateDeliveryAddressResponse = function(e) {
		//document.location.reload();  // generates re-post msg in ue
		//elm.innerHTML = e;  // update via jax.. but doesnt update
		document.forms['changeAddress'].submit();

	}



	var selectBox = document.changeAddress.del_address;
	for (var i = 0; i < selectBox.options.length; i++){
		if(selectBox.options[i].selected ){
			var address_id = selectBox.options[i].value;
		}
	}

	RPC("customer", "updateDeliveryAddress", elm, "updateDeliveryAddressResponse", Array(address_id));

}

function deleteAddress(address_id){
	todelete =  confirm('You sure you want to delete this address?');
	if(!todelete){
		return false;
	}else{

		elm = document.getElementById('addr_row_'+address_id);

		elm.deleteAddressResponse = function(e) {
			if(e == "last"){
				alert('Cannot delete, you must have at least one address');
			}else{
				elm.style.display = "none";
			}
		}

		RPC("customer", "deleteAddress", elm, "deleteAddressResponse", Array(address_id));

	}
}

