var startForm;
var navFrame;
var nextCommand;
var controlsDisabled = false;
var clearCommand;

function initPage() {
	startForm = document.getElementById("startForm");
	navFrame = window.parent.topFrame;
	nextCommand = page.nextButtonCommand;
	clearCommand = page.clearBookingsCommand;
}

function handleBodyOnLoad(navButtonIdToDisplay, nextCommandCode, tabIdToSelect, tabIdsToDisplay,
                selectedMenuItemClass,isLoggedIn,agencyName, clearBookingsCommandCode) {
    startForm = document.startForm;
    navFrame = window.parent.topFrame;
    nextCommand = nextCommandCode;
    clearCommand = clearBookingsCommandCode;

    initializeMenu(['quote'], selectedMenuItemClass);

    if(tabIdToSelect) {
        if(navFrame.navFrameLoaded) {
            navFrame.initializeControls(navButtonIdToDisplay,tabIdToSelect,tabIdsToDisplay);
        }
    }

    if(isLoggedIn) {
        window.parent.topFrame.loggedIn(agencyName);
    } else {
        window.parent.topFrame.notLoggedIn();
    }

	 navFrame.enableSubmitters();
	 if(navFrame.document.navForm.brandRegion.value!=startForm.brandRegion.value) {
		navFrame.location.reload(true);
	 }
    undoBack(window);
}

function disableControls() {
	controlsDisabled = true;
}

function enableControls() {
	controlsDisabled = false;
}

function formatPassengerNames() {
	//remove any ',' in the passenger name fields
	for(var i=0; i<6; ++i) {
		var key = 'adult'+i+'FirstName';
		var firstName = document.getElementById(key);
		if(firstName) {
			var value = firstName.value;
			firstName.value = stripCharsInBag(value, ',');
		}
		key = 'adult'+i+'LastName';
		var lastName = document.getElementById(key);
		if(lastName) {
			var value = lastName.value;
			lastName.value = stripCharsInBag(value, ',');
		}
		key = 'child'+i+'FirstName';
		firstName = document.getElementById(key);
		if(firstName) {
			var value = firstName.value;
			firstName.value = stripCharsInBag(value, ',');
		}
		key = 'child'+i+'LastName';
		var lastName = document.getElementById(key);
		if(lastName) {
			var value = lastName.value;
			lastName.value = stripCharsInBag(value, ',');
		}
	}
}

function handleNavButtonOnClick() {
	formatPassengerNames();
	
    if(validate()) {
        startForm.command.value=nextCommand;
        startForm.submit();
    }
}

function handleRegionChange(commandCode, hasBookings, regionElement, selectedIndex) {
	if(!controlsDisabled) {
		window.parent.topFrame.disableSubmitters();
		if(hasBookings) {
			if(!confirm('Changing region will clear all previously selected items!')) {
				selectOption(regionElement,selectedIndex);
				window.parent.topFrame.enableSubmitters();
				return false;
			}
		}
		var regionValue = regionElement.value;
//		var newBrandRegionId = regionValue.substring(regionValue.indexOf(':')+1);
		
//		startForm.brandRegion.value = newBrandRegionId;
		startForm.command.value = commandCode;
		startForm.submit();
	}
}

function handleDestinationOnChange(element, elementIndex, hasBookings, oldSelection) {
	if(!controlsDisabled) {
		//If bookings have been made, offer to save or clear
		if(hasBookings) {
			//Warn this will affect current bookings
			if(confirm('Changing destinations may affect current bookings.  Click "OK" to commit change.')) {
				destinationChanged(element, elementIndex);
				//Offer to delete bookings
				if(confirm('Current bookings may conflict with this new destination.\n'+
						'Click "OK" to delete all booked items or "Cancel" to handle yourself.')) {
					//Set the form command and submit the form
					window.parent.topFrame.disableSubmitters();
					startForm.command.value = clearCommand;
					startForm.submit();
				}
			} else {
				//revert selection
				element.selectedIndex = oldSelection;
			}
		}
	}
}

function destinationChanged(element, elementIndex) {
	// If this is not the first destination element the first item will be blank.
	// Therefore if they have a subsequent destination to blank we should clear
	// any related number of nights value
	if ((element.selectedIndex == 0) && (elementIndex > 0)) {
		var nightsElement = document.getElementById('nights' + elementIndex);
		if (nightsElement != null) {
			nightsElement.value = '';
		}
	}
}

function getChildAge(index) {
	var age = -1;
	
	var posCount = 0;
	for(var childIndex = 0; childIndex < 5; ++childIndex) {
		var elementId = 'child' + childIndex + 'Age';
		var element = document.getElementById(elementId);
		if (element != null) {			
			if (posCount == index) {
				age = parseInt(element.value);
				break;
			}
			posCount++;
		}
	}
	
	return age;
}

function createTrip() {
	tracein();
	var departDate = document.getElementById('departureDate').value;
	var returnDate = document.getElementById('returnDate').value;
	var duration = document.getElementById('nights').value;
	var region = getSelectedValue(document.getElementById('region'));
	debug(DEBUG, 'region', region);
	debug(DEBUG, 'departDate', departDate);
	debug(DEBUG, 'returnDate', returnDate);
	debug(DEBUG, 'duration', duration);
	
	var trip = new Trip(region, duration, departDate, returnDate);
	
	function createTripDestinations() {	
		tracein();	
		for (var destIndex = 0; destIndex < 3; ++destIndex) {
			nightsElement = document.getElementById('nights' + destIndex);
			destElement = document.getElementById('destination' + destIndex);
	
			if ((nightsElement != null) && (destElement != null)) {
			  var numNights = parseInt(nightsElement.value);
		      if (numNights > 0) {		
				  var dest = new Destination(destElement.value, numNights);
				  trace('new Destination. name=' + destElement.value + ' nights=' + numNights);
				  trip.addDestination(dest);
			  }
			}
		}
		traceout();
	}
	
	function createTripPassengers() {
		tracein();
		
		var adultCount = parseInt(getSelectedValue(document.getElementById('adultCount')));
		debug(DEBUG, 'adultCount', adultCount);
		for (var adultIndex = 0; adultIndex < adultCount; adultIndex++) {
			var adult = new Passenger(PassengerType().adult);
			trip.addPassenger(adult);
		}
		
		var childCount = parseInt(getSelectedValue(document.getElementById('childCount')));
		debug(DEBUG, 'childCount', childCount);
		for (var childIndex = 0; childIndex < childCount; childIndex++) {
			var age = getChildAge(childIndex)
			var child = new Passenger(PassengerType().child, age);
			trip.addPassenger(child);
		}
		
		var infantCount = parseInt(getSelectedValue(document.getElementById('infantCount')));
		debug(DEBUG, 'infantCount', infantCount);
		for (var infantIndex = 0; infantIndex < infantCount; infantIndex++) {
			var infant = new Passenger(PassengerType().infant);
			trip.addPassenger(infant);
		}			
		
		traceout();	
	}
	
	createTripDestinations();
	createTripPassengers();
	
	trace('returning trip');
	return trip;
}

function validate() {   
	tracein();
	var tripValidator = new Validator(validateTrip);
	var trip = createTrip();
	
	if (tripValidator.validate(trip)) {
		trace('validate() returning true');
		return true;
	}
	else {
		var errorMsg = tripValidator.messages[0];
		alert(errorMsg);
		
		trace('validate() returning false');		
		window.parent.topFrame.enableSubmitters();
		return false;
	}        
}

function handleStartOverOnClick(commandCode) {
	 if(!controlsDisabled) {
	    if(confirm("Click OK to discard your changes and start over or Cancel to continue")) {
				window.parent.topFrame.disableSubmitters();
				startForm.command.value=commandCode;
				startForm.submit();
				return;
	    }
	    window.parent.topFrame.enableSubmitters();
	 }
}


function handleAdultsOnChange(adults) {
    var adultCount = parseInt(getSelectedValue(adults));
    for(var i=0; i<6; ++i) {
        var elementId = 'adult'+i;
        document.getElementById(elementId).style.display=(i<adultCount)?'':'none';
        elementId = 'adultSpacer'+i;
        document.getElementById(elementId).style.display=(i<adultCount)?'':'none';
    }
}

function handleChildrenOnChange(children) {
    var childCount = parseInt(getSelectedValue(children));
    for(var i=0; i<5; ++i) {
        var elementId = 'child'+i;
        document.getElementById(elementId).style.display=(i<childCount)?'':'none';
        elementId = 'childSpacer'+i;
        document.getElementById(elementId).style.display=(i<childCount)?'':'none';
        elementId = 'childHeader'+i;
        document.getElementById(elementId).style.visibility=(i<childCount)?'visible':'hidden';
        elementId = 'child'+i+'Age';
        document.getElementById(elementId).style.visibility=(i<childCount)?'visible':'hidden';
    }
    if(childCount>0) {
        document.getElementById('agesLabel').style.visibility='visible';
    } else {
        document.getElementById('agesLabel').style.visibility='hidden';
    }
}

function handleInfantsOnChange(infants) {
    var infantCount = parseInt(getSelectedValue(infants));
    for(var i=0; i<3; ++i) {
        var elementId = 'infant'+i;
        document.getElementById(elementId).style.display=(i<infantCount)?'':'none';
        elementId = 'infantSpacer'+i;
        document.getElementById(elementId).style.display=(i<infantCount)?'':'none';
    }
}

function handleCalendarOnClose(targetField) {
	if(!controlsDisabled) {
		dateChanged(targetField, 'departureDate', 'returnDate', 'nights');
	}
}

function handleCalendarOnClick(calendarElement) {
	if(!controlsDisabled) {
		openCalendar(calendarElement);
	}
	return true;
}

