/**
* Functions for the route selection form and flash movie.
*
* @author Michael Hodgins
*/

/**
* Called from within the flash movie. Sets the 
* departure country and port.
*
* @param country
* @param port
*/
function setDeparturePort(country, port) {
	ccwJsDebugInstance.outputMessage('setDeparturePort', DO_MAP_DEBUG);
	resetElement('leavingCountry');
	resetElement('leavingPort');
	var depCountry = $('leavingCountry');
	for(var i = 0; depCountry.options.length; i++) {
		if (depCountry.options[i].value == country) {
			depCountry.options[i].selected = true;
			break;
		}
	}
	updatePortList(country, 'leavingPort', 'leavingPortSection', port);
	removeSelectOption(depCountry);
	//constrainDestinations();
}

/**
* Called from within the flash movie to set the
* destination country and port.
*
* @param country
* @param port
*/
function setDestinationPort(country, port) {
	ccwJsDebugInstance.outputMessage('setDestinationPort', DO_MAP_DEBUG);
	resetElement('arrivalCountry');
	resetElement('arrivalPort');
	var destCountry = $('arrivalCountry');
	for(var i = 0; destCountry.options.length; i++) {
		if (destCountry.options[i].value == country) {
			destCountry.options[i].selected = true;
			break;
		}
	}
	updatePortList(country, 'arrivalPort', 'arrivalPortSection', port);
	removeSelectOption(destCountry);
	//constrainDepartures();
}

/**
* Resets the the country and port selects to their
* initial values.
*/
function resetForm() {
	ccwJsDebugInstance.outputMessage('resetForm', DO_MAP_DEBUG);
	hideElement('leavingPortSection');
	hideElement('arrivalPortSection');
	hideElement('submitForm');
	['leavingCountry', 'leavingPort', 'arrivalCountry', 'arrivalPort'].each(
		function(item, index) {
			resetElement(item);
		}
	);
	portConstraint = PORT_CONSTRAINT_UNKNOWN;
}

function resetElement(elementId) {
	ccwJsDebugInstance.outputMessage('resetElement', DO_MAP_DEBUG);
	var element = $(elementId);
		if (element.value != 0) {
		element.options.length = 0;
		for (var i = 0; i < initValues[elementId].length; i++) {
			element.options.add(initValues[elementId][i]);
		}
		element.selectedIndex = 0;
	}
}

/**
* Gets the flash map.
*/
function thisMovie(movieName) {
	ccwJsDebugInstance.outputMessage('thisMovie', DO_MAP_DEBUG);
  if (navigator.appName.indexOf ("Microsoft") !=-1) {
    return window[movieName]
  }	else {
    return document[movieName]
  }
}	

function sendDepartureCountryToFlash(country) {
	ccwJsDebugInstance.outputMessage('sendDepartureCountryToFlash', DO_MAP_DEBUG);
    thisMovie("route_movie").sendDepartureCountryToFlash(country);
}
function sendDestinationCountryToFlash(country) {
	ccwJsDebugInstance.outputMessage('sendDestinationCountryToFlash', DO_MAP_DEBUG);
    thisMovie("route_movie").sendDestinationCountryToFlash(country);
}

function sendDeparturePortToFlash(port) {
	ccwJsDebugInstance.outputMessage('sendDeparturePortToFlash', DO_MAP_DEBUG);
    thisMovie("route_movie").sendDepartureToFlash(port);
}
function sendDestinationPortToFlash(port) {
	ccwJsDebugInstance.outputMessage('sendDestinationPortToFlash', DO_MAP_DEBUG);
    thisMovie("route_movie").sendDestinationToFlash(port);
}

function sendOperatorToFlash(operator) {
	ccwJsDebugInstance.outputMessage('sendOperatorToFlash', DO_MAP_DEBUG);
	thisMovie("route_movie").sendOperatorToFlash(operator);
}

function removeSelectOption(elm) {
	ccwJsDebugInstance.outputMessage('removeSelectOption', DO_MAP_DEBUG);
	if (elm.options.length> 0 && elm.options[0].value == 0) {
		elm.remove(0);
	}
	if (elm.value != -1) {
		for(var i = 0; i < elm.options.length; i++) {
			if (elm.options[i].value == -1) {
				elm.remove(i);
				break;
			}
		}
	}
}

function updatePortList(country, elm, container, selectedPort) {
	//debugger;
	ccwJsDebugInstance.outputMessage('updatePortList', DO_MAP_DEBUG);
	var args = {'country':country};
	if (elm == "arrivalPort" && portConstraint == PORT_CONSTRAINT_DEPARTURE) {
		args['fromPort'] = $('leavingPort').value;
	} else if (elm == "leavingPort" && portConstraint == PORT_CONSTRAINT_DESTINATION) {
		args['fromPort'] = $('arrivalPort').value;
	}
	new Request.JSON ({
		url: "/json/getCountryPorts.php",
		onComplete: function(ports) {
			var portSelect = $(elm);
			portSelect.options.length = 0;
			if (ports.length > 0) {
				if (selectedPort == 0) {
					portSelect.options.add(new Option('Select', 0));
				}
				var selectedIndex = 0;
				for(var i = 0; i < ports.length; i++) {
   					portSelect.options.add(new Option(ports[i].name, ports[i].id));
   					if (selectedPort == ports[i].id) {
   						selectedIndex = i;
   					}
   				}
   				if (selectedIndex>0) {
   					portSelect.options[selectedIndex].selected = true;
   				}
   				easeInElement(container);
				updateFormSubmit();
				if (selectedPort != 0) {
					if (elm == 'leavingPort') {
						constrainDestinations();
					} else if (elm == 'arrivalPort') {
						constrainDepartures();
					}
				}
				//setTimeout('$(\''+container+'\').highlight(\'#CC6\')', 1000);
			}
		}
	}).get(args);
}

function checkCountriesMatchPorts() {
	ccwJsDebugInstance.outputMessage('checkCountriesMatchPorts', DO_MAP_DEBUG);
	checkCountryMatches($('leavingPort'), $('leavingCountry'));
	checkCountryMatches($('arrivalPort'), $('arrivalCountry'));
}

function checkCountryMatches(portField, countryField) {
	ccwJsDebugInstance.outputMessage('checkCountryMatches', DO_MAP_DEBUG);
	if (portField.value > 0) {
		new Request.JSON ({
			url: '/json/getPortCountry.php',
			onComplete: function(output) {
				
				var country = output.country.id;
				if (countryField.value != country) {
					for (var i = 0; i < countryField.options.length; i++) {
						if (countryField.options[i].value == country) {
							countryField.selectedIndex = i;
							break;
						}
					}
				}
				removeSelectOption(countryField);
			}
		}).get({'port':portField.value});
	}
}

function constrainDestinations() {
	ccwJsDebugInstance.outputMessage('constrainDestinations', DO_MAP_DEBUG);
	//debugger;
	if (portConstraint == PORT_CONSTRAINT_UNKNOWN) {
		portConstraint = PORT_CONSTRAINT_DEPARTURE;
	}
	if (portConstraint == PORT_CONSTRAINT_DEPARTURE) {
		constrainPorts_impl($('arrivalPort'), $('arrivalCountry'), $('leavingPort'));
	}
	if ($('arrivalPortSection').style.display == 'none') {
		//setTimeout('$(\'arrivalPortSection\').highlight(\'#CC6\')', 1500);
	}
	easeInElement('arrivalPortSection');
}

function constrainDepartures() {
	ccwJsDebugInstance.outputMessage('constrainDepartures', DO_MAP_DEBUG);
	//debugger;
	if (portConstraint == PORT_CONSTRAINT_UNKNOWN) {
		portConstraint = PORT_CONSTRAINT_DESTINATION;
	}
	if (portConstraint == PORT_CONSTRAINT_DESTINATION) {
		constrainPorts_impl($('leavingPort'), $('leavingCountry'), $('arrivalPort'));
	}
	if ($('leavingPortSection').style.display == 'none') {
		//setTimeout('$(\'leavingPortSection\').highlight(\'#CC6\')', 1000);
	}
	easeInElement('leavingPortSection');
}

function constrainPorts_impl(slavePortSelect, slaveCountrySelect, masterPortSelect) {
	ccwJsDebugInstance.outputMessage('constrainPorts_impl', DO_MAP_DEBUG);
	var selectedSlaveCountry = slaveCountrySelect.value;
	var selectedSlavePort = slavePortSelect.value;
	var args = {'port':masterPortSelect.value};
	if (masterPortSelect.id == 'arrivalPort') {
		args['reverse'] = '1';
	}
	new Request.JSON ({
		url: '/json/getPortDestinations.php',
		onComplete: function(output) {
			//debugger;
			slavePortSelect.options.length = 0;
			slaveCountrySelect.options.length = 0;
			if (output.ports.length > 0) {
				var selectedIndex = 0;
				if (output.ports.length > 1) {
					for(var i = 0; i < output.ports.length; i++) {
						if (selectedSlavePort == output.ports[i].id) {
   							selectedIndex = i;
							break;
						}
					}
					if (selectedIndex == 0) slavePortSelect.options.add(new Option('Select', 0));
				}
				for(var i = 0; i < output.ports.length; i++) {
   					slavePortSelect.options.add(new Option(output.ports[i].name, output.ports[i].id));
   				}
   				if (selectedIndex>0) {
   					slavePortSelect.options[selectedIndex].selected = true;
   				}
			}
			if (output.countries.length > 0) {
				var selectedIndex = 0;
				if (output.countries.length > 1) {
					for(var i = 0; i < output.countries.length; i++) {
						if (selectedSlaveCountry == output.countries[i].id) {
   							selectedIndex = i;
							break;
						}
					}
					if (selectedIndex == 0) slaveCountrySelect.options.add(new Option('Select', 0));
				}
				for(var i = 0; i < output.countries.length; i++) {
   					slaveCountrySelect.options.add(new Option(output.countries[i].name, output.countries[i].id));
   					if (selectedSlaveCountry == output.countries[i].id) {
   					}
   				}
   				if (selectedIndex>0) {
   					slaveCountrySelect.options[selectedIndex].selected = true;
   				}
			}
			updateFormSubmit();
		}
	}).get(args);
}

function updateFormSubmit() {
	ccwJsDebugInstance.outputMessage('updateFormSubmit', DO_MAP_DEBUG);
	var port_leaving = $('leavingPort');
	var port_arriving = $('arrivalPort');
	var port1 = 0;
	var port2 = 0;
	try {
    	port1 = port_leaving.options[port_leaving.selectedIndex].value;
    	port2 = port_arriving.options[port_arriving.selectedIndex].value;
	} catch (e) {}
	var selected1 = port1 != 0;
	var selected2 = port2 != 0;
	
	if (selected1 && selected2 && port1 != port2) {
		easeInElement('submitForm', {minHeight:34,marginTop:14});
	} else {
		hideElement('submitForm');
	}
}

window.addEvent('domready', function() {
	//debugger;
	ccwJsDebugInstance.outputMessage('domready', DO_MAP_DEBUG);
	if ($('leavingPort').value == 0) {
		hideElement('leavingPortSection');
	}
	if ($('arrivalPort').value == 0) {
		hideElement('arrivalPortSection');
	}
	//hideElement('returnDateSection');
	if ($('leavingCountry').value == 0 && $('leavingPort').value == 0 && $('arrivalCountry').value == 0 && $('arrivalPort').value == 0) {
		hideElement('submitForm');
	}
	//save initial values
	['leavingCountry', 'leavingPort', 'arrivalCountry', 'arrivalPort'].each(
		function(item, index) {
			var options = new Array();
			var element = $(item);
			for (var i = 0; i < element.options.length; i++) {				
				options[i] = new Option(element.options[i].text, element.options[i].value);
			}
			initValues[item] = options;
		}
	);
	
//	var returnField = $('return');
//	if (returnField) {
//		returnField.addEvent('click', function(evt) {
//			evt.stopPropagation();
//			if (evt.target.checked) {
//				easeInElement('returnDateSection');
//			} else {
//				hideElement('returnDateSection');
//			}
//		});
//	}
	var countrySelects = $$('.countrySelect');
	var portSelects = $$('.portSelect');
	
	countrySelects.addEvents({
		'change': function(evt) {
			var country = evt.target.options[evt.target.selectedIndex].value;
			if (country != 0) {
				if (evt.target.id == 'leavingCountry') {
					if (country == -1) easeInElement('leavingPortSection');
					else updatePortList(country, 'leavingPort', 'leavingPortSection', 0);
				} else if (evt.target.id == 'arrivalCountry') {
					if (country == -1) easeInElement('arrivalPortSection');
					else updatePortList(country, 'arrivalPort', 'arrivalPortSection', 0);
				}
				removeSelectOption(evt.target);
				if (evt.target.id == 'leavingCountry') {
					sendDepartureCountryToFlash(country);
				} else if (evt.target.id == 'arrivalCountry') {
					sendDestinationCountryToFlash(country);
				}
			}
		}
	});
	
	portSelects.addEvents({
		'change': function(evt) {
			var port = evt.target.options[evt.target.selectedIndex].value;
			if (evt.target.id == 'leavingPort') {
				sendDeparturePortToFlash(port);
				constrainDestinations();
			} else if (evt.target.id == 'arrivalPort') {
				sendDestinationPortToFlash(port);
				constrainDepartures();
			}
			removeSelectOption(evt.target);
			checkCountriesMatchPorts();
			updateFormSubmit();
		}
	});
	var operators = $('operators');
	if (operators) {
		operators.addEvent('change', function(evt) {
			var target = evt.target;
			sendOperatorToFlash(target.value);
		});
	}
	$$('img.calendarTrigger').addEvents({
		'click' : function(evt) {
			evt.stopPropagation();
			var id = evt.target.id;
			var idLength = id.length;
			var target = id.substring(0, idLength-3);
			$(target).focus();
		}
	});
	
	$$('input.text-date').addEvents({
		'focus': function(evt) {
			this.select();
			lcs(this);
		},
		'click': function(evt) {
			evt.stopPropagation();
			this.select();
			lcs(this);
		}
	});
	var resetButton = $('resetButton');
	if (resetButton) {
		resetButton.addEvent('click', resetForm);
	}
	
});


var PORT_CONSTRAINT_NONE = 0;
var PORT_CONSTRAINT_UNKNOWN = 1;
var PORT_CONSTRAINT_DEPARTURE = 2;
var PORT_CONSTRAINT_DESTINATION = 3;
var portConstraint = PORT_CONSTRAINT_UNKNOWN;
var initValues = new Object();
var DO_MAP_DEBUG = false;