	var initialOption = '<option value="-1">Till:</option>';
	var destSelected = false;
	
	function loadDestinations(des) {
		var resource = '/json/arrivalCities?id=' + $("#departure").val();
		$.ajaxSetup ({cache: false});
		$.getJSON(resource, {id: $("#departure").val(), ajax: 'true'}, function(j) {
			var options = initialOption;
			if(j.length > 0) options = '';
			for (var i = 0; i < j.length; i++) {
				optionAttr = '';
				if(des == j[i].optionValue) {optionAttr = 'selected="selected"';}
				options += '<option value="' + j[i].optionValue + '" ' + optionAttr + '>' + j[i].optionDisplay + '</option>';
			}
			$("#destination").html(options);
		})
	}
	
	function setHistory() {
		$.historyLoad(($("#departure").val() + ',' + $("#destination").val()).replace(/^.*#/, ''));
	}
	
	function loadOptions() {
		$("#destination").html(initialOption);
		
	    $("#departure").change(function() {
	    	destSelected = false;
	    	setHistory();
	        return false;
	    });
	    $("#destination").change(function() {
	    	destSelected = true;
	    	setHistory();
	        return false;
	    }); 
	}
	
	// This function is called when:
	// 1. after calling $.historyInit();
	// 2. after calling $.historyLoad();
	// 3. after pushing "Go Back" button of a browser

  function historyCallback(hash) {
    if(hash) {
      dep = hash.split(',')[0];
      des = hash.split(',')[1];
      if($("#departure").val() != dep) {
    	  $("#departure option").each(function() {
            if($(this).val() == dep) {$(this).attr("selected","selected")}
    	  });
      }
      // Chrome/Safari fix for calling callback method multiple times now and then
      if(destSelected == true && jQuery.browser.safari) {}
      else { loadDestinations(des); }
    }
  }
	
	$(document).ready(function() {
		loadOptions();
		$.historyInit(historyCallback);
	});