
var no_delivery_methods_found = $("no_delivery_methods_found");
/*if(no_delivery_methods_found) {
    no_delivery_methods_found.style.display = "block";
}*/

var delivery_method_data = $("delivery_method_data");
/*if(delivery_method_data) {
    delivery_method_data.style.display = "none";
}*/

// retrieves the XMLHttprequest object
function createXmlHttpRequestObject()
{
    
    // will store the reference to the XMLHttpRequest object
    var xmlHttp;
    // if running Internet Explorer
    if(window.ActiveXObject)
    {
	try {
	    xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
	} catch (e){
	    xmlHttp = false;
	}
    }
    
    // if running mozilla or other browsers
    
    else {
	
	try {
	    
	    xmlHttp = new XMLHttpRequest();
	    
	} catch (e) {
	    
	    xmlHttp = false;
	    
	}
	
    }
    
    // return the created object or display an error message
    if(!xmlHttp) {
	alert("Error creating the XMLHttpRequest object.");
	return false;
    } else {
	return xmlHttp;
    }
}


// stores the reference to the XMLHttpRequest object
var xmlHttp = createXmlHttpRequestObject();
var xmlHttp__uriQueue = new Array();
function xmlHttp__uriQueueItem(uriStr, cb) {
    this.uriString = uriStr;
    this.callback = cb;
}

var country_select = $('country_select');
var delivery_method_select = $('delivery_method_select');

var country_value = '';

function updateCountryValue() {
    if(country_select) {
	country_value = country_select.value;
    }
}

function resetDeliveryList() {
    if(delivery_method_select) {
		while(delivery_method_select.firstChild) {
			delivery_method_select.removeChild(delivery_method_select.firstChild);
		}
    }
    if(delivery_method_data) {
		delivery_method_data.addClass('hide');
    }
    if(no_delivery_methods_found) {
		no_delivery_methods_found.removeClass('hide');
    }
    stop_auto_submit = true;
}
	

function getDeliveryMethodList(stop_auto_submit) {
    updateCountryValue();
    
    var delivery_postcode_data = $('delivery_postcode_data');
    var delivery_postcode_input = $('delivery_postcode');
    if(delivery_postcode_data != null) {
		if(country_value == 'gb') {
			/**
			 * Need to allow the user to enter their post-code so we can
			 * check against the list of free-delivery postcodes
			 */
			delivery_postcode_data.removeClass('hide');
		}
		else delivery_postcode_data.addClass('hide');
    }
    
    if(country_value == '0' || country_value == 'gb' && delivery_postcode_input != null && delivery_postcode_input.value.length == 0) {
		resetDeliveryList();
		if(no_delivery_methods_found) {
			no_delivery_methods_found.addClass('hide');
		}
		return false;
    }
    else {
		var requestURI = "_load_delivery_methods.php?iso="+country_value+(delivery_postcode_input != null ? "&delivery_postcode="+encodeURIComponent(delivery_postcode_input.value): '');
		var requestCallbackPtr = stop_auto_submit ? handleDeliveryMethodList_NoSubmit : handleDeliveryMethodList_Submit;
		// proceed only if the xmlHttp object isn't busy
		if(xmlHttp.readyState == 4 || xmlHttp.readyState == 0) {
			xmlHttp.open("GET", requestURI, true);
			//define the method to handle server response
			xmlHttp.onreadystatechange = requestCallbackPtr;
			// post variables
			xmlHttp.send(null);
		} else {
			//alert("Sorry, the list of delivery methods could not be loaded.  You can proceed to checkout and select your delivery method later.");
			xmlHttp__uriQueue.push(new xmlHttp__uriQueueItem(requestURI, requestCallbackPtr));
		}
		return false;
    }
}

function handleDeliveryMethodList_Submit() {
    handleDeliveryMethodList(false);
}
function handleDeliveryMethodList_NoSubmit() {
    handleDeliveryMethodList(true);
}

// executed automatically when a message is receieved from the server
function handleDeliveryMethodList(stop_auto_submit) {
    // move forward only if the transaction has completed
    if(xmlHttp.readyState == 4) {
	// status of 200 indicates the transaction completed successfully
	if(xmlHttp.status == 200) {
		
	    // extract the XML retrieved from the server
	    var xmlResponse = xmlHttp.responseXML;
	    // obtain the document element (the root element) of the XML structure
	    var xmlDocumentElement = xmlResponse.documentElement;
	    var methods = xmlDocumentElement.getElementsByTagName('method');
	    
	    resetDeliveryList();
		
		var last_method_ref;
	    
	     for (j=0;j<methods.length;j++) {
			
			new_option_cont = new Element('p');
			
			new_option_jq = new Element('input', {type:'radio', name:'delivery_method_id', value:methods[j].getAttribute('id'), id:'method_'+methods[j].getAttribute('id')});
			
			new_option_jq.addEvent('change', function() { submitBasketForm(); } );
			new_label_jq = new Element('label', {'for':'method_'+methods[j].getAttribute('id')});
			new_label_jq.set('text', methods[j].firstChild.nodeValue);
			
			new_option_cont.grab(new_option_jq);
			new_option_cont.grab(new_label_jq);
			
			if(delivery_method_select) {
				$(delivery_method_select).grab(new_option_cont);
			}
			
			last_method_ref = 'method_'+methods[j].getAttribute('id');
	    }
	    
	    if(methods.length > 0) {
			
			if(no_delivery_methods_found) {
				no_delivery_methods_found.addClass('hide');
			}
			if(delivery_method_data) {
				delivery_method_data.removeClass('hide');
			}
			/* If there is only one method, submit the form automatically for the user */
			if(methods.length == 1) {
				$(last_method_ref).set('checked', true);
				if(stop_auto_submit === false) {
					submitBasketForm();
				}
			}
		} else {
			resetDeliveryList();
			if(no_delivery_methods_found) {
				no_delivery_methods_found.removeClass('hide');
			}
	    }

	} else {
		alert('Sorry, the list of delivery methods could not be loaded.  You can proceed to checkout and select your delivery method later.');
	}
	
	/**
	 * Process any queued xmlHttp requests
	 */
	var nextRequest = xmlHttp__uriQueue.shift();
	if(nextRequest != null) {
	    xmlHttp.open("GET", nextRequest.uriString, true);
	    //define the method to handle server response
	    xmlHttp.onreadystatechange = nextRequest.callback;
	    // post variables
	    xmlHttp.send(null);
	}
    }
}


function submitBasketForm() {
    for(k=0;k<document.forms.length;k++) {
	if(document.forms[k].id == "basket-form") {
	    frm = document.forms.item(k);
	    frm.submit();
	}
    }
}

function getDeliveryMethodList_NoSubmit() {
    getDeliveryMethodList(true);
}

function getDeliveryMethodList_Submit() {
    getDeliveryMethodList(false);
}

window.onload = function(evnt) {
	evnt = evnt == null ? window.event : evnt;
	/**
	 * The basket delivery thingy isn't supported sans
	 * JavaScript, so is served hidden.
	 * Let's show it.
	 */	
    var delivery_postcode_data = document.getElementById('delivery_postcode_data');
	if(delivery_method_select) {
		var methods = $(delivery_method_select).getElements('option');
		var method_count = 0;
		for(var i=0; i < methods.length; ++i) {
			if(methods[i].value.length > 0) ++method_count;
		}
		
		$('delivery_country_data').removeClass('hide');
		/*$(delivery_postcode_data).removeClass('hide');
		if(method_count > 0)  $('delivery_method_data').removeClass('hide');
		if(method_count == 0) $('no_delivery_methods_found').removeClass('hide');
		*/
		//Run the postcode changed handler
		deliveryPostcodeChanged(evnt);
	}
	//Set-up event listeners
    if(delivery_postcode_data != null) {
		delivery_postcode_data.onkeyup = deliveryPostcodeChanged;
		//delivery_postcode_data.onchange = deliveryPostcodeChanged;
    } 
}
if(country_select) {
    country_select.onchange = getDeliveryMethodList_Submit;
}

function deliveryPostcodeChanged(evnt) {
    getDeliveryMethodList(true);
}
