Search = {
    types: ["oneway", "return", "multi", "multicity"],

    process: function(criteria) {
    	var form = $$("form[name = '" + criteria.type + "Travel']")[0];

    	if(criteria.type == "oneway") {
    		$("city1FromOnewayCode").value = criteria.segments[0].origin;
    		$("city1ToOnewayCode").value = criteria.segments[0].destination;
    		$("l1OnewayDate").value = criteria.segments[0].departure;
    	}
    	else if(criteria.type == "return") {
    		$("city1FromReturnCode").value = criteria.segments[0].origin;
    		$("city1ToReturnCode").value = criteria.segments[0].destination;
    		$("l1ReturnDate").value = criteria.segments[0].departure;
    		$("r1ReturnDate").value = criteria.segments[1].departure;
    	}
    	else if(criteria.type == "multicity") {
    		// Overcome the case when the user used the "multi-city" view to search for a round-trip solution.
    		criteria.segments.each(function(segment, index) {
    			$("city" + (index + 1) + "FromMulticityCode").value = segment.origin;
        		$("city" + (index + 1) + "ToMulticityCode").value = segment.destination;
        		$("l" + (index + 1) + "MulticityDate").value = segment.departure;
    		});
    	}
    	else if(criteria.type == "multi") {
    		for(var index = 0; index < 5; index++) {
	    		$("city" + (index + 1) + "FromMultiCode").value = criteria.segments[index].origin;
	    		$("city" + (index + 1) + "ToMultiCode").value = criteria.segments[index].destination;
	    		$("l" + (index + 1) + "MultiDate").value = criteria.segments[index].departure;
    		}
    	}

    	form.submit();
    },

    /** @function ? Switch the search view according to the given search type. */
    switchView: function(type) {


		// Storing current layer name
		setCurrentTripTab(type);
	    
		// Hide errors header if switch tab
		hideShowErrorsHeader()	    
	
        // Previous search type (view). 
        var previous = $("currentTripTab").value;

        // Update the hidden field "currentTripTab".
        $("currentTripTab").value = type;

        // Activate the specified tab.
        Search.types.each(function(type) {
            $(type).hide();
            $("searchTypeTab_" + type).removeClassName("activated");
        });
        $(type).show();
        $("searchTypeTab_" + type).addClassName("activated");

        // (legacy) ???
        if(type == "return") {
            recoverSearch();
        }

        // Search criteria that are shared between the different views.
        // Values in it answer the question «Where do we get the values to share?», as field identifiers.
        var mapping = {
            "return": {
                airports: [{value: "city1FromReturnCode", label: "city1FromReturn"},
                           {value: "city1ToReturnCode", label: "city1ToReturn"}],
                dates: [{value: "l1ReturnDate", label: "l1Return"},
                        {value: "r1ReturnDate", label: "r1Return"}],
                passengers: {adults: "ReturnAdultsNb", children: "ReturnChildrenNb"},
                cabin: "ReturnCabin"
            },
            "oneway": {
                airports: [{value: "city1FromOnewayCode", label: "city1FromOneway"},
                           {value: "city1ToOnewayCode", label: "city1ToOneway"}],
                dates: [{value: "l1OnewayDate", label: "l1Oneway"}],
                passengers: {adults: "OnewayAdultsNb", children: "OnewayChildrenNb"},
                cabin: "OnewayCabin"
            },
            "multicity": {
                airports: [{value: "city1FromMulticityCode", label: "city1FromMulticity"},
                           {value: "city1ToMulticityCode", label: "city1ToMulticity"}],
                dates: [{value: "l1MulticityDate", label: "l1Multicity"},
                        {value: "l2MulticityDate", label: "l2Multicity"},
                        {value: "l3MulticityDate", label: "l3Multicity"}],
                passengers: {adults: "MulticityAdultsNb", children: "MulticityChildrenNb"},
                cabin: "MulticityCabin"
            },
            "multi": {
                airports: [{value: "city1FromMultiCode", label: "city1FromMulti"}],
                dates: [{value: "l1MultiDate", label: "l1Multi"},
                        {value: "r1MultiDate", label: "r1Multi"}],
                passengers: {adults: "MultiAdultsNb", children: "MultiChildrenNb"},
                cabin: "MultiCabin"
            }
        }

        // Retrieve the shared criteria from the previous view.
        mapping[type].airports.each(function(airport, index) {
            if(mapping[previous].airports[index]) {
                $(airport["value"]).value = $F(mapping[previous].airports[index]["value"]);
                $(airport["label"]).value = $F(mapping[previous].airports[index]["label"]);
            }
        });

        mapping[type].dates.each(function(date, index) {
            if(mapping[previous].dates[index]) {
                $(date["value"]).value = $F(mapping[previous].dates[index]["value"]);
                $(date["label"]).value = $F(mapping[previous].dates[index]["label"]);
            }
        });

        $(mapping[type].passengers["adults"]).value = $F(mapping[previous].passengers["adults"]);
        $(mapping[type].passengers["children"]).value = $F(mapping[previous].passengers["children"]);
        $(mapping[type].cabin).value = $F(mapping[previous].cabin);
        
        if ($("city1From" + type.capitalize()).isVisible())
        	$("city1From" + type.capitalize()).focus();
    },

    // Fill the destination fields with the desired suggestions.
    useSuggestedDestinations: function(type) {
        $('suggestedDestinationsDialog').show();
        Search.type = type;
    },

    // Update the fields if the user wants to proceed
    updateCompareFields: function() {
    	var suggestions = this.suggestedDestinations;         
        if (suggestions != null) {
	        suggestions.Destination.findAll(function(destination) {
	            return destination.type == Search.type;
	        }).each(function(destination, index) {
	            var id = "city" + (index + 1) + "ToMulti";
	            var field = $(id);
	            if(!field) { throw $break; }
	            field.value = destination["#TEXT"];
	            $(id + "Code").value = destination.code;
	        });;
        }
    },

    // Clears the destinations in the "Compare destinations" view.
    clearDestinations: function() {
        $R(1, 5).each(function(index) {
            $("city" + index + "ToMulti").clear();
        });
    },

    // Call-back function called when the user clicks on "Add/Remove Flight #3".
    toggleSegment3Block: function() {
        var block = $("block3");
       	block.toggle();
       	$('block3-link').toggle();


        // Reset the block fields when it hides.
        if(!block.visible()) {
            // Switch the label.
            block.select("input, select, textarea").each(function(field) {
                if((field.type == "checkbox") || (field.type == "radio")) {
                    field.checked = false;
                }
                else if((field.type == "hidden") || (field.type == "password")
                        || (field.type == "text") || (field.type == "textarea")) {
                    field.value = "";
                }
                else if((field.type == "select") || (field.type == "select-one")
                        || (field.type == "select-multiple")) {
                    field.selectedIndex = 0;
                }
            });
        }
        else {
			console.warn(":toDo: localization");
        }
    }
};



/** @class ? Agent that retrieves some destinations to suggest to the user according to the airport he's just chosen.
 * Acts as a listener to AirportCompleter objects.
 */
AirportCompleter.DestinationSuggestor = Class.create({
    initialize: function() {
    },

    notifyEntrySelected: function(code) {
        new Ajax.Request("/adr/getSuggestedDestinations.do", {
            parameters: {origin: code},

            onSuccess: function(response) {
                var suggestions = response.responseJSON;
                Search.suggestedDestinations = suggestions;
                if(suggestions != null && suggestions.Destination) {
                	// Display the right divs corresponding to the choice we have
                	if(suggestions.Destination.find(function(destination) {
	            		return destination.type == "Sun";
	        		})){
                		$("theme1").show();
                	} else {
                		$("theme1").hide();
                	}
                	
                	if(suggestions.Destination.find(function(destination) {
	            		return destination.type == "Shopping";
	        		})){
                		$("theme2").show();
                	} else {
                		$("theme2").hide();
                	}

                	if(suggestions.Destination.find(function(destination) {
	            		return destination.type == "Touring";
	        		})){
                		$("theme3").show();
                	} else {
                		$("theme3").hide();
                	}
                    $("suggestedDestinations").show();
                }
                else {
                    $("suggestedDestinations").hide();
                }
            },

            onException: function(response, exception) {
                throw exception;
            }
        });
    }
});


function updateFormMessage(baseFieldName) {
	
	//var fieldName = 'l' + blockNo + tripType + "Date";
	var fieldName = baseFieldName + "Date";
	var blockNo = baseFieldName.substring(1,2);
	//console.info("LeChamp: " + fieldName + "blockNo: " + blockNo);
    var dateValuel = $(fieldName).value;
    var travelDatel = Date.parse(dateValuel);
	
	//var field = $('r' + blockNo + tripType + "Date");
    var field = $('r' + baseFieldName + "Date");
    var travelDater = null;
    if (field) {
        var dateValuer = field.value;
        travelDater = Date.parse(dateValuer);
    }

    var today = Date.today();

    var diffl = 0;
    if(travelDatel != null) {
        diffl = travelDatel.getTime() - today.getTime();
        diffl = diffl / 1000 / 60 / 60 / 24;
    }

    var diffr = 0;
    if (travelDater != null) {
        diffr =  travelDater.getTime() - today.getTime();
        diffr = diffr / 1000 / 60 / 60 / 24;
    }

    if ( (diffl > 331 && diffl < 356) || (diffr > 331 && diffr < 356)) {
        $("searchFormMessage2"+baseFieldName.substring(1)).style.display = 'block';
        $("searchFormMessage1"+baseFieldName.substring(1)).style.display = 'none';
    } else {
        $("searchFormMessage2"+baseFieldName.substring(1)).style.display = 'none';
        if (blockNo == '1') {
            $("searchFormMessage1"+baseFieldName.substring(1)).style.display = 'block';
        }
    }
}

function addOption(selectbox,text,value, selected )	{
	var optn = document.createElement("OPTION");
	optn.text = text;
	optn.value = value;
	if (selected) {
		optn.selected = "selected";
	}
	selectbox.options.add(optn);
}


// this function automatically adjusts the number of available children seats
// in the search form to allow the user valid search parameters
// in case the number of children have already been chosen by the user,
// it is keeped unless it breaks the maximum of passengers allowed
function updateMaxPassengers(travelType) {
	
	Search.types.each(function(type) {
		type = type.capitalize();	    
	    var formName        = travelType.toLowerCase() + 'Travel';
	    
	    var adultsFieldName   = travelType + 'AdultsNb';
	    var childrenFieldName = travelType + 'ChildrenNb';
	    	    
	    var totField        = type + 'TotalPassengerNb';
	    var nbAdults        = 1;
	    var nbChildren      = 0;
	    var total           = 0;
	    var max             = 8;
	    
	    var f               = document.forms[formName];

		//position selected for Adults and Children
		var listA = f.elements[adultsFieldName];
		var selectedA = listA.selectedIndex;
		
		var listC = f.elements[childrenFieldName];
		var selectedC = listC.selectedIndex;
		
	    nbAdults = parseInt(listA.options[selectedA].value,10);
	    nbChildren = parseInt(listC.options[selectedC].value,10);
	    total = nbAdults + nbChildren;
	    
	    var currentMaxNbA = parseInt(listA.options[listA.length-1].value,10);
	    var currentMaxNbC = parseInt(listC.options[listC.length-1].value,10)
	    
	    var newMaxNbA = max - nbChildren;
	    var newMaxNbC = max - nbAdults;

	    if (currentMaxNbA < newMaxNbA) {
	    	for(var i = currentMaxNbA+1; i <= newMaxNbA; i++) {
	    		addOption(listA, i, i, false);
	    	}
	    } else if (currentMaxNbA > newMaxNbA) {
	    	for(var i = currentMaxNbA; i > newMaxNbA; i--) {
	    		listA.remove(i-1);
	    	}
	    }

	    if (currentMaxNbC < newMaxNbC) {
	    	for(var i = currentMaxNbC+1; i <= newMaxNbC; i++) {
	    		addOption(listC, i, i, false);
	    	}
	    } else if (currentMaxNbC > newMaxNbC) {
	    	for(var i = currentMaxNbC; i > newMaxNbC; i--) {
	    		listC.remove(i);
	    	}
	    }
    	$(totField).value = total;	
    });
}



// Actions to be performed when the page is loaded.
Event.observe(window, "load", function(event) {
    // One-way
    ["city1FromOneway", "city1ToOneway"].each(function(field) {
        var completer = new AirportCompleter(field, field + "AutoComplete");
    });

    // Round-trip
    $R(1, 4).each(function(index) {
        var field = "city" + index + "FromReturn";
        if($(field)) { new AirportCompleter(field, field + "AutoComplete"); }
        field = "city" + index + "ToReturn";
        if($(field)) { new AirportCompleter(field, field + "AutoComplete"); }
    });

    // Multiple cities
    $R(1, 3).each(function(index) {
        var field = "city" + index + "FromMulticity";
        if($(field)) { new AirportCompleter(field, field + "AutoComplete"); }
        field = "city" + index + "ToMulticity";
        if($(field)) { new AirportCompleter(field, field + "AutoComplete"); }
    });

    // Multiple destinations
    $R(1, 10).each(function(index) {
        var field = "city" + index + "FromMulti";
        if($(field)) {
            var completer = new AirportCompleter(field, field + "AutoComplete");
            // Listener to control the visibility of the suggested destinations box.
            completer.addListener(new AirportCompleter.DestinationSuggestor());
        }
        field = "city" + index + "ToMulti";
        if($(field)) { new AirportCompleter(field, field + "AutoComplete"); }
    });

    $$("#mainBlock form").each(function(form) {
        Form.setAutoSelection(form);
    });
});

function moveFocus(id){
	var nf;
	var el = $(id);
	var toFocus = $(getNextFocus(el.name));
	
	if (toFocus != undefined) {
		if (toFocus.type == 'select-one' || (el.value != '' && (toFocus.value == '' || toFocus.value == 'yyyymmdd' || toFocus.value == 'aaaammjj' || toFocus.value == 'mmddyyyy' || toFocus.value == 'jjmmaaaa' ))) {
			toFocus.focus();
		}
	}
}
function getNextFocus(id){
	// Return
	if (id=='city1FromReturn') return 'city1ToReturn';
	if (id=='city1ToReturn') return 'l1Return';	
	if (id=='l1Return') return 'r1Return';
	if (id=='r1Return') return 'ReturnCabin';
	
	// Oneway
	if (id=='city1FromOneway') return 'city1ToOneway';
	if (id=='city1ToOneway') return 'l1Oneway';	
	if (id=='l1Oneway') return 'OnewayCabin';
	
	// Multicity
	if (id=='city1FromMulticity') return 'city1ToMulticity';
	if (id=='city1ToMulticity') return 'l1Multicity';	
	if (id=='l1Multicity') return 'city2FromMulticity';
	if (id=='city2FromMulticity') return 'city2ToMulticity';
	if (id=='city2ToMulticity') return 'l2Multicity';	
	if (id=='l2Multicity') return 'city3FromMulticity';	
	if (id=='city3FromMulticity') return 'city3ToMulticity';
	if (id=='city3ToMulticity') return 'l3Multicity';			
	if (id=='l3Multicity') return 'MulticityCabin';
	
	// Multi
	if (id=='city1FromMulti') return 'city1ToMulti';
	if (id=='city1ToMulti') return 'city2ToMulti';	
	if (id=='city2ToMulti') return 'city3ToMulti';
	if (id=='city3ToMulti') return 'city4ToMulti';
	if (id=='city4ToMulti') return 'city5ToMulti';			
	if (id=='city5ToMulti') return 'city6ToMulti';			
	if (id=='city6ToMulti') return 'city7ToMulti';	
	if (id=='city7ToMulti') return 'city8ToMulti';
	if (id=='city8ToMulti') return 'city9ToMulti';
	if (id=='city9ToMulti') return 'city10ToMulti';			
	if (id=='l1Multi') return 'r1Multi';
	if (id=='r1Multi') return 'MulticityCabin';

	if(id.match(/^(return|oneway|multicity|multi)SubmitButton$/)) {
		return $("searchTypeTab_return").down("a");
	}

	return '';
}
