/**
 * @(#)$Id: searchPanel.js,v 1.15 2011/10/03 16:15:06 joseramon-cocha Exp $
 *
 * JavaScript object for search panel.
 *
 * (C)opyright OpenJaw Technologies Ltd. 2009
 */

 
/* These methods are called when the return or departure
    calendars are updated by the user. The two functions
    will ensure that the departure date is always before
    the return date (called by calendar's onChoose).*/

onChooseDepartureDate = function(calendar) {
    var departDate = calDepartDate.getDate();
    var returnDate = calReturnDate.getDate();
    if (departDate > returnDate) {
        //  CalenderReturnOffset configured in common/system/calendar.xml
        calReturnDate.setDate(addCalendarDays(departDate,searchPanel.CalenderReturnOffset));
    }
    setNumberOfNights();
}

onChooseReturnDate = function(calendar) {
    var departDate = calDepartDate.getDate();
    var returnDate = calReturnDate.getDate();
    if (departDate > returnDate) {
        calDepartDate.setDate(returnDate);
    }
    setNumberOfNights();
}

setNumberOfNights = function() {
    var departDate = calDepartDate.getDate();
    var returnDate = calReturnDate.getDate();
                          
    // 1 night in milliseconds = 24*60*60*1000 = 86400000
    var one_night=86400000;
                        
    //  Have to round up to take into account that the miliseconds is not returned in UTF.  Could change to use something similar to:
    //  var num = Date.UTC(returnDate.getYear(),returnDate.getMonth(),returnDate.getDay()) - Date.UTC(departDate.getYear(),departDate.getMonth(),departDate.getDay()) / one_night;                   
    //var num = Math.ceil((returnDate.getTime() - departDate.getTime()) / one_night);  
	var num = Math.round((returnDate.getTime() - departDate.getTime()) / one_night);  
    var nights = $('numNights');
                         
    if (nights != null) nights.innerHTML = num;
    var input = $('numNightsInput');
    if (input != null) input.value = num;

}

addCalendarDays = function(date, delta) {
    // Get the calendar date 24h before the current date.
    var result = new Date();
    result.setTime(date.getTime() + delta*(24 * 60 * 60 *1000) );
    if (result.getDate() == date.getDate()) {
      // Special case if date had more than 24 hours to it (DST!)
      result.setTime(result.getTime() + (delta > 0 ? 1 : -1 ) *60 * 60 * 1000);
    }
         
    // Clamp the time to the original time:
    result.setHours(date.getHours());
    return result;
}
  
var SearchPanel = Class.create();


SearchPanel.prototype = {
	
	//Variable for IBE server URL
	requestURL: '',
	maxChildren: '',
	hotelMaxInfantAge: '',
	packageMaxInfantAge: '',
	// If the return date is set to be earlier than the return date then the return date is reset to be this number of days after the depart date
	CalenderReturnOffset: 7,
	
	
	/**
	* Constructor.
	* @param bundle Table bundle name.
	* @param name Table name.
	*/
	initialize: function() {
	
	},
  
  
  	/**
	 * This function loads the search panel selectors.
	 * This method will load the product panel for the current or default selected product
	 */
	loadSearchSelector: function() {
		//If the request url is not set use a relative URL
		var url = searchPanel.requestURL;
		if(url == '')
			url = '..';
	
		//perform AJAX
		new Ajax.Updater('searchPanel', url + '/common/searchPanelSelector.do',  
			{
				asynchronous:true,
				evalScripts:true,
				onComplete:this.assignSearchSelectorEvents
			}
		);		
	},
  
  	/**
	 * This function loads the search panel selectors
	 * @param searchType The  product search Panel to load.
	 */
	loadProductSearchSelector: function(searchType) {
	
		//If the request url is not set use a relative URL
		var url = searchPanel.requestURL;
		if(url == '')
			url = '..';
		
		//Add searchType as a parameter
		url = url + '/common/searchPanelSelector.do?';
		if(searchType != '')
			url = url + 'Search/searchType='+searchType;
		
		//perform AJAX		
		new Ajax.Updater('searchPanel', url,  
			{
			asynchronous:true,
			evalScripts:true,
			onComplete:this.assignSearchSelectorEvents
			}
			
		);
	},
	
	/**
	* Add the click event to the search panel radio buttons.
	* @param form.
	*/	
	assignSearchSelectorEvents: function(form) {
	
		$$('input[name=Search/searchType]').each(function(curInput) {
			Event.observe(curInput, 'click', function() {
				new SearchPanel().processChange();
				new SearchPanel().updateCMS();
			});
		});
		//new SearchPanel().processChange();
		//delete onclick search button property to avoid search until all form fields are loaded
		//$('search.search-link').onclick='';
	},
	
	/**
	 * This function sends an Ajax request to update the search panel from the users search type selection
	 */
	processChange: function() {
		
		//If the request url is not set use a relative URL
		var url = searchPanel.requestURL;
		if(url == '')
			url = '..';
		
		//Standard Ajax
		new Ajax.Updater('searchPanel-form', url + '/common/searchPanelForm.do',
			{
				asynchronous:true,
				evalScripts:true,
				parameters: Form.serialize($('plan_trip')),				
				onSuccess: function(transport){
					//restore de value to the search button onclick function to allow search after all fields of search are complete.
					$('search.search-link').onclick= function onclick(event){javascript:searchPanel.submitSearch();return false;};
				}				
			}
		);
		
		//Ajax with Slide only effect
		/**new Effect.SlideUp('searchPanel-form');
		new Ajax.Updater('searchPanel-form',  url + '/common/searchPanelForm.do',  
		{
			asynchronous:true,
			evalScripts:true,
			parameters: Form.serialize($('plan_trip')), 
			onSuccess: function(transport){
				new Effect.SlideDown('searchPanel-form', {
					queue: 'end',
					beforeSetup: function() {
						$('searchPanel-form').innerHTML=transport.responseText;
					}
				});
			}
		});*/
		
		//Ajax with  Opacity  effect only. 
		/**new Effect.Opacity('searchPanel-form', { from: 1.0, to: 0.0, duration: 0.5 });
		new Ajax.Updater('searchPanel-form',  url + '/common/searchPanelForm.do',  
		{
			asynchronous:true,
			evalScripts:true,
			parameters: Form.serialize($('plan_trip')), 
			onSuccess: function(transport){
				new Effect.Opacity('searchPanel-form', {
					from: 0,
					to: 1.0,
					duration: 1.25,
					queue: 'end',
					beforeSetup: function() {
						$('searchPanel-form').innerHTML=transport.responseText;
					}
				});
			}
		});*/
		
		//Ajax with combined Opacity and slider effect. Combined to make transition smooth
		/**new Effect.Opacity('searchPanel-form', { from: 1.0, to: 0.0, duration: 0.5 });
		new Effect.SlideUp('searchPanel-form', { duration: 0.25 });
		new Ajax.Updater('searchPanel-form',  url + '/common/searchPanelForm.do',  
		{
			asynchronous:true,
			evalScripts:true,
			parameters: Form.serialize($('plan_trip')), 
			onSuccess: function(transport){
				new Effect.SlideDown('searchPanel-form', {duration: 0.1});
				new Effect.Opacity('searchPanel-form', {
					from: 0,
					to: 1.0,
					duration: 1.25,
					queue: 'end'
				});
				$('searchPanel-form').innerHTML=transport.responseText;
			}
		});*/
	},
	
	updateCMS: function() {
		//If the request url is not set use a relative URL
		var url = searchPanel.requestURL;
		if(url == '')
			url = '..';
			
		if(reloadCMSCentral){
			new Ajax.Updater('centralbox', url + '/common/updateCMScentral.do',
				{
					asynchronous:true,
					evalScripts:true,
					parameters: Form.serialize($('plan_trip')),	
					onSuccess: function(transport){

					}				
				}
			);
		}
	},
	
	/** 
	*
	* Flight search panel methods. START *
	*
	*/
	
	/**
	* Toggles search panel between  return and oneway .
	* @param flightType.
	*/
	toggleOneWayFlights: function(flightType) {
	
		if(flightType == 'oneway')
		{
			$('return-date-selector').setStyle({display: 'none'});
			if ($('return-time-selector')) 
			{
				$('return-time-selector').setStyle({display: 'none'});
			}
			$('returnFlexibility').setStyle({display: 'none'});
			$('calendarSearch-block').setStyle({display: 'none'});
	        this.updateCheckboxValue('calendarSearchCheck', false);
		}
		else if(flightType == 'return')
		{
			$('return-date-selector').setStyle({display: 'block'});
			if ($('return-time-selector')) 
			{
				$('return-time-selector').setStyle({display: 'block'});
			}
			$('returnFlexibility').setStyle({display: 'block'});
			$('calendarSearch-block').setStyle({display: 'block'});           
	    }
	},
	
	/** 
	*
	* Flight search panel methods. END *
	*
	*/
	
	
	/** 
	*
	* Hotel search panel methods. START *
	*
	*/
	
	/**
	* Function to update room selectors.
	* @param numRooms.
	*/
	changeNumberRooms: function(numRooms) {
	
		var rooms = $$('#searchPanel-rooms .searchPanel-hotel-room');
		
		for(var i=0; i<rooms.length; i++){
		
			var room = rooms[i];
			var roomNumber = i+1;
				
			if (roomNumber <= numRooms) {
				room.setStyle({
				  display: 'block'
				});
			}
			else {	
				room.setStyle({
				  display: 'none'
				});
			}
		}
		this.addChildAges();

	},
	
	/**
	* Function to update child age selectors. Determine if Child Rooms Block shouel be displayed
	*/
	addChildAges: function() {
	
		var anyChildrenPresent=false;
		var rooms = $$('#searchPanel-rooms .searchPanel-hotel-room');
		var maxRooms = rooms.length;
		var numRooms = $('numRooms').value;
		
		// For each room
		for(roomNumber=1; roomNumber<=maxRooms; roomNumber++)
		{	
			// Get the number of children (for this room)
			var numChildInRoom = $('numChildrenRoom_' + roomNumber).value;
			var childrenPresentInRoom = false;
			if(numChildInRoom > 0 && roomNumber <= numRooms)
			{
				childrenPresentInRoom=true;
				anyChildrenPresent = true;
			} 
			
			// For each child, show its age input
			for(childIndex = 1; childIndex<=this.maxChildren; childIndex++)
			{    	
				var roomId = 'room' + roomNumber + 'AgeFieldChild' + childIndex;
				
				if(childIndex <= numChildInRoom)
				{
					$(roomId).setStyle({display: 'block'});
				}
				else
				{
					$(roomId).setStyle({display: 'none'});
				}
			}
			
			//Show hide individulal Child ages room blocks
			if(childrenPresentInRoom){
				$('child-ages-room'+roomNumber).setStyle({display: 'block'});
		  	} else{
		  		$('child-ages-room'+roomNumber).setStyle({display: 'none'});
		  	}
		}
		
		//Show hide all Child ages room blocks
		if(anyChildrenPresent){  		 
			$('hotelChildRoomsBlock').setStyle({display: 'block'});
			//Uncomment next line to restore infant seat selection
			//this.changeChildAge(); 
	  	} else{
			$('hotelChildRoomsBlock').setStyle({display: 'none'});
	  	}
	  	
	},
	
	/**
	* Function to update child age selectors.
	*/
	changeChildAge: function() {
		
		//The number of infants selected in this search panel
		var infantCount = 0; 
		
		$$('select[class=roomAgeSelect]').each(function(curInput) {
			age = curInput.value;
			
			if(age > -1){
				if(age <= this.hotelMaxInfantAge)
					infantCount++;		
				else{
					if(age <= this.packageMaxInfantAge)
						infantCount++;
				}
			}
		});
		//Uncomment below if using infant seat selection
		/**
		if(infantCount > 0 ){
			$('infantSeatSelection').setStyle({display: 'block'});
		} else {
			$('infantSeatSelection').setStyle({display: 'none'});
		}*/
	},

	/** 
	*
	* Hotel search panel methods. END *
	*
	*/
	
	/** 
	*
	* Vehicle search panel methods. START *
	* @param numRooms.
	*/
	toggleCarSelectDropOff: function(toggletype) {
		
		if(toggletype == 'diff'){
			$('searchPanel-car-selector-dropOff-location').setStyle({display: 'block'});
			$('carSelectorDropOffSameLocation').setStyle({display: 'block'});
			$('carSelectorDropOffDiffLocation').setStyle({display: 'none'});
			$('carSelectorDropOffDiff').setValue('');
		}
		if(toggletype == 'same'){
            $('Search-VehicleInformation-dropOffLocation').value = $('Search-VehicleInformation-pickUpLocation').value;
            $('Search-VehicleInformation-dropOffLocation_input').value = '';
			$('searchPanel-car-selector-dropOff-location').setStyle({display: 'none'});
			$('carSelectorDropOffDiffLocation').setStyle({display: 'block'});
			$('carSelectorDropOffSameLocation').setStyle({display: 'none'});
			$('carSelectorDropOffSame').setValue('');
		}
	},
	
	setDropOffValues: function() {

		$('Search-VehicleInformation-dropOffLocation_input').value = $('Search-VehicleInformation-pickUpLocation_input').value;
		$('Search-VehicleInformation-dropOffLocation').value = $('Search-VehicleInformation-pickUpLocation').value;
	},
	/** 
	*
	* Vehicle search panel methods. END *
	*
	*/
	
	
	/** 
	*
	* Extra search panel methods.START *
	*
	*/
	addEventChildAges: function() {	
	
		// Get the number of children (for this room)
		var numChildren = $('eventChildPassengers').value;	
		var childrenPresent = (numChildren>0);
		
		// For each child create an age input
		for( i = 1; i <= this.maxChildren; i ++)
		{
			if(i <= numChildren){
				$('eventAgeFieldChild' + i).setStyle({display: 'block'});
			}
			else{
				$('eventAgeFieldChild' + i).setStyle({display: 'none'});
			}     
		}
		
		 if(childrenPresent){			
			$('eventAgeSelection').setStyle({display: 'block'});
			searchPanel.changeEventChildAge();   	
		  }
		  else {
			$('eventAgeSelection').setStyle({display: 'none'});
		  }

	},
	
	changeEventChildAge: function(){

		var infantPresent = false;
		var infantCount = 0; //The number of infants selected in this search panel
		$$('select[class=eventAgeSelect]').each(function(curInput) {
			age = curInput.value;
			if(age > -1 && age <= eventMaxInfantAge){		
				infantCount++;			
			}
		});
	},	
	/** 
	*
	* Extra search panel methods. END *
	*
	*/
	

	
	/**
	* Function to test if checkbox values are present before updating them. Required as some may be optional
	* @param inputName.
	* @param inputValue.
	*/
	updateCheckboxValue: function(inputName, inputValue) {
		input = document.getElementById(inputName);
		if(input != null)
			input.checked = inputValue; 
	},
	
	/**
	* Function to test if input values are present before updating them. Required as some may be optional
	* @param inputName.
	* @param inputValue.
	*/
	updateInputValue: function(inputName, inputValue) {
		input = document.getElementById(inputName);
		if(input != null)
			input.value = inputValue; 
		
	},
	
	/**
	* Function to toggle extra search options
	*/
	toggleMoreOptions: function() {
		if(!document.getElementById('Search-moreOptions').checked) {  
	
		document.getElementById('searchPanel-additional-options').style.display = 'none';	  
        document.getElementById('Search-moreOptions').value = 'false';
		}
		else {	
			document.getElementById('searchPanel-additional-options').style.display = 'block';
			document.getElementById('Search-moreOptions').value = 'true';
		}
	},
	
	/**
	* Function to toggle extra search options
	*/
	pickTheFirstLocation: function() {
		//For Each Location input box
		$$('input[class=inputtext locationinput selectInput]').each(function(curInput) {
			
			//get input name
			var inputName = curInput.getAttribute('ojname');
			//Choices div
			var choices = $(inputName + '_choices');
			//current chosen location
			var choosenLocation = $(inputName).value;
			
			//determine if there are locations in the list
			var locaitonNotInTheList = false;
	    	if( choosenLocation == '' || choices.innerHTML.indexOf(choosenLocation) == -1 ) 
	    	{
	    		locaitonNotInTheList = true;
	    	}
			
			//Get the first location in the list id
	    	var idString = searchPanel.getValueByAttribute(choices, 'id' );
			//Get the first location in the list name
	    	var nameString = searchPanel.getValueByAttribute(choices, 'name' );
	
			//Set the location if the first in the listif the user did not select one
	    	if ( locaitonNotInTheList && choosenLocation != idString && choices.innerHTML != '' && idString != '' && nameString != '' )
	    	{
	    		//Set the xlocation ID in the Search Form
	    		$(inputName).value = idString;
	    		//Set the xlocation location string in the Search Form
	    		$(inputName+'_input').value = nameString;
	    	}
		});		
	},

	/**
	* Get the value of an attribte from an xLocation Choices block
	* @param choices.
	* @param attr.
	*/
	getValueByAttribute: function(choices, attr) {
	
		if (choices.firstChild!=null && choices.firstChild.firstChild!=null) {
			return choices.firstChild.firstChild.getAttribute(attr) ;
		} else {
			return "";
		}		
	},
    
    /** Function to test if radio buttons are checked: Required as some may be optional.
     * @param radio.
     */
    isRadioButtonChecked: function(radio) {
        if (radio != null) {
            return radio.checked;
        }
        else {
            return false;
        }
    },
	
	/**
	* Function to Submit  the searchPanel plan_trip from
	*/
	submitSearch: function() 
	{		
		//check number of nights > 0 in hotel & package search		
		if(((this.isRadioButtonChecked(document.getElementById('radio_hotelOnly')))
				||(this.isRadioButtonChecked(document.getElementById('radio_flightHotel')))
				||(this.isRadioButtonChecked(document.getElementById('radio_charter')))
				||(this.isRadioButtonChecked(document.getElementById('radio_flightHotelCar')))
                )&&(document.getElementById('numNights').innerHTML=='0'))
		{
			alert(document.getElementById('validateNightsMsg').value);
			return false;
		}
		else
		{
			//check user location input
			this.pickTheFirstLocation();
			//set the form to Post
			document.getElementById("plan_trip").method="POST";					
			//submit the form
			document.plan_trip.submit();		
		}
	}
	
};
	
function loadSearchPanel(url) {
	searchPanel = new SearchPanel();
	searchPanel.requestURL = url;
	searchPanel.loadSearchSelector();
}	
	
function loadProductSearchPanel(url, searchType) {
	searchPanel = new SearchPanel();
	searchPanel.requestURL = url;
	searchPanel.loadProductSearchSelector(searchType);
}
