

function Setup(){
	//alert("Setup called");
	var dateTextField = document.getElementById("date");
	if( !dateTextField ){
		alert("No date text field in page"); 
		return;
	}
	
	// create our popup menu container
	var datePopupMenu = document.createElement('select');
	datePopupMenu.setAttribute('id', 'datePickerMenu');
	datePopupMenu.setAttribute('name', 'date');
	
	// replace our text field with the popup menu
	// we have to do this early since the UpdateLocations callback can
	// fire before we've finished
	var parent = dateTextField.parentNode;
	parent.replaceChild( datePopupMenu, dateTextField );
	
	var locationPopup = document.getElementById("location");
	// see if we are pre-filled with a value so we're not confusing to the user
	if( locationPopup.selectedIndex != 0 ){
		UpdateLocations( locationPopup.options[locationPopup.selectedIndex].value );
	}else{	
		// Add a dummy element for 'choose location'
		var initialOption =  document.createElement('option');
		initialOption.appendChild( document.createTextNode('Choose Location..') );
		initialOption.setAttribute('value','');
		datePopupMenu.appendChild(initialOption);
	}
}

function UpdateLocations(loc_key){
	gCSNW_Ajax.Call("/includes/helpdesk/get_dates_for_location.php?loc_key="+loc_key, CallComplete, 'GET');
}

function CallComplete(status, data){

	var datePickerMenu = document.getElementById("datePickerMenu");
	if( ! datePickerMenu ){
		alert("No datePickerMenu element in page");
		return;
	}
	
	if( status ){
		var resultOptions = eval( data );
		
		// Clear the menu of old values
		while( datePickerMenu.hasChildNodes() ){
			datePickerMenu.removeChild( datePickerMenu.firstChild );
		}
		
		// Insert our placeholder empty element
		var optionElement = document.createElement("option");
		optionElement.appendChild( document.createTextNode('Choose..') );
		optionElement.setAttribute('value', '');
		datePickerMenu.appendChild( optionElement );
		
		if( resultOptions ){
			// loop over the result array and add the entries to the popup
			for(var i=0; i< resultOptions.length; i++ ){
				var optionElement = document.createElement('option');
				optionElement.appendChild( document.createTextNode( resultOptions[i].name ) );
				optionElement.setAttribute('value', resultOptions[i].value);
				datePickerMenu.appendChild( optionElement );
			}
		}
	}
}



