suppressClearingAddress = false;

function addressFieldChanged(obj) {
    suppressClearingAddress = true;
    if (obj.id.indexOf('id_delivery') != -1) {
        document.getElementById('idDeliveryAddress').value = 0;
    }
    else {
        document.getElementById('idInvoiceAddress').value = 0;
    }
    suppressClearingAddress = false;
}

var addressFields =  [ 'addressName', 'personName', 'companyName', 'address1', 'address2', 'city', 'postalCode', 'postalCity', 'NIP', 'phone', 'faxNumber', 'email' ];

function modify_deliveryShowUserAddress(comboboxId, fieldPrefix){
	var combobox = document.getElementById(comboboxId);
	var value  = combobox.value;
	var fields = addressFields;

	if (value > 0){
        // Jeśli ktoś już wybrał taki adres i zmodyfikował jego pola przepiszemy
        // wartości zmodyfikowane. Jeśli nie zmodyfikował - adres jest nietknięty
        // i nie trzeba go ściągać przez AJAX   
        /*if (document.getElementById("idDeliveryAddress") && document.getElementById("idInvoiceAddress") && document.getElementById("idDeliveryAddress").value == document.getElementById("idInvoiceAddress").value) {    
            for (i in fields) {
                var fi = fields[i];
                if (fieldPrefix == 'id_delivery') {
                    document.getElementById('id_delivery-'+fi).value = document.getElementById('id_invoice-'+fi).value;
                }
                else {
                    document.getElementById('id_invoice-'+fi).value = document.getElementById('id_delivery-'+fi).value;
                }
            }
            return;
        }*/
        var addressStore = new dojo.data.ItemFileReadStore({
        	url: "/shop/delivery/loadAddress/"+value
        });
        addressStore.fetchItemByIdentity({
        identity: "address", 
        onItem: function(item){
            for (i in fields) {
                document.getElementById(fieldPrefix+"-"+fields[i]).value = addressStore.getValue(item,fields[i]);
            }
            checkNIPrequirement();
        }
        });
    }
	else if (! suppressClearingAddress) {
        for ( i in fields) {
            document.getElementById(fieldPrefix+"-"+fields[i]).value = '';
        }
        checkNIPrequirement();
	}
}

function modify_deliverySendForm()
{
	if (checkAdditionalCommentsLength()){
		console.log("modifyDeliverySendForm");
		document.getElementById('edit_delivery').submit();
	}
}

function edit_delivery() {
    window.location = '/shop/delivery/edit';
}

function checkNIPrequirement() {
    var obj;
    if (document.getElementById('useTheSameAddresAsForDelivery') && document.getElementById('useTheSameAddresAsForDelivery').checked) {
        obj = document.getElementById('id_delivery-NIP');
    }
    else {
        obj = document.getElementById('id_invoice-NIP');
    }
    document.getElementById('invoiceWithoutNIP').style.display=(obj.value ? "none":"block");
}


function updateUseTheSameAddresAsForDelivery(obj) {
    if (obj) {
        if (obj.checked) {
            document.getElementById('selectInvoiceAddress').style.visibility = "hidden";
            document.getElementById('invoiceFormDiv').style.visibility = "hidden";
        }
        else {
            document.getElementById('selectInvoiceAddress').style.visibility = "visible";
            document.getElementById('invoiceFormDiv').style.visibility = "visible";
        }
    }
    checkNIPrequirement();
}

function checkAdditionalCommentsLength() {
    var comments =  document.getElementById("additionalComments");
    if (comments.value.length > 128) {
        comments.style.backgroundColor = "#FFFF99";
        document.getElementById("additionalCommentsTooLongInfo").style.visibility = "visible";
        return false;    
    }
    else {
        comments.style.backgroundColor = "#ffffff";
        document.getElementById("additionalCommentsTooLongInfo").style.visibility = "hidden";
        return true;
    }
}

// Przepisuje dane z jednego pola do drugiego
// (Zwraca funkcję anonimową aby zachowane zostały pola w scopie)
function synchronizeFields(field1,field2) {
	return function () {
	   if (document.getElementById("idDeliveryAddress").value == document.getElementById("idInvoiceAddress").value && 
	   	   document.getElementById("idDeliveryAddress").value !== 0) {
	      field2.value = field1.value;
	   }
	};
}


// Funkcja zapewnia synchronizację wszystkich pól dwóch formularzy adresów, gdy wybrany jest ten 
// sam adres (możliwe było wpisanie różnych danych podczas zmiany tego samego adresu)
function registerAddressSynchronization(invoiceDataForm) {
    var fieldsToSynch = addressFields;
    for (var i=0; i<fieldsToSynch.length; i++) {
        if (fieldsToSynch[i] != 'addressName') {
            var f1 = document.getElementById("id_delivery-"+fieldsToSynch[i]);
            var f2 = document.getElementById("id_invoice-"+fieldsToSynch[i]);
            if (f1 !== null && f2 !== null) {
            	f1.onchange = synchronizeFields(f1, f2);
            	f2.onchange = synchronizeFields(f2, f1);
            }
        }
    }
}

