

var errorAlert = function(err) {
    alert('Error ' + err.status + ' -- ' + err.statusText);
}

//For an XML response:
var handlerPopulate = function(xmlHttpRequest) {

	var xmlObj = xmlHttpRequest.responseXML;

	var xmlDoc = xmlObj.documentElement;
    //Handle data.
	
	var products = xmlDoc.getElementsByTagName('product');
		
	var productOptn = document.getElementById('form-product');
	
	
	
	if(products.length == 0){
		ClearOptions(productOptn);
		AddToOptionList(productOptn, "", "Select a product category first");
		productOptn.disabled=true;
		
	}
	else{
		ClearOptions(productOptn);
		AddToOptionList(productOptn, "", "All" );
		var currProduct = document.getElementById('current_product');
		if(currProduct == null){
			currProduct = "All";
		}
		else{
			currProduct = currProduct.value;
		}
		for(i=0;i<products.length;i++){
			var productid = getValueByTagName(products,"id");
			AddToOptionList(productOptn, productid, getValueByTagName(products,"description") );

			if(currProduct == productid){
				productOptn.selectedIndex = i+1;
			}
			
		}
		productOptn.disabled=false;
	}
	


}

function ClearOptions(OptionList) {

   // Always clear an option list from the last entry to the first
   for (x = OptionList.length; x >= 0; x--) {
      OptionList[x] = null;
   }
}


function AddToOptionList(OptionList, OptionValue, OptionText) {
   // Add option to the bottom of the list
   OptionList[OptionList.length] = new Option(OptionText, OptionValue);
   
}


function getResponseXml(xmlUrl) {
	var xmlhttp=null
	// code for Mozilla, etc.
	if (window.XMLHttpRequest)
	  {
	  xmlhttp=new XMLHttpRequest()
	  }
	// code for IE
	else if (window.ActiveXObject)
	  {
	  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP")
	  }
	if (xmlhttp!=null){
		xmlhttp.open("GET", xmlUrl, false);
		xmlhttp.send(null);
		return xmlhttp;
	}
else
  {
  alert("Your browser does not support XMLHTTP.")
  }
}

function getValueByTagName(node, tag) {
  var a = node[i].getElementsByTagName(tag)[0];
  if (a) {
    if (a.firstChild && a.firstChild.nodeValue) {
		
      return(a.firstChild.nodeValue);
	  
    }
  } else {
  console.log("node[" + i + "] is null: tag=" + tag);
  }
}

function populateProduct(){

	var productCategory = document.getElementById('form-product-category');
	
	new Ajax.Request('/page_templates/act/act_generate-product-xml.cfm', {parameters:'catid='+productCategory.value, onSuccess:handlerPopulate, onFailure:errorAlert});
	
	

	productCategory.onchange = function(){
		new Ajax.Request('/page_templates/act/act_generate-product-xml.cfm', {parameters:'catid='+productCategory.value, onSuccess:handlerPopulate, onFailure:errorAlert});
	}

}

Event.observe(window, 'load', populateProduct, false);