var departSearchParam='&searchableOnly=false&locationType=airport'; //xLocaton Search paramaters used by the depart box. Should be set to whatever is apropriate for the search type  
var destinationSearchParam='&searchableOnly=false&locationType=airport'; //xLocaton Search paramaters used by the destination box. Should be set to whatever is apropriate for the search type  


/**
 * This function is called after the page is fully loaded
 */
OJ(function() 
{
    
	// Assign events
	assignEvents();

	// Open up the default search panel
	refreshSearchType();
    
    document.getElementById('searchPanel-form').style.display = 'block';
	// Preset all rooms to 1	
	changeNumberRooms(null, document.getElementById("numRooms").value);

	// If children have been selected in a previous search
	// when the form is prepopulated the age inputs must be
	// added.	
	setupChildAges();	
	calcNumDays(document.getElementById('departDateCO'), document.getElementById('returnDateCO'), document.getElementById('numNights'));	
});

/**
 * Assign the events to the HTML elements
 */
function assignEvents()
{
	// When the number of rooms are changed the passenger inputs need to too
	// Note: numRooms can exist in multiple forms
	/*OJ("select[@name='numRooms']").change(function() {
		changeNumberRooms(this, this.selectedIndex +1);
	});*/
	// Specific treatment of hotel form for number rooms change
	OJ("select[@name='Search/HotelInformation/numRooms']").change(function() {
		changeNumberRooms(this, this.selectedIndex +1);
	});
	// Search Type Options need to change the visible form
	OJ("#searchPanel-selector input[@name='Search/searchType']").click(function() {
		changeSearchType(this.value)
	});
	
	// Submit buttons need the event to submit their form		
	OJ(".searchPanel-searchButtonClass a").click(function() {
		OJ(this).parents("form").submit();
	});

	// Add event on child passenger blocks, to show age inputs
	OJ(".searchPanel-hotel-rooms").each(function() {

		childSelects = OJ(".childSelector");
		
		childSelects.change(function() {
			addChildAges(this);
		});
	
	});
	OJ("#searchPanel-flight-passengers .searchPanel-flight-pax:eq(1) select").change(function() {
		addFlightChildAges(this);
	});
	var inputFocusBuffer;
	OJ(".selectInput").focus(function() {
		inputFocusBuffer=this.value;
		this.select();
	});
	

}

/**
 * This function sets again the same "searchType" so it hiddes or
 * displies properly the fields in case they weren't already there
 * because of partially loaded page functionality.
 */
function refreshSearchType()
{

	chosenOpt = OJ("#searchPanel-selector input[@name='Search/searchType'][@checked]");
	changeSearchType(chosenOpt[0].value);
}

/**
*Sets the click event of the given search type just as if the user clicked it*
*/
function setUiOption(searchType){
	OJ("#searchPanel-selector input[@value='" + searchType + "']").click();

}


function changeSearchType(searchType)
{
  var commonForm = OJ('#plan_trip_common');
   
  commonForm.find('#searchType')[0].value=searchType;
  commonForm.find('#searchTypevalidator')[0].value=searchType;
  hideAllSearchOptions(commonForm);
  
  var vehicleForm = OJ('#plan_trip_vehicle');
  vehicleForm.find('#searchType')[0].value=searchType;
  vehicleForm.find('#searchTypevalidator')[0].value=searchType;
  
  showAllRandomDividers();

  if(searchType == 'V')
  {

    document.getElementById('searchPanel-car-selector').style.display = 'block';
  	document.getElementById('searchPanel-common-selector').style.display = 'none';
    
  	destinationSearchParam = carDestinationSearch;	
    toggleMoreOptions();
    toggleCarSelectDropOff();
  }else
  {
    document.getElementById('searchPanel-car-selector').style.display = 'none';
  	document.getElementById('searchPanel-common-selector').style.display = 'block';
  }
  
  if(searchType == 'F')
  {
    
    commonForm.find('#datesAndPAX').css('display', 'block');	
  	commonForm.find('#depart-selector').css('display', 'block');    
	commonForm.find('#searchPanel-flight-passengers').css('display', 'block');
  	commonForm.find('#displayChildAge')[0].innerHTML='(' + (airMaxInfantAge) + '-'+(airMaxChildAge - 1)+')';  	
    commonForm.find('#infant-label').css('display', 'block');
    commonForm.find('#roomDisplayInfantAge').css('display', 'block');
    commonForm.find('#infantPassengers').css('display', 'block');
    commonForm.find('#flightTypes').css('display', 'block');
	commonForm.find('#destinationLabel').css('display', 'block');
	departSearchParam = flightDepartSearch;
	destinationSearchParam = flightDestinationSearch;
	commonForm.find('#flightTimes').css('display', 'block');
	document.getElementById('divider_line_2').style.display = 'none';	
	document.getElementById('divider_line_3').style.display = 'none';
	chosenOpt = OJ("#searchPanel-common-selector input[@name='Search/flightType'][@checked]");
        //Display Calendar Checkbox only if Flight Only and Return Flights
        if(document.getElementById('flightType-Return').value = 'return')
           document.getElementById('calendarSearch-block').style.display = 'block';
        else
            document.getElementById('calendarSearch-block').style.display = 'none';  
    toggleMoreOptions();
    
    // If it's multicity, there are no radio buttons for oneway or return. Skip toggleOneWayFlights
    if (chosenOpt[0]) {
        toggleOneWayFlights(chosenOpt[0].value);
    }
}
  
  if(searchType == 'A')
  {

	commonForm.find('#depart-selector').css('display', 'block');    
	commonForm.find('#searchPanel-flight-passengers').css('display', 'block');
  	commonForm.find('#displayChildAge')[0].innerHTML='(' + (hotelMaxInfantAge + 1) + '-'+hotelMaxChildAge+')';  	
    commonForm.find('#infant-label').css('display', 'block');
    commonForm.find('#roomDisplayInfantAge').css('display', 'block');
    commonForm.find('#infantPassengers').css('display', 'block');
	commonForm.find('#flightTypes').css('display', 'block');
	commonForm.find('#returnFlexibility').css('display', 'block');
	commonForm.find('#destinationLabel').css('display', 'block');
	departSearchParam = flightDepartSearch;
	destinationSearchParam = flightDestinationSearch;
	commonForm.find('#flightTimes').css('display', 'block');
	commonForm.find('#flightFlexibility').css('display', 'block');
	document.getElementById('divider_line_2').style.display = 'none';	
	document.getElementById('divider_line_3').style.display = 'none';

	chosenOpt = OJ("#searchPanel-common-selector input[@name='Search/flightType'][@checked]");
	toggleOneWayFlights(chosenOpt[0].value);
	
    toggleMoreOptions();
  }
  
  
  if(searchType == 'H')
  {   	

  	// commonForm.find('#searchPanel-hotel-additional-options').css('display', 'block');
  	commonForm.find('#searchPanel-rooms').css('display', 'block');
  	commonForm.find('#searchPanel-rooms-required').css('display', 'block');  	
	commonForm.find('#hotelOnlyDestination').css('display', 'block');
  	commonForm.find('#roomDisplayAdultAge')[0].innerHTML='(' + (hotelMaxChildAge + 1) + '+)';  	
  	commonForm.find('#roomDisplayChildAge')[0].innerHTML='(0-' + hotelMaxChildAge + ')';  	
  	commonForm.find('#return-date-selector').css('display', 'block');
	commonForm.find('#num-nights-block').css('display', 'block');
	document.getElementById('divider_line_5').style.display = 'none';	
	destinationSearchParam = hotelDestinationSearch;
    toggleMoreOptions();
  }
  
  if(searchType == 'HF')
  {  	
  	
  	commonForm.find('#depart-selector').css('display', 'block');    	
	commonForm.find('#numNights-block').css('display', 'block');    
	commonForm.find('#searchPanel-rooms').css('display', 'block');
	commonForm.find('#searchPanel-rooms-required').css('display', 'block');
	commonForm.find('#destinationLabel').css('display', 'block');
	commonForm.find('#roomDisplayAdultAge')[0].innerHTML='(' + (hotelMaxChildAge + 1) + '+)';  	
  	commonForm.find('#roomDisplayChildAge')[0].innerHTML='(0-' + hotelMaxChildAge + ')';  	
   	commonForm.find('#return-date-selector').css('display', 'block');
	commonForm.find('#num-nights-block').css('display', 'block');
	document.getElementById('divider_line_5').style.display = 'none';	
	departSearchParam = packageDepartSearch;
	destinationSearchParam = HFDestinationSearch;
    toggleMoreOptions();
  }
  
  if(searchType == 'HFV')
  {  	
  	commonForm.find('#depart-selector').css('display', 'block');    	
	commonForm.find('#numNights-block').css('display', 'block');    
	commonForm.find('#searchPanel-rooms').css('display', 'block');
	commonForm.find('#destinationLabel').css('display', 'block');
	commonForm.find('#searchPanel-rooms-required').css('display', 'block');
	commonForm.find('#cabinBlock').css('display', 'block');
   	commonForm.find('#directFlight-block').css('display', 'block');
    commonForm.find('#searchPanel-hotel-additional-options').css('display', 'block');
    commonForm.find('#return-date-selector').css('display', 'block');
    commonForm.find('#airlinePrefBlock').css('display', 'block');
	commonForm.find('#num-nights-block').css('display', 'block');
	document.getElementById('divider_line_5').style.display = 'none';	
	departSearchParam = packageDepartSearch;
	destinationSearchParam = HFVDestinationSearch;
    toggleMoreOptions();
  }

  if(searchType == 'VF')
  {  	

  	commonForm.find('#depart-selector').css('display', 'block');    
	commonForm.find('#searchPanel-flight-passengers').css('display', 'block');
	commonForm.find('#destinationLabel').css('display', 'block');
  	commonForm.find('#displayChildAge')[0].innerHTML='(0-' + hotelMaxChildAge + ')'; 
    commonForm.find('#infant-label').css('display', 'none');
    commonForm.find('#roomDisplayInfantAge').css('display', 'none');
    commonForm.find('#infantPassengers').css('display', 'none');
	commonForm.find('#cabinBlock').css('display', 'block');
   	commonForm.find('#directFlight-block').css('display', 'block');
   	commonForm.find('#return-date-selector').css('display', 'block');
   	commonForm.find('#airlinePrefBlock').css('display', 'block');	
	document.getElementById('divider_line_2').style.display = 'none';	
	document.getElementById('divider_line_3').style.display = 'none';	
	departSearchParam = packageDepartSearch;
	destinationSearchParam = VFDestinationSearch;	
    toggleMoreOptions();
}
     
}

function hideAllSearchOptions(commonForm){

    document.getElementById('searchPanel-car-selector').style.display = 'none';
  	document.getElementById('searchPanel-common-selector').style.display = 'none';
    document.getElementById('calendarSearch-block').style.display = 'none';
	commonForm.find('#depart-selector').css('display', 'none');
	commonForm.find('#numNights-block').css('display', 'none');
	commonForm.find('#searchPanel-hotel-additional-options').css('display', 'none');
	commonForm.find('#searchPanel-flight-passengers').css('display', 'none');
	commonForm.find('#searchPanel-rooms').css('display', 'none');
	commonForm.find('#searchPanel-rooms-required').css('display', 'none');
	commonForm.find('#cabinBlock').css('display', 'none');
	commonForm.find('#directFlight-block').css('display', 'none');
	commonForm.find('#flightTypes').css('display', 'none');
	commonForm.find('#flightTimes').css('display', 'none');	
	commonForm.find('#airlinePrefBlock').css('display', 'none');	
	commonForm.find('#flightFlexibility').css('display', 'none');
	commonForm.find('#destinationLabel').css('display', 'none');
	commonForm.find('#hotelOnlyDestination').css('display', 'none');
	commonForm.find('#num-nights-block').css('display', 'none');


}
function showAllRandomDividers(){

	//show all divider_line's
	document.getElementById('divider_line_1').style.display = 'block';
	document.getElementById('divider_line_2').style.display = 'block';
	document.getElementById('divider_line_3').style.display = 'block';
	document.getElementById('divider_line_5').style.display = 'block';
}

function toggleOneWayFlights(flightType){
    
    if(flightType == 'oneway'){
		document.getElementById('return-date-selector').style.display = 'none';	
		if (document.getElementById('return-time-selector')) 
            document.getElementById('return-time-selector').style.display = 'none';	
		document.getElementById('returnFlexibility').style.display = 'none';	
                document.getElementById('calendarSearch-block').style.display = 'none';
                updateCheckboxValue('calendarSearchCheck', false);
	}
	else {
        if(flightType == 'return'){
            document.getElementById('return-date-selector').style.display = 'block';
		    if (document.getElementById('return-time-selector')) 
                document.getElementById('return-time-selector').style.display = 'block';
            document.getElementById('returnFlexibility').style.display = 'block';
            document.getElementById('calendarSearch-block').style.display = 'block';            
        }
    }
}

function toggleMoreOptions(){
	searchType = OJ("#searchPanel-selector input[@name='Search/searchType'][@checked]")[0].value;
    if(!document.getElementById('Search/moreOptions').checked) {   
		document.getElementById('airlinePrefBlock').style.display = 'none';	
		document.getElementById('cabinBlock').style.display = 'none';	
		document.getElementById('directFlight-block').style.display = 'none';	
		document.getElementById('searchPanel-hotel-additional-options').style.display = 'none';	
        //  Test if optional values are there before clearing them
        updateInputValue('propertyType', '');
        updateInputValue('locationType', '');
        updateInputValue('hotelName', '');
		// gohop remove
        // updateInputValue('roomRating', '');      
        document.getElementById('Search/moreOptions').value = 'false';
	}
	else {
		flightSearch = searchType.indexOf("F") != -1 || searchType.indexOf("A") != -1;
		hotelSearch = searchType.indexOf("H") != -1;
		
        if ( flightSearch )
        {
			document.getElementById('airlinePrefBlock').style.display = 'block';	
			document.getElementById('cabinBlock').style.display = 'block';	
			document.getElementById('directFlight-block').style.display = 'block';	
		}
	
        if ( hotelSearch )
		{		
			document.getElementById('searchPanel-hotel-additional-options').style.display = 'block';	
	}



        document.getElementById('Search/moreOptions').value = 'true';
	}
}
//  Test if optional values are there before updating them
function updateInputValue(inputName, inputValue)
{
    input = document.getElementById(inputName);
    if(input != null)
        input.value = inputValue; 
}
//  Test if optional checkbox values are there before updating them
function updateCheckboxValue(inputName, inputValue)
{
    input = document.getElementById(inputName);
    if(input != null)
        input.checked = inputValue; 
}
function toggleCarSelectDropOff(){

    if(!document.getElementById('carSelectorDropOffDiff').checked && 
        (document.getElementById('Search/VehicleInformation/dropOffLocation').value == document.getElementById('Search/VehicleInformation/pickUpLocation').value ||
        document.getElementById('carSelectorDropOffSame').checked)) {
        document.getElementById('Search/VehicleInformation/dropOffLocation').value = document.getElementById('Search/VehicleInformation/pickUpLocation').value;
        document.getElementById('Search/VehicleInformation/dropOffLocation_input').value = document.getElementById('Search/VehicleInformation/pickUpLocation_input').value;
        document.getElementById('searchPanel-car-selector-dropOff-location').style.display = 'none';	
        document.getElementById('carSelectorDropOffDiffLocation').style.display = 'block';
        document.getElementById('carSelectorDropOffSameLocation').style.display = 'none';
        document.getElementById('carSelectorDropOffSame').checked = false;
	}
	else { 
        document.getElementById('searchPanel-car-selector-dropOff-location').style.display = 'block';	
        document.getElementById('carSelectorDropOffDiffLocation').style.display = 'none';
        document.getElementById('carSelectorDropOffSameLocation').style.display = 'block';
        document.getElementById('carSelectorDropOffDiff').checked = false;
    }
}

function setVisibleAdditionalOptions(visible)
{
	var display='none';
	if (visible)
	{
		display='block';
	}
	document.getElementById('searchPanel-car-selector-additionalOptions').style.display = display;
}

function changeNumberRooms(el, numRooms)
{
		// Get all passenger types
		rooms = OJ(".searchPanel-hotel-rooms");
		
		// If an element was selected only get the relative pax types
		if (el != null) {

			// Go up to higher parent, then across the the rooms container
			rooms = OJ(el).parents(".searchPanel-rooms-required").siblings(".searchPanel-hotel-rooms");

			// Each passenger type
			//rooms = roomPax.children(".searchPanel-hotel-room");
		}
		
		for (roomCategories = 0; roomCategories < rooms.length; roomCategories++) 
		{
			roomCategory = OJ(rooms[roomCategories]);
		
			// Each room input (per pax type)
			roomList = roomCategory.children(".searchPanel-hotel-room");
			
			for (j = 0; j < roomList.length; j++) 
			{
					room = OJ(roomList[j]);
					
					if (j < numRooms) {
						room.css('display', 'block');
						
					}
					else {				
						room.css('display', 'none');
					}
					
					
			}
		
		}
		setupChildAges();		
}

/**
 * Adds the default child age inputs for the current
 * number of children selected in the session
 */
function setupChildAges()
{
  // Air child passengers
  OJ("#childPassengers").each(function() {
  	addFlightChildAges(this);
  });
  
      OJ("#plan_trip_common").find("#searchPanel-rooms").find(".childSelector").each(function() {
		addChildAges(this);
	});
	
	
  
}

function addChildAges(inpt)
{
  cform = inpt.form;  
  
  numRooms = cform['Search/HotelInformation/numRooms'].value;
 
  var output='';
  var anyChildrenPresent=false;
  
  // For each room
  for(x=1; x <= maxRooms; x++)
  {	
    // Get the number of children (for this room)
    parents1 = OJ(inpt).parents(".searchPanel-hotel-rooms");
    numChildRoom =  OJ(parents1).find("#child-select-room" + x).children().get(0).value;
    var childrenPresentInRoom=false;
    if(numChildRoom > 0 && x <= numRooms){
    	childrenPresentInRoom=true;
    	anyChildrenPresent = true;
    } 
   	
    // For each child create an age input
    for( i = 1; i <= maxChildren; i ++)
    {    
     	
     	if(i <= numChildRoom){
     		OJ(parents1).find("#room" + x + "AgeFieldChild" + i).css('display', 'block');
     	}
     	else{
     		OJ(parents1).find("#room" + x + "AgeFieldChild" + i).css('display', 'none');
     	}
      	
     
    }
    //endDiv =  OJ(parents1).find("#child-ages-room" + x).get(0);
    //endDiv.innerHTML = output;
  	//endDiv.style.display = 'block';
  	var output='';
  	
  	if(childrenPresentInRoom){
  		 OJ(parents1).find("#child-ages-room" + x).css('display', 'block');
  	} else{
  		  OJ(parents1).find("#child-ages-room" + x).css('display', 'none');
  	}
  	
  	
  }
  if(anyChildrenPresent){  		 
  		 OJ(parents1).find("#hotelChildRoomsBlock").css('display', 'block');
  		 changeChildAge(); 
  	} else{
  		 OJ(parents1).find("#hotelChildRoomsBlock").css('display', 'none');
  		 OJ('#infantSeatSelection').css('display', 'none');
  	}
  
}

function addFlightChildAges(inpt)
{ 
  cform = inpt.form; 
    
 
  // Get the number of children 
  numChildren = parseInt(cform['childPassengers'].value);
  
  var childrenPresent=false;
  
   if(numChildren > 0 ){    	
    	childrenPresent = true;
    } 
		
	
    // For each child create an age input
    for( i = 1; i <= maxChildren; i ++)
    {
    	if(i <= numChildren){
     		 OJ("#plan_trip_common").find("#flightAgeFieldChild" + i).css('display', 'block');
     	}
     	else{
     		 OJ("#plan_trip_common").find("#flightAgeFieldChild" + i).css('display', 'none');     		
     	}
     
      
    }
 
  if(childrenPresent){
  	 OJ("#plan_trip_common").find(".flight-child-ages").css('display', 'block');
  	  changeFlightChildAge();   	
  }
  else {
  	 OJ("#plan_trip_common").find(".flight-child-ages").css('display', 'none');
  	  OJ('#infantSeatSelection').css('display', 'none');
  }
  
}

function changeChildAge(){
	var searchType = OJ('#plan_trip_common').find('#searchType')[0].value;
	
	var infantPresent = false;
	var infantCount = 0; //The number of infants selected in this search panel
	
	OJ(".roomAgeSelect").each(function() {
		age = parseInt(this.value);
		if(age > 0){
			if(searchType == 'H'){
				if(age <= hotelMaxInfantAge){
					infantCount++;
				}
			}		
			else{
				if(age <= packageMaxInfantAge){
					infantCount++;
				}
			}
		}
	
	});	
	
	if(infantCount > 0 ){
		//Uncomment this to restore infant seat selection
		//OJ('#infantSeatSelection').css('display', 'block');
	} else {
		OJ('#infantSeatSelection').css('display', 'none');
	}	
}

function changeFlightChildAge(){
	var searchType = OJ('#plan_trip_common').find('#searchType')[0].value;
	
	var infantPresent = false;
	var infantCount = 0; //The number of infants selected in this search panel
	
	OJ(".flightAgeSelect").each(function() {
		age = parseInt(this.value);
		if(age > 0 && age <= airMaxInfantAge){		
			infantCount++;			
		}
	
	});	
	
	if(infantCount > 0){
		//Uncomment this to restore infant seat selection
		//OJ('#infantSeatSelection').css('display', 'block');
	} else {
		OJ('#infantSeatSelection').css('display', 'none');
	}	
}


function setDropOffValues()
{
	document.getElementById('Search/VehicleInformation/dropOffLocation_input').value = document.getElementById('Search/VehicleInformation/pickUpLocation_input').value;
	document.getElementById('Search/VehicleInformation/dropOffLocation').value = document.getElementById('Search/VehicleInformation/pickUpLocation').value;
}

/*
*Called when the search panel appears as a javascript popup. Inserts the "Close Window" text
*/
function onPopUp(dialog){
	OJ('.modalClose')[0].innerHTML='Close Window';
	dialog.container.show();
	dialog.data.show();
	dialog.overlay.show();
}



/* gohop change */


/*
* when user change the search type, clear all location box.
*/
function clearLocations()
{
    var processFields=new Array("Search/OriginDestinationInformation/Destination/location",
								  "Search/OriginDestinationInformation/Origin/location",
								  "Search/VehicleInformation/pickUpLocation",
								  "Search/VehicleInformation/dropOffLocation");
    for( i = 0 ; i < processFields.length ; i ++ )
    { 
	    document.getElementById(processFields[i]).value = "" ;
		document.getElementById(processFields[i]+'_input').value = "" ;
		document.getElementById(processFields[i] + '_choices').innerHTML = "" ;
	}
}


/*
* If user doesn't click the ajax locaion list, pick the first one.
*/
function pickTheFirstLocation()
{
	var processFields=new Array("Search/OriginDestinationInformation/Destination/location",
								  "Search/OriginDestinationInformation/Origin/location",
								  "Search/VehicleInformation/pickUpLocation",
								  "Search/VehicleInformation/dropOffLocation");
	
	for( i = 0 ; i < processFields.length ; i ++ )
    { 
		var choices = document.getElementById(processFields[i] + '_choices') ;
	    var choosedLocation = document.getElementById(processFields[i]).value ;
		
    	var locaitonNotInTheList = false ;
    	if( choosedLocation == '' || choices.innerHTML.indexOf(choosedLocation) == -1 ) 
    	{
    		locaitonNotInTheList = true ;
    	}
	
    	var idString = getValueByAttribute(choices, "id" )  ;
    	var nameString = getValueByAttribute(choices, "" )  ;
	
	
    	if ( locaitonNotInTheList && document.getElementById(processFields[i]).value != idString && idString != '' && idString != null && nameString != '' && nameString != null)
    	{
    		document.getElementById(processFields[i]).value = idString ;
    		document.getElementById(processFields[i]+'_input').value = nameString ;
    	}
	}
	
	document.getElementById("plan_trip_common").method="POST";
	
	
}


function getValueByAttribute( choices, attr )
{
    if( attr == "" && choices.firstChild!=null && choices.firstChild.firstChild!=null){
	    return choices.firstChild.firstChild.innerHTML ;
	}
	if (choices.firstChild!=null && choices.firstChild.firstChild!=null) {
		return choices.firstChild.firstChild.getAttribute(attr) ;
	} else {
		return "";
	}
}

/* end of gohop change */

