var currentOrg;
var currentAddress = null;
var currentMode = null;
var isGuestUser = true;
var submitted = false;

function Organisation(orgId, custId, orgName, addressCount) {
	this.orgId = orgId;
	this.custId = custId;
	this.orgName = orgName;
	this.addresses = new Array(addressCount);
}

function Address(addId, attentionTo, addressLine1, addressLine2, suburb, state, country, postcode, phone, mobile, fax) {
	this.addId = addId;
	this.attentionTo = attentionTo;
	this.addressLine1 = addressLine1;
	this.addressLine2 = addressLine2;
	this.suburb = suburb;
	this.state = state;
	this.country = country;
	this.postcode = postcode;
	this.phone = phone;
	this.mobile = mobile;
	this.fax = fax;
}

function changeAddress(formName) {
	var form = eval('document.' + formName);
	if (form.CUSTOMER_ADDRESS_LIST.selectedIndex > -1) {
		var addId = form.CUSTOMER_ADDRESS_LIST.options[form.CUSTOMER_ADDRESS_LIST.selectedIndex].value;
		var add =  currentOrg.addresses[addId];
		if (add == null) {
			var orgList = eval('document.' + formName + '.ORGANISATION_LIST');
			add = organisations[orgList.options[1].value].addresses[addId];
		}
		if (add != null) {
			setDeliveryAddress(add, formName);			
			currentAddress = add;
		}
	}
}

function changeOrganisation(form) {
}

function changeThisOrgAddress(formName) {
	var form = eval('document.' + formName);
	if (form.ADDDRESS_LIST.length == 1) {
		form.ADDDRESS_LIST.selectedIndex = 0;
	}
	
	if (form.ADDDRESS_LIST.selectedIndex > -1) {
		var addId = form.ADDDRESS_LIST.options[form.ADDDRESS_LIST.selectedIndex].value;
		var add =  currentOrg.addresses[addId];
		if (add != null) {
			setDeliveryAddress(add, formName);			
			currentAddress = add;
		}
	}
}

function addressCheckClick(clicked) {
    var buyerName = document.getElementById("BUYER_NAME");
    var defaultAddressReadOnly = document.getElementById("defaultAddressReadOnly");
    var yourCustomers = document.getElementById("yourCustomers");
    var otherAddress = document.getElementById("otherAddress");
    var readOnlyAddress = document.getElementById("readOnlyAddress");
    var enterableAddress = document.getElementById("enterableAddress");
	makeInvisible("addressListRow");
	makeInvisible("customerListRow");
	makeInvisible("customerAddessListRow");
    if (clicked.value == "defaultAddressCheck") {
    	readOnlyAddress.style.visibility = "visible";
    	enterableAddress.style.visibility = "hidden";
	   	readOnlyAddress.style.display = "block";
	   	enterableAddress.style.display = "none";
        buyerName.className = "adminPrompt";
        yourCustomers.className = "deliveryInactive";
        otherAddress.className = "deliveryInactive";
        if (organisations[buyerOrgId].addresses.length > 1) {
	    	makeVisible("addressListRow");
    	}
		currentOrg = organisations[buyerOrgId];
    	changeThisOrgAddress("orderMaintenanceForm");
    } else if (clicked.value == "customerAddressCheck") {
    	readOnlyAddress.style.visibility = "visible";
    	enterableAddress.style.visibility = "hidden";
	   	readOnlyAddress.style.display = "block";
	   	enterableAddress.style.display = "none";
        buyerName.className = "deliveryInactive";
        yourCustomers.className = "adminPrompt";
        otherAddress.className = "deliveryInactive";
    	makeVisible("customerListRow");
		makeVisible("customerAddessListRow");
		changeCustomer("orderMaintenanceForm");
    } else if (clicked.value == "otherAddressCheck") {
    	readOnlyAddress.style.visibility = "hidden";
	   	readOnlyAddress.style.display = "none";
    	enterableAddress.style.visibility = "visible";
	   	enterableAddress.style.display = "block";
        buyerName.className = "deliveryInactive";
        yourCustomers.className = "deliveryInactive";
        otherAddress.className = "adminPrompt";
        currentAddress = null;
    }
}

function makeInvisible(tagId) {
    var tag = document.getElementById(tagId);
    if (tag != null) {
	   	tag.style.visibility = "hidden";
	   	tag.style.display = "none";
   	}
}
function makeVisible(tagId) {
    var tag = document.getElementById(tagId);
    if (tag != null) {
	   	tag.style.visibility = "visible";
	   	tag.style.display = "block";
   	}
}

function changeCustomer(formName) {
	var form = eval('document.' + formName);
	var orgList = eval('document.' + formName + '.ORGANISATION_LIST');
	var addList = eval('document.' + formName + '.CUSTOMER_ADDRESS_LIST');

	if (orgList.selectedIndex > -1) {
		var orgId = orgList.options[orgList.selectedIndex].value;
		var org = organisations[orgId];
		for (var i = addList.options.length; i > 0; i--) {
			addList.options[i-1] = null;
		}
		if (org != null) {
			form.CUSTOMER_ID.value = org.custId;
			currentOrg = org;
			if (org.addresses.length > 1) {
				addList.options[addList.options.length] = new Option("Select the delivery address", "");
			}
			for (var i = 0; i < org.addresses.length; i++) {
				var addLine = org.addresses[i].addressLine1 + ", " +  org.addresses[i].suburb + ", " + org.addresses[i].state;
				var opt = new Option(addLine, i);
				opt.selected = (org.addresses[i].addressLine1 == form.DELIVERY_ADDRESS_LINE1.value &&
				    org.addresses[i].suburb == form.DELIVERY_SUBURB.value
				    && org.addresses[i].state == form.DELIVERY_STATE.value);
				addList.options[addList.options.length] = opt;
			}
			if (org.addresses.length == 1) {
				addList.selected = 1;
				changeAddress(formName);
			}
		}
	}
}

function populateAddressesForOrg(formName) {
	var addList = document.orderMaintenanceForm.ADDDRESS_LIST;
	var buyerOrg = organisations[buyerOrgId];
	currentOrg = buyerOrg;
	if (buyerOrg.addresses.length > 1) {
		addList.options[addList.options.length] = new Option("Select the delivery address", "");
	}
	for (var i = 0; i < buyerOrg.addresses.length; i++) {
		var addLine = buyerOrg.addresses[i].addressLine1 + ", " +  buyerOrg.addresses[i].suburb + ", " + buyerOrg.addresses[i].state;
		var opt = new Option(addLine, i);
		opt.selected = (buyerOrg.addresses[i].addressLine1 == document.orderMaintenanceForm.DELIVERY_ADDRESS_LINE1.value &&
		    buyerOrg.addresses[i].suburb == document.orderMaintenanceForm.DELIVERY_SUBURB.value
		    && buyerOrg.addresses[i].state == document.orderMaintenanceForm.DELIVERY_STATE.value);
		addList.options[addList.options.length] = opt;
	}
	if (buyerOrg.addresses.length == 1) {
		makeInvisible("addressListRow");
	}

}

function setDeliveryAddress(add, formName) {
	var form = eval('document.' + formName);
	var countryList = document.orderMaintenanceForm.DELIVERY_COUNTRY_LIST;
	var countryName = "";
	for (var i = 0; i < countryList.options.length; i++) {
		if (countryList.options[i].value == add.country) {
			countryList.selectedIndex = i;
			countryName = countryList.options[i].text;
		}
	} 
	setSpanValue("DELIVERY_ORGANISATION_NAME", currentOrg.orgName);
	setSpanValue("DELIVERY_ADDRESS_LINE1", add.addressLine1);
	setSpanValue("DELIVERY_ADDRESS_LINE2", add.addressLine2);
	setSpanValue("DELIVERY_SUBURB", add.suburb);
	setSpanValue("DELIVERY_STATE", add.state);
	setSpanValue("DELIVERY_POSTCODE", add.postcode);
	setSpanValue("DELIVERY_PHONE", add.phone);
	setSpanValue("DELIVERY_MOBILE", add.mobile);
	setSpanValue("DELIVERY_COUNTRY", countryName);
	setSpanValue("DELIVERY_FAX", add.fax);
}

function setSpanValue(tagId, textValue) {
	var element = document.getElementById(tagId);
	if (textValue == "" || textValue == "undefined" || textValue == "null") {
		document.getElementById(tagId).parentNode.style.visibility = "hidden";
		document.getElementById(tagId).parentNode.style.display = "none";
	}
	else {
		document.getElementById(tagId).parentNode.style.visibility = "visible";
		document.getElementById(tagId).parentNode.style.display = "block";
	}
	element.innerHTML = textValue;
}

function showCheckout() {
	makeInvisible("templateFields");    
	makeVisible("checkoutFields");
	var objDiv = document.getElementById("checkoutFields");
	objDiv.scrollTop = objDiv.scrollHeight;	
}

function showTemplates() {
	makeInvisible("checkoutFields");    
	makeVisible("templateFields");
}

function showHelp(element, imageSrc) {
	var helpElement = document.getElementById(element + "_HELP");
	if (helpElement != null) {
		helpElement.style.visibility = "visible";
		helpElement.style.display = "block";
	}
	var imageElement = document.getElementById(element + "_IMAGE");
	if (imageElement != null) {
		imageElement.src = imageSrc;
	}
}

function hideHelp(element, imageSrc) {
	var helpElement = document.getElementById(element + "_HELP");
	if (helpElement != null) {
		helpElement.style.visibility = "hidden";
		helpElement.style.display = "none";
	}
	var imageElement = document.getElementById(element + "_IMAGE");
	if (imageElement != null) {
		imageElement.src = imageSrc;
	}
}

function finaliseForm(mode) {
	document.orderMaintenanceForm.ACTION.value=mode;
	if (currentAddress != null) {
		if (currentAddress.attentionTo.length > 0) { 
			document.getElementsByName("DELIVERY_ATTENTION_TO").value = currentAddress.attentionTo;
		}
		document.orderMaintenanceForm.DELIVERY_ORGANISATION_NAME.value = currentOrg.orgName;
		document.orderMaintenanceForm.DELIVERY_ADDRESS_LINE1.value = currentAddress.addressLine1;
		document.orderMaintenanceForm.DELIVERY_ADDRESS_LINE2.value = currentAddress.addressLine2;
		document.orderMaintenanceForm.DELIVERY_SUBURB.value = currentAddress.suburb;
		document.orderMaintenanceForm.DELIVERY_STATE.value = currentAddress.state;
		document.orderMaintenanceForm.DELIVERY_POSTCODE.value = currentAddress.postcode;
		document.orderMaintenanceForm.DELIVERY_PHONE.value = currentAddress.phone;
		document.orderMaintenanceForm.DELIVERY_MOBILE.value = currentAddress.mobile;
		document.orderMaintenanceForm.DELIVERY_COUNTRY.value = currentAddress.countryName;
		document.orderMaintenanceForm.DELIVERY_FAX.value = currentAddress.fax;
		var countryList = document.orderMaintenanceForm.DELIVERY_COUNTRY_LIST;
		var countryName = "";
		for (var i = 0; i < countryList.options.length; i++) {
			if (countryList.options[i].value == currentAddress.country) {
				countryList.selectedIndex = i;
				countryName = countryList.options[i].text;
			}
		} 
	}
}

function submitForm() {
	if (isFormorderMaintenanceFormValid()) {
		submitted = true;
		document.orderMaintenanceForm.submit();
		return true;
	}
}

function buildOrderUrl(customerOrderId) {
  submitted = true;
  document.cancelOrderForm.CUSTOMER_ORDER_ID.value = customerOrderId;
  document.cancelOrderForm.CancelOrder.value = 'true';
  document.cancelOrderForm.submit();
  return false;

}

function submitChanges(updateOnly) {
	if (document.orderMaintenanceForm.agreed.checked || updateOnly) {
		if (isFormorderMaintenanceFormValid()) {
			var deliveryEmail = eval(document.DELIVERY_EMAIL);
			if (!updateOnly && deliveryEmail != null) {
				if (document.orderMaintenanceForm.DELIVERY_EMAIL.value != document.orderMaintenanceForm.CONFIRM_DELIVERY_EMAIL.value) {
					alert('The email address is different from the confirm email address.');
				}
				else {
					submitted = true;
					document.orderMaintenanceForm.submit();
					return true;
				}
			}
			else {
				submitted = true;
				document.orderMaintenanceForm.submit();
				return true;
			}
			return false;
		}
		else {
			return false;
		}
	}
	else {
		alert('You must accept the terms and conditions before the order can be placed.');
		return false;
	}
}

function setup() {
	if (isGuestUser) {
		makeVisible("enterableAddress");
	} else {
		makeVisible("readOnlyAddress");
		populateAddressesForOrg();
	}
	if (window.location.href.indexOf("OPEN_PRINT_DIALOG") != -1) {
		var conj = document.location.href.indexOf('?') == -1 ? '?' : '&';
		var _pfv=window.open(document.location.href + conj + '__B=body', 'PaymentConfirmation', 'width=500,height=600,scrollbars=yes,resizable'); 
		if (!_pfv) {
			alert('You seem to be using pop-up blocker software. Please turn it off to enable the printer-friendly version.');
		}
	}
}

function confirmExit() {
  if (!submitted && isFormorderMaintenanceFormChangedFlag) {
    return "If you have made any changes without saving, your changes will be lost.";
  }
  // no changes - return nothing      
}
window.onbeforeunload = confirmExit;

