//meetings.js
	
function newWindowSm(file) {
	 msgWindow=open('','window','resizable=no,scrollbars=no,menubars=no,toolbars=no,location=no,resizable=no,width=310,height=300');
	 msgWindow.location.href = file;
	 if (msgWindow.opener == null) msgWindow.opener = self;
}

function addLoadEvent(func) {
  		var oldonload = window.onload;
  		if (typeof window.onload != 'function') {
    		window.onload = func;
  		} else {
    			window.onload = function() {
      				oldonload();
      				func();
    			}
  		} 
	}
	
// This function ensures that if a State is
// selected, then USA is auto-populated as the country

function SetCountryList(objForm, stateField, countryField)
{
	  if ( objForm.elements[stateField].selectedIndex == 0 )
	  {
	    objForm.elements[countryField].selectedIndex = 0;
	  }
	  else
	  {
	    objForm.elements[countryField].value = "US";
	  }
}


// set the state list
function SetStateList(objForm, stateField, countryField)
{
	if (objForm.elements[countryField].value != 'US') {
		objForm.elements[stateField].selectedIndex = 0;
	}
}

function isBlank(testStr) {
	if (testStr.length == 0)
	  return true
	for (var i = 0; i <= testStr.length-1; i++)
	  if (testStr.charAt(i) != " ")
		return false
	return true
}

function checkWeatherNumber(testStr)
{
	var pattern="0123456789";
    var Char;

 
    for (i = 0; i < testStr.length; i++) 
	{ 
		Char = testStr.charAt(i); 
		if (pattern.indexOf(Char) == -1) 
		{
         	return false;
		}
	}
	
	// Check to see if the number is grater than 0.
	var num = parseInt( testStr ) ;
	if(num != NaN && num <= 0){
		return false;	
	}
	return true;
}

// Function to remove comma, and remove leading 0s.
function formatNumber(aNum) {

	//remove any commas
	aNum=aNum.replace(/,/g,"");

	//remove any spaces
	//aNum=aNum.replace(/\s/g,"");

	while (aNum.length > 1 && aNum.charAt(0)=="0")
	{
		aNum=aNum.substring(1,aNum.length);
	}

	return aNum;

}//end of formatNumber(aNum)

function validateWeddingForm (form)
{
	var countryIndex = $(form).find('select[name=searchCriteriaVO.country]').attr('selectedIndex');
	var stateIndex = $(form).find('select[name=searchCriteriaVO.stateProvince]').attr('selectedIndex');
	
	//If both state and country are not selected
	if ((countryIndex == 0) && (stateIndex == 0))
	{
		alert("Please select a state or country.");
		return false;
	}
	
	// If selected USA is selected as country annd state is not selected
	if($(form).find('select[name=searchCriteriaVO.country] option:selected').val() == 'US' && stateIndex == 0)
	{
		alert("When selecting the country USA, you must specify a state.");
		return false;
	}
	
	return true;

}
function ValidateStateAndCountry(form) 
{
	var siteId = $(':hidden[name=siteId]').val();
	var cityInputField = $(form).find(':input[name=searchCriteriaVO.city]').val();
	var countryIndex = $(form).find('select[name=searchCriteriaVO.country]').attr('selectedIndex');
	var stateIndex = $(form).find('select[name=searchCriteriaVO.stateProvince]').attr('selectedIndex');
	
	if ((siteId != null && siteId != "" ) || $(":hidden[name=cityStateError]").get(0) == undefined)
	{
		//If both state and country are not selected
		if ((countryIndex == 0) && (stateIndex == 0))
		{
			alert("Please select a state or country.");
			return false;
		}
		
		// If selected USA is selected as country annd state is not selected
		if($(form).find('select[name=searchCriteriaVO.country] option:selected').val() == 'US' && stateIndex == 0)
		{
			alert("When selecting the country USA, you must specify a state.");
			return false;
		}
			
	}
	else
	{
		var cityStateError = $(":hidden[name=cityStateError]").val();
		
		if ((cityInputField == "") && (countryIndex == 0) && (stateIndex == 0))
		{
			alert(cityStateError);
			return false;
		}
	}
	return true;
}

var meetingsLanding = {

 INVALID_ROOMS_MSG_US : "Please enter a valid number greater than zero for 'Number of Sleeping Rooms Required'",	
 INVALID_ROOMS_MSG : "Please enter a valid number greater than zero for 'Maximum number of sleeping rooms.'",
 INVALID_SPACE_MSG : "Please enter a valid number greater than zero for 'Largest Meeting Room Needed.'",
 INVALID_SPACE_MSG_US : "Please enter a valid number greater than zero for 'Largest Meeting Space Required'",

 init : function(){
	//attaches submit event to groupsales form on Events & Meetings Page.
	var meetingsForm = $('form.events-meetings-groupsales-searchform');
	if( meetingsForm && meetingsForm.length > 0)
	{
		$(meetingsForm).submit(meetingsLanding.validateRequiredFields);
		$(meetingsForm).find('select[name=searchCriteriaVO.searchType]').change(function(){
			DisableFields(this.form);
		});
		DisableFields(meetingsForm[0]);
	}	
 },
/** This function does validation for the E&M search pages. 
A pop up message is displayed for validation errors
*/
validateRequiredFields :function() 
{
	var meetingsForm = this;
	var sgoSupported = $(meetingsForm).find(':hidden[name=sgoSupported]').val();
	
	if(sgoSupported === 'true')
	{
		var eventType = $(meetingsForm).find('select[name=searchCriteriaVO.searchType]').get(0);
		
		if((eventType) && (eventType.value == ""))
		{
			alert("Please enter a meeting/event type.");	
			return false;
		}
	}
	// Begin Validating common fields for US and non US pages
	
	if(!ValidateStateAndCountry(meetingsForm))
	{
		  return false;
	}

	// End Validating common fields for US and non US pages
	
	if(sgoSupported === 'true')
	{
		
		// validate 'US' specific fields - event options, dates etc.
		if(meetingsLanding.validateSgoFields(meetingsForm))
		{
			
			var roomCount = groupSales.getRoomCount(meetingsForm,"InCity");
			var spaceCount = groupSales.getMeetingSpace(meetingsForm,"InCity");
		
			var numRoomsArray = $(meetingsForm).find(':input[name=searchCriteriaVO.guestRoomCount]');
			var meetingSpaceArray = $(meetingsForm).find(':input[name=searchCriteriaVO.sizeLargestMeetingRoom]');
	
			/* Set num rooms and meeting space fields. Since, there are two text boxes each for rooms and space,
				we need to set the value respective fields.
			*/
				
			groupSales.setRoomElements(numRoomsArray, roomCount);
			groupSales.setRoomElements(meetingSpaceArray, spaceCount);		
		
			return true;
		}
		else
		{
			return false;
		}	
	}
	else
	{
		// validate UK and DE fields
		var minSpace = $(meetingsForm).find(':input[name=searchCriteriaVO.sizeLargestMeetingRoom]').val();
		var minGuest = $(meetingsForm).find(':input[name=searchCriteriaVO.guestRoomCount]').val();
		var eventType = $(meetingsForm).find('select[name=searchCriteriaVO.searchType] option:selected').val();
	
		if(!groupSales.showInvalidNumMsg(minGuest,meetingsLanding.INVALID_ROOMS_MSG))
		{		
			return false;
		}
		if(!groupSales.showInvalidNumMsg(minSpace,meetingsLanding.INVALID_SPACE_MSG))
		{
			return false;
		}		
		
		groupSales.setNumRooms($(meetingsForm),minGuest);
		groupSales.setMeetingSpace($(meetingsForm),minSpace);
		
		if (isBlank(minGuest) && isBlank(minSpace))
		{		
			if((sgoSupported == 'true') || (eventType == 'Meeting'))
			{
			  alert("Please enter at least one value for 'Maximum number of sleeping rooms' or 'Largest Meeting Room Needed'");
			  return false;
			}
		}	
	}	
},


/* This method validates the Event Rooms and Space section of the E&M landing page. 
	A popup message is displayed in case of a validation error.
*/
validateSgoFields : function(form) {

	var eventsChecked = false;
	var eventOptionsValue;
	var maxRooms;
	var meetingSpace;
	
	// Retrieve all the error msgs that are supposed to be displayed from the JSP
	var noEventOptionsMsg = $(':hidden[name=noEventOptionsMsg]').val();
	var roomsOnlyErrorMsg = $(':hidden[name=roomsOnlyError]').val();
	var roomsAndSpaceErrorMsg = $(':hidden[name=roomsAndSpaceError]').val();
	var spaceOnlyErrorMsg = $(':hidden[name=spaceOnlyError]').val();
	var invalidRoomsAndSpaceErrorMsg = $(':hidden[name=invalidRoomsAndSpaceError]').val();
	
	var eventType = $(form).find('select[name=searchCriteriaVO.searchType] option:selected').val();
		
	var eventOptionsArray = $(form).find(':radio[name='+groupSales.EVENTOPTIONS+']'); 
	
	if(!dates.validateEandMDates(form,"searchCriteriaVO.fromDate","searchCriteriaVO.toDate"))
	{
		return false ;
	}
	
	if(eventOptionsArray)
	{
		for(var i=0; i<eventOptionsArray.length;i++)
		{
			/* Check to see if any of the radio buttons has been clicked. 
			If clicked, then validate applicable rooms and space info */
			
			if(eventOptionsArray[i].checked)
			{
				eventsChecked = true;
				eventOptionsValue = eventOptionsArray[i].value;
				
				if(eventOptionsValue == 'roomsOnly')
				{
					if(document.getElementById("roomCount-InCity-1"))
					{
						maxRooms = document.getElementById("roomCount-InCity-1").value;
					}	
					if((isBlank(maxRooms)) && (roomsOnlyErrorMsg))
					{
						alert(roomsOnlyErrorMsg);						
						return false;											
					}
				}  // End roomsOnly if blk
				
				else if(eventOptionsValue == 'roomsAndSpace')
				{					
					if(document.getElementById("roomCount-InCity-2"))
					{
						maxRooms = document.getElementById("roomCount-InCity-2").value;
					}
					if(document.getElementById("largestMeetingSpace-InCity-1"))	
					{
						meetingSpace = document.getElementById("largestMeetingSpace-InCity-1").value;
					}
					
					if((isBlank(maxRooms) || isBlank(meetingSpace)) && (roomsAndSpaceErrorMsg))	
					{						
							alert(roomsAndSpaceErrorMsg);						
							return false;											
					}
					
					// If both rooms and space entered are invalid.
					if((!checkWeatherNumber(maxRooms)) && (!checkWeatherNumber(meetingSpace)) && (invalidRoomsAndSpaceErrorMsg))
					{
						alert(invalidRoomsAndSpaceErrorMsg);
						return false;
					}
					
				} // End RoomsAndSpace if blk
				
				else if(eventOptionsValue == 'spaceOnly')
				{
				
					if(document.getElementById("largestMeetingSpace-InCity-2"))	
					{
						meetingSpace = document.getElementById("largestMeetingSpace-InCity-2").value;
					}
					
					if(isBlank(meetingSpace) && (spaceOnlyErrorMsg))
					{
						alert(spaceOnlyErrorMsg);						
						return false;
					}
					
				}// End spaceOnly if blk
				
				if((maxRooms) && (!isBlank(maxRooms)))
				{	
					// If rooms are between 1-3 or 4-9 for rooms only scenario, display message			
					if(eventOptionsValue == 'roomsOnly')
					{
						if(maxRooms >= 4 && maxRooms <= 9)
						{
							alert("For reservations of 4-9 rooms, you may reserve online. Make multiple reservations of up to 3 rooms each.");
							return false;
						}
						if(maxRooms >= 1 && maxRooms <= 3)
						{
							alert("For reservations of 1-3 rooms, you may reserve online from the Marriott.com home page.");
							return false;
						}
					}
					
					// If max rooms is an invalid number, display msg.	
					if(!groupSales.showInvalidNumMsg(maxRooms,meetingsLanding.INVALID_ROOMS_MSG_US))
					{
						return false;
					}
				}
				
				// If space is an invalid number, display msg.		
		
				if((meetingSpace) && (!isBlank(meetingSpace)))
				{
					if(!groupSales.showInvalidNumMsg(meetingSpace,meetingsLanding.INVALID_SPACE_MSG_US))
					{
						return false;
					}
				}							
			} // Enf if eventOptions checked
		} // End for loop close
	} // End top most if
	
	// If no Event options radio button is checked, display error msg.

	if((!eventsChecked) && (noEventOptionsMsg))
	{	
			alert(noEventOptionsMsg);
			return false;				
	}	
	// Display alert msg if government event type has been selected
	groupSales.displayGovernmentEventMessage(form, eventType);
	
	return true;	
	
}

}

// End meetingsLanding

/*
Funciton that disables rooms and space section on the E&M landing page when event type is 'meeting'
*/
function DisableFields(objForm) 
{
	var meetingsForm = objForm;
	
	var eventTypeSelect = $(meetingsForm).find('select[searchCriteriaVO.searchType] option:selected').get(0);
	var divTag = document.getElementById('optional-fields');
	var sgoSupported = $(meetingsForm).find(':hidden[name=sgoSupported]').val();
	
	if(sgoSupported != 'true')
	{
		if (eventTypeSelect.value != 'Meeting') {
		$(meetingsForm).find(':input[name=searchCriteriaVO.guestRoomCount]').val('');
		$(meetingsForm).find(':input[name=searchCriteriaVO.guestRoomCount]').attr('disabled', true);
		$(meetingsForm).find(':input[name=searchCriteriaVO.sizeLargestMeetingRoom]').val('');
		$(meetingsForm).find(':input[name=searchCriteriaVO.sizeLargestMeetingRoom]').attr('disabled', true);
		$(meetingsForm).find(':input[name=searchCriteriaVO.spcunits]').attr('disabled', true);
			if (divTag.className == "enable-fields") {
				divTag.className = "disable-fields";			
			}
		}
		else {
			$(meetingsForm).find(':input[name=searchCriteriaVO.guestRoomCount]').attr('disabled', false);
			$(meetingsForm).find(':input[name=searchCriteriaVO.sizeLargestMeetingRoom]').attr('disabled', false);
			$(meetingsForm).find(':input[name=searchCriteriaVO.spcunits]').attr('disabled', false);
			
			if (divTag.className == "disable-fields") {
			   divTag.className = "enable-fields";	
			}
		}
	}
} 

function showPrinterFriendlyGroupSales(urlExtension)
{
		//windowName = "Printer_Friendly_GroupSales"; 
		page = "/meetings/schedule-meeting/review" + urlExtension + ".mi?"
		+ "submitAction=printerFriendly";
		
		//IPMI00036683
		sendto('','',page,'15');
		
		//windowprops = "height=600,width=800,location=no,"
		//+ "scrollbars=yes,menubar=no,toolbar=yes,resizable=yes"
		//+ ",left=100,top=50";
		
		//printerfriendlywin = window.open("about:blank", windowName, windowprops);
		
		//if (printerfriendlywin.open && 
        //      !printerfriendlywin.closed) {
        //       printerfriendlywin.close();
        //}  
  
       // printerfriendlywin = window.open(page, windowName, windowprops);
			
}


// Function for printer friendly link for terms and conditions on the review page.
function showPrinterFriendlyTerms()
{
		page = "/meetings/group-travel/terms.mi?"+ "submitAction=printerFriendly";
		sendto('','',page,'15');
}	


function getFormFromType(searchType)
{
	if(searchType == 'InCity')
	{
		var inCityForm = $('form.group-sales-incity-form')[0];
	  	return inCityForm;
	}
	
	if(searchType == 'NearAddress')
	{
		var nearAddressForm = $('form.group-sales-near-address-form')[0];
	  	return nearAddressForm;
	}
	
	if(searchType == 'NearAirport')
	{
		var nearAirportForm = $('form.group-sales-near-airport-form')[0];
		return nearAirportForm;
	}
	if (searchType == 'VaryByNight')
	{
		var varyByNightForm = $('form.group-sales-vbn-form')[0];
		return varyByNightForm;
	}
	
 
}

/*function startDate_onchange(form){
	var fromDate = document.forms[form].elements["fromDate"];
	if ( fromDate != null )
	{
		var dateFormatPattern = YAHOO.calendarUtil.module.getDateFormatPattern() ;
		var checkInDate = getDate(fromDate,dateFormatPattern) ;
		var toDate = document.forms[form].elements["endDate"];
		var checkOutDate = null ;
		if(toDate != null){
			checkOutDate = getDate(toDate,dateFormatPattern) ;
		}

		if (checkOutDate == null || checkInDate >= checkOutDate || checkInDate < checkOutDate)
		{     
			toDate = datePlusOne(fromDate,dateFormatPattern) ;
			document.forms[form].elements["endDate"].value = toDate;
		}
	}

} */

function arrivaldate_onchange(isGroupSales, searchType)
{
	var form = getFormFromType(searchType);
	if (isGroupSales == 'true')
	{
		if (determineSGO(searchType, form))
		{
			var isSGO = $(form).find(':hidden[name=sgoSearch]').val();
			var isVaryByNight = $(form).find(':hidden[name=varybyNights]').val();
			if (isSGO == 'true' && isVaryByNight == 'true')
			{ 
				$(form).attr('action', "/meetings/group-travel/group-rooms.mi");
				$(form).submit();
			}
		}
	}
}

function departuredate_onchange(isGroupSales, searchType)
{
	var form = getFormFromType(searchType);
	if (isGroupSales == 'true')
	{
		if (determineSGO(searchType, form))
		{
			var isSGO = $(form).find(':hidden[name=sgoSearch]').val();
			var isVaryByNight = $(form).find(':hidden[name=varybyNights]').val();
			
			if (isSGO == 'true' && isVaryByNight == 'true')
			{ 
				$(form).attr('action', "/meetings/group-travel/group-rooms.mi");
				$(form).submit();
			}
		}
	}
}


function setInnerHtml()    //<%NEED TO REFACTOR Later%>
{
	var getAllString = document.getElementById('getAll').innerHTML;
	// Replace javascript: string from the request.	
	getAllString = getAllString.replace(/javascript:/gi, "js:");	
	$('form#erfpConfirmForm').find(':hidden[name=innerHtml]').val(getAllString).end().submit();
}


// Start JavaScripts for SGO Project 

//Function to disable check boxes and dropdowns on the groupsales form when a particular event type is selected.
 function disableEventFields(){
		
	var eventTypeSelected=document.forms['groupSalesForm'].elements['erfp.currentEventInfo.eventType'].options[document.forms['groupSalesForm'].elements['erfp.currentEventInfo.eventType'].selectedIndex].value;
		
    var divTag = document.getElementById("optional-fields");
  
	if((eventTypeSelected == "breakfast.list") || (eventTypeSelected == "brunch.list") || (eventTypeSelected == "luncheon.list")
			|| (eventTypeSelected == "dinner.list"))
	{
	
		document.forms['groupSalesForm'].elements['erfp.currentEventInfo.eventchkContBreakfast'].value = "";
		document.forms['groupSalesForm'].elements['erfp.currentEventInfo.eventchkContBreakfast'].disabled = true;
		
		document.forms['groupSalesForm'].elements['erfp.currentEventInfo.eventchkCoffeeBreak'].value = "";
		document.forms['groupSalesForm'].elements['erfp.currentEventInfo.eventchkCoffeeBreak'].disabled = true;
			
		document.forms['groupSalesForm'].elements['erfp.currentEventInfo.eventchkLunch'].value = "";
		document.forms['groupSalesForm'].elements['erfp.currentEventInfo.eventchkLunch'].disabled = true;
			
		document.forms['groupSalesForm'].elements['erfp.currentEventInfo.eventchkAfternoonBreak'].value = "";
		document.forms['groupSalesForm'].elements['erfp.currentEventInfo.eventchkAfternoonBreak'].disabled = true;			
			
		document.forms['groupSalesForm'].elements['erfp.currentEventInfo.eventContBreakfast'].value = "";
		document.forms['groupSalesForm'].elements['erfp.currentEventInfo.eventContBreakfast'].disabled= true;
		
		document.forms['groupSalesForm'].elements['erfp.currentEventInfo.eventCoffeeBreak'].value = "";
		document.forms['groupSalesForm'].elements['erfp.currentEventInfo.eventCoffeeBreak'].disabled= true;
			
		document.forms['groupSalesForm'].elements['erfp.currentEventInfo.eventLunch'].value = "";
		document.forms['groupSalesForm'].elements['erfp.currentEventInfo.eventLunch'].disabled= true;
			
		document.forms['groupSalesForm'].elements['erfp.currentEventInfo.eventAfternoonBreak'].value = "";
		document.forms['groupSalesForm'].elements['erfp.currentEventInfo.eventAfternoonBreak'].disabled= true;			
				
			if(divTag.className == "enable-fields") 
			{
				divTag.className = "disable-fields";
			}
	}		
	else
	{			
		document.forms['groupSalesForm'].elements['erfp.currentEventInfo.eventchkContBreakfast'].disabled = false;
		document.forms['groupSalesForm'].elements['erfp.currentEventInfo.eventchkCoffeeBreak'].disabled = false;
		document.forms['groupSalesForm'].elements['erfp.currentEventInfo.eventchkLunch'].disabled = false;
		document.forms['groupSalesForm'].elements['erfp.currentEventInfo.eventchkAfternoonBreak'].disabled = false;			
		document.forms['groupSalesForm'].elements['erfp.currentEventInfo.eventContBreakfast'].disabled= false;
		document.forms['groupSalesForm'].elements['erfp.currentEventInfo.eventCoffeeBreak'].disabled= false;
		document.forms['groupSalesForm'].elements['erfp.currentEventInfo.eventLunch'].disabled= false;
		document.forms['groupSalesForm'].elements['erfp.currentEventInfo.eventAfternoonBreak'].disabled= false;				
		
		if(divTag.className == "disable-fields") 
		{
				divTag.className = "enable-fields";
		}
			
	}			
} 

function daysInMonth( month, year )
{
  return 32 - new Date( year, month, 32 ).getDate();
}

// Function that determines if sgo criteria has been met
function determineSGO (searchType, form)
{ 
  var kDate = $(form).find(':hidden[name=kDate]').val();
  var isVaryByNight  = $(form).find(':hidden[name=varybyNights]').val();
  var roomCtElement = "roomCount";
  var roomCount;

  roomCount = groupSales.getRoomCount(form, searchType, roomCtElement);
  
  var fromDate = $(form).find(':input[name=fromDate]').val();
  var toDate = $(form).find(':input[name=toDate]').val();
  var checkIn = null ;
  var checkOut = null 
  var dateFormatPattern = $(':hidden[name=dateFormatPattern]').val().toLowerCase();

  if((fromDate != null && fromDate.length > 0) && isDateValid(fromDate,dateFormatPattern)){
	checkIn = getDate(fromDate,dateFormatPattern) ;
  }

  if((toDate != null && toDate.length > 0) && isDateValid(toDate,dateFormatPattern)){
	checkOut = getDate(toDate,dateFormatPattern) ;
  }
  
  var testDate = processDate(kDate);
  var daysDiff = calculateNoOfNights(checkIn, checkOut);
  var fdate = new Date();
  fdate.setDate(fdate.getDate()+3) ;
    
  if ((roomCount >= 10 && roomCount <= 25)
	  && ((checkIn != null && checkIn >= fdate && checkIn <= testDate) 
	  && (checkOut != null && checkOut >= fdate && checkOut <= testDate))
	  && (daysDiff >= 1 && daysDiff <= 7))
  {  
	 $(form).find(':hidden[name=sgoSearch]').val('true');
	 $(form).find(':input[name=varyByNight]').filter(':input[value=false]').attr('checked', true);
	 var enableVaryByNightModule = searchType+"VaryByNightModule";
	 var enableVaryByNightInclude = searchType+"VaryByNightInclude";

	$('#'+enableVaryByNightModule).show();
	$('#'+enableVaryByNightInclude).hide();
		
	 if (isVaryByNight == 'true')
	 {
		$('#'+enableVaryByNightInclude).show();	
		$(form).find(':input[name=varyByNight]').filter(':input[value=true]').attr('checked', true);
	 }
 
	 return true;
  }
  else
  {
  	$(form).find(':hidden[name=sgoSearch]').val('false');
  	$(form).find(':hidden[name=varybyNights]').val('false');
	
  	$('#InCityVaryByNightModule').hide();
  	
  	// only if not HWS search
  	if(document.getElementById("hwsSearchSgo").value == "false")
  	{
  		$('#NearAddressVaryByNightModule').hide();
  		$('#NearAddressVaryByNightInclude').hide();
  	}

  	$('#InCityVaryByNightInclude').hide();

	return false;
  }
}

//Intermediary function that sets the date 
function processDate(date)
{
	if (date != null)
	{
		var dateArray = date.split("/");
		var toDate = new Date();
		toDate.setFullYear(dateArray[2], dateArray[0]-1, dateArray[1]);
		toDate.setHours(0,0,0,0);
	}
  return toDate;

}

//Intermediary function to calculate number of nights
function calculateNoOfNights(checkInDate, checkOutDate)
{
	var daysDifference = 0;
	if (checkInDate != null && checkOutDate != null)
	{
		var difference = checkOutDate.getTime() - checkInDate.getTime();
		daysDifference = Math.round(difference/1000/60/60/24);
	}
	return daysDifference;
}

//Function that gets called when room field is changed
function roomcount_onchange(isGroupSales, searchType)
{
	var form = getFormFromType(searchType);
	if (isGroupSales == 'true')
	{	
		if (determineSGO(searchType, form))	
		{
			var isSGO = $(form).find(':hidden[name=sgoSearch]').val();
			var isVaryByNight = $(form).find(':hidden[name=varybyNights]').val();

			if (isSGO == 'true' && isVaryByNight == 'true')
			{

				var message = $(form).find(':hidden[name=changeMaxNum]').val();
				var ans = confirm(message);
				if (ans)
				{
					$(form).attr('action', "/meetings/group-travel/group-rooms.mi");
					$(form).submit();		
				}
				else
				{
					return false;
				}				
			}
		}
	}
}

/* Function that submits the form when the "Yes" or "No" radio button is clicked for the 
	the group sales varying by nights question
*/
function forward(searchType, isVaryByNights)
{
	
	var formObj = getFormFromType(searchType);
	
	var roomCount = groupSales.getRoomCount(formObj, searchType);
	var meetingSpace = groupSales.getMeetingSpace(formObj, searchType);
	
	if($(formObj).find(':input[name=varyByNight]').filter(':input[value=true]').attr('checked'))
	{
		$(formObj).find(':hidden[name=varybyNights]').val('true');
		$(formObj).attr('action', '/meetings/group-travel/group-rooms.mi');

		//var roomArray = document.forms[form].elements['roomCount'];
		var roomArray = $(formObj).find(':input[name=roomCount]');
		var spaceArray = $(formObj).find(':input[name=largestMeetingSpace]');
		
		//Submit Rooms
		if(roomArray.length > 0)
		{
			roomArray.each(function(){
				$(this).val(roomCount);
			});
		} 
		//Submit MeetingSpace
		if(spaceArray.length > 0)
		{
			spaceArray.each(function(){
				$(this).val(meetingSpace);
			});
		}
		
		$(formObj).submit();
	}
	else
	{
		$(formObj).find(':hidden[name=varybyNights]').val('false');
		//Disable all vary by night include modules
		$('#InCityVaryByNightInclude').hide();
		if($('#NearAddressVaryByNightInclude').length > 0 )
		{		
			$('#NearAddressVaryByNightInclude').hide();
		}
		
		$(formObj).attr('action', '/meetings/group-travel/group-rooms.mi');
		$(formObj).submit();

	}
}

/**
	This function gets called from the onchange of event type and largest meeting space.
	Disable Brand dropdown when user selects Event Type = Wedding & largest meeting space is not blank
*/
function disableBrand(searchType)
{

	var form = getFormFromType(searchType);
	var eventType = $(form).find('select[name=eventType] option:selected').val();
	var brandsObj = $(form).find('select[name=marriottBrands]')[0];
	var meetingSpaceObj = groupSales.getMeetingSpace(form, searchType);
	if(brandsObj)
	{
		if (eventType == 'Wedding'
				&& (meetingSpaceObj != null && checkWeatherNumber(meetingSpaceObj)) 
				&& (meetingSpaceObj != "" && meetingSpaceObj != 0))
		{
			brandsObj.disabled = true;
			brandsObj.selectedIndex = 0;
		}
		else
		{
			brandsObj.disabled = false;			
		}
	}
}

// Function that checks for validations on submit from the group sales search pages
function validateGroupSalesForm(form)
{
	var guestRoomTBODY = $(form).find('#guestRoomTbody');
	var isVaryByNight = $(form).find(':hidden[name=varybyNights]').val();
	var currentSearch = $(form).find('#currentSearchType');
	
	var searchType;
	
	if(currentSearch.length > 0)
	{
		searchType = currentSearch.val();
	}
	
	var isHwsSearchSgo = $(form).find(':hidden[name=hwsSearchSgo]');
	
	if((isHwsSearchSgo.length > 0) && (isHwsSearchSgo.val() == "true"))
	{
		searchType="InCity";
	}
	
	var eventType = $(form).find(':input[name=eventType]').val();
	
	var numRooms;
	var roomCount ;
	
	/* If on the Stand alone vary by nights page, getRoomCount would return null as 
		there would be only one hidden field for "roomCount" on the Standalone VBN page,
		whereas the getRoomCount checks for an array.
		We don't need roomCount for standAlone VBN Page. So, get the numRooms directly. 
	*/
	
	var standAloneVBNRooms = document.getElementById("standAloneVBNRooms");
	
	if(standAloneVBNRooms)
	{
		numRooms = document.getElementById("standAloneVBNRooms").value;		
	}
	else
	{ 
		roomCount= groupSales.getRoomCount(form,searchType,"roomCount");
	}
	var spaceCount;
	if($(':hidden[name=standAloneVBN]').length > 0)
	{
		spaceCount = $(form).find(':hidden[name=largestMeetingSpace]').val();
	}
	else
	{
		spaceCount = groupSales.getMeetingSpace(form,searchType);
	}
	
						
	if(roomCount >= 0)
	{
		numRooms = roomCount;			
	}
	
	var numRoomsArray = $(form).find(':input[name=roomCount]');
	var meetingSpaceArray = $(form).find(':input[name=largestMeetingSpace]'); 
		
	groupSales.setRoomElements(numRoomsArray, roomCount);
	groupSales.setRoomElements(meetingSpaceArray, spaceCount);

	// Display alert msg if government event type has been selected
	if($(':hidden[name=standAloneVBN]').length < 1)
	{
		groupSales.displayGovernmentEventMessage(form, eventType);
	}
	
	if (isVaryByNight == 'true')
	{
		if(guestRoomTBODY.length > 0 )
		{
			var meetingSpace = $(form).find(':input[name=largestMeetingSpace]').val();

			// Get the list of the guest room list		
			var guestRoomTableRows = $(guestRoomTBODY).get(0).getElementsByTagName("tr");
			var largestNumber = "0";

			for(var i=0;i<guestRoomTableRows.length;i++) 
			{			
				var totalRoomsId = "varyByNightVO["+i+"].totalRooms";
				var totalRooms = $(form).find('select[name='+totalRoomsId+']').val();
				if (Number(totalRooms) > largestNumber)
				{
					largestNumber = Number(totalRooms);
				}
			}
			if(Number(largestNumber) != Number(numRooms))
			{
				//var message = document.forms[form].elements['overrideMaxNum'].value;
				var message = $(form).find(':hidden[name=overrideMaxNum]').val();
				var ans = confirm(message);
				if (ans)
				{
					// If stand alone vbn page, then set the updated rooms into the roomCount hidden field
					if(standAloneVBNRooms)
					{
						$(form).find(":input[name=roomCount]").val(largestNumber);						
					}
					// Else, Set the latest room numbers in both the roomCount text boxes of the search forms (Splash pg, stand alone pg).
					else
					{	
						groupSales.setRoomElements(numRoomsArray, largestNumber);
					}
					if (largestNumber < 10 && (meetingSpace != null && meetingSpace != "" && meetingSpace != 0))
					{
							$(form).find(':hidden[name=sgoSearch]').val('false');
					}
				}
				else
				{
					return false;
				}
			}
		}

	}

	return true;
}


// Function to handle Continue button Click on GroupSales City, Address, Vary By Nights and Terms and Conditions pages.
function handleContinue(formType) 
{	
	if(formType != '' && formType != 'undefined')
	{		
		if(formType != 'groupSalesForm')
		{
			var form = getFormFromType(formType);	
			if(validateGroupSalesForm(form))
			{
				$(form).submit();
			}				
		}
		else
		{
			document.forms[formType].submit();
		}		
	}	
}

function submitForm(formName) 
{
	document.forms[formName].submit();
}

// Funtion to display the search tabs on SGO Search pages
function displayGroupSalesSearch(searchType){
	if(searchType == "InCity")
	{		
		handleClick("show it", "find-search-form", null);
		handleClick("hide it", "near-address-form", null);
	}
	else if(searchType == "NearAddress")
	{
		handleClick("show it", "near-address-form", null);
		handleClick("hide it", "find-search-form", null);		
	}

	// Set the search type to whatever radio button user clicked/the form user is on	
	if(document.getElementById("currentSearchType"))
	{
		document.getElementById("currentSearchType").value = searchType;
	}
	//disableBrand(searchType);
	groupSales.initializeVaryByNights(searchType);
}

// Function that handles radio button click
function handleClick(whichClick, whichLayer, actionLayer) {
	if (whichClick == "hide it") {
		// then the user wants to hide the layer
		hideLayer(whichLayer);
	}
	else if (whichClick == "show it") {
		// then the user wants to show the layer
		showLayer(whichLayer);
	} 
}

// Hide the layer
function hideLayer(whichLayer) {
	var layer = document.getElementById(whichLayer);
	layer.style.display = 'none';
}

// Show the layer
function showLayer(whichLayer) {
	var layer = document.getElementById(whichLayer);
	layer.style.display = 'block';
}

// End JavaScripts for SGO Project

//Space calculator functions

/******************************************************************
This function checks whether field is empty or not
Parameters : data
Returns    : 1 if data is empty or contains only spaces
			 0 if data is not empty
******************************************************************/
function isEmpty(data) {
	if (data.length == 0) {
		return 1;
	}

	for( i = 0;i < data.length; i++) {
			if (data.substr(i,1)!= " ")
				return 0;
		}
	return 1;

}
/******************************************************************
This function checks whether field is numeric or not
Parameters : flag,data
When flag  = 1 (Field cannot be empty)
Returns    : 1 if data is numeric
			 0 if data is not numeric or empty

When flag  = 0 (Field can be empty)
Returns    : 1 if data is numeric or empty
			 0 if data is not numeric
*******************************************************************/
function isNumeric(flag,data) {
	var integers ="0123456789";
	var i = 0;

	if (isEmpty(data)) {
		if (flag == 0)
			return 1;
		if (flag == 1) {
			return 0;
		}
	}

	for (i=0; i < data.length; i++) {
		if (integers.indexOf(data.substring(i,i+1)) == -1) {
			return 0;
		}
	}
	return 1;
}

function changelength()
{
	if (document.forms[0].sqfoot[0].checked==true)
	{
		document.forms[0].attendance.value="";
		document.forms[0].attendance.maxLength=4;
	}
	else
	{
		document.forms[0].attendance.value="";
		document.forms[0].attendance.maxLength=5;
	}
}

function SizeClose()
{
	var meetingSpaceField = document.getElementById("meetingSpaceField").value;
	var meetingSpaceUnitsField = document.getElementById("meetingSpaceUnitsField").value;
	var meetingSpaceArea = document.getElementById("meetingSpaceArea").value;
	var areaUnit = "sqFeet";

	if (window.opener.closed==false)
	{
		//set the room value in the main window
		if (document.forms[0].sqfoot[0].checked==true)
		{
			for(i=0; i<window.opener.document.forms.length; i++)
			{
				for(j=0; j<window.opener.document.forms[i].elements.length; j++)
				{
					if(window.opener.document.forms[i].elements[j].name == meetingSpaceField) 
					{
						window.opener.document.forms[i].elements[j].value=document.forms[0].result.value;
					}
				}
			}
		}
		else
		{
			areaUnit = "sqMeters";
			for(i=0; i<window.opener.document.forms.length; i++)
			{
				for(j=0; j<window.opener.document.forms[i].elements.length; j++)
				{
					if(window.opener.document.forms[i].elements[j].name == meetingSpaceField) 
					{
						window.opener.document.forms[i].elements[j].value=document.forms[0].result.value;
					}	
				}
			}
		}
		
		//set the radio button in the main window
		if(window.opener.document.forms.length > 0) 
		{ 
			var unitTypeGroup = utils.getElementsByClass(areaUnit+meetingSpaceArea, window.opener.document);	
			for(k=0; k<unitTypeGroup.length; k++)
			{
				unitTypeGroup[k].checked=true;
			}
		}
	}

	window.close()
}

function CloseWindow()
{
	window.close()
}

function ClearInput(form) {
form.attendance.value="";
/*form.attendance.value="";
form.banquet60.value="";
form.banquet72.value="";
form.theater.value="";
form.school18.value="";
form.school30.value="";
form.reception.value="";*/
form.result.value="";
return true;
}
function help(nothingentered) {
if (nothingentered == "attendance")
alert("Enter the number of people who will be attending your event.")
}

function SizeCalc()
{
	var units;
	if (document.forms[0].sqfoot[0].checked==true)
	{
		units="sqf";
	}
	else
	{
		units="sqm";
	}
	if (document.forms[0].attendance.value==null||document.forms[0].attendance.value.length==0)
	{
		alert("Please enter the number of people attending.");
		document.forms[0].attendance.focus();
		return false;
	}
	else
	{
		if (isNumeric(0,document.forms[0].attendance.value)==0)
		{alert("Please enter a numeric value");
		 document.forms[0].result.value="";
		 document.forms[0].attendance.focus();
		 return false;
		}
		else
		{
		document.forms[0].result.value="";
		if (units == "sqf")
		{
			if (document.forms[0].roomshape.selectedIndex==0)
			{
				if (document.forms[0].attendance.value>105250)
				{
					alert("Max number of people cannot be more than 105250"); 
					document.forms[0].attendance.focus();
					return false;
				}
				else
					{document.forms[0].result.value=Math.round(9.5 * document.forms[0].attendance.value);}
			}
			if (document.forms[0].roomshape.selectedIndex==1)
			{
				if (document.forms[0].attendance.value>68950)
					{
						alert("Max number of people cannot be more than 68950"); 
						document.forms[0].attendance.focus();
						return false;
					}
				else
					{document.forms[0].result.value=Math.round(14.5 * document.forms[0].attendance.value);}
			}

			if (document.forms[0].roomshape.selectedIndex==2)
			{
				if (document.forms[0].attendance.value>57140)
					{
						alert("Max number of people cannot be more than 57140"); 
						document.forms[0].attendance.focus();
						return false;
					}
				else
					{document.forms[0].result.value=Math.round(17.5 * document.forms[0].attendance.value);}
			}

			if (document.forms[0].roomshape.selectedIndex==3)
			{
				if (document.forms[0].attendance.value>79999)
					{
						alert("Max number of people cannot be more than 79999"); 
						document.forms[0].attendance.focus();
						return false;
					}
				else
					{document.forms[0].result.value=Math.round(12.5 * document.forms[0].attendance.value);}
			}
			if (document.forms[0].roomshape.selectedIndex==4)
			{
				if (document.forms[0].attendance.value>105250)
					{
						alert("Max number of people cannot be more than 105250"); 
						document.forms[0].attendance.focus();
						return false;
					}
				else
					{document.forms[0].result.value=Math.round(9.5 * document.forms[0].attendance.value);}
			}
			if (document.forms[0].roomshape.selectedIndex==5)
			{
				if (document.forms[0].attendance.value>24930)
					{
						alert("Max number of people cannot be more than 24930"); 
						document.forms[0].attendance.focus();
						return false;
					}
				else
					{
						if (document.forms[0].attendance.value > 35)
						{
							alert("Conference Style setup is not recommenced for groups of more than 35 people");
						}
						document.forms[0].result.value=Math.round(40.1 * document.forms[0].attendance.value);
					}
			}
			if (document.forms[0].roomshape.selectedIndex==6)
			{
				if (document.forms[0].attendance.value>26300)
					{
						alert("Max number of people cannot be more than 26300"); 
						document.forms[0].attendance.focus();
						return false;
					}
				else
					{
					if ((document.forms[0].attendance.value < 13) || (document.forms[0].attendance.value > 38))
					{
						alert("Hollow square style setup is recommended for groups between 13 and 38 people");
					}
					document.forms[0].result.value=Math.round(38 * document.forms[0].attendance.value);
					}
			}
		}
		else
		{
				if (document.forms[0].roomshape.selectedIndex==0)
				{
					if (document.forms[0].attendance.value>1052500)
						{
							alert("Max number of people cannot be more than 1052500"); 
							document.forms[0].attendance.focus();
							return false;
						}
					else
						{document.forms[0].result.value=Math.round(9.5 * 0.0929 * document.forms[0].attendance.value);}
				}
				if (document.forms[0].roomshape.selectedIndex==1)
				{
					if (document.forms[0].attendance.value>689500)
						{
							alert("Max number of people cannot be more than 689500"); 
							document.forms[0].attendance.focus();
							return false;
						}
					else
						{document.forms[0].result.value=Math.round(14.5 * 0.0929 * document.forms[0].attendance.value);}
				}

				if (document.forms[0].roomshape.selectedIndex==2)
				{
					if (document.forms[0].attendance.value>571400)
						{
							alert("Max number of people cannot be more than 571400"); 
							document.forms[0].attendance.focus();
							return false;
						}
					else
						{document.forms[0].result.value=Math.round(17.5 * 0.0929 * document.forms[0].attendance.value);}
				}

				if (document.forms[0].roomshape.selectedIndex==3)
				{
					if (document.forms[0].attendance.value>799990)
						{
							alert("Max number of people cannot be more than 799990"); 
							document.forms[0].attendance.focus();
							return false;
						}
					else
						{document.forms[0].result.value=Math.round(12.5 * 0.0929 * document.forms[0].attendance.value);}
				}
				if (document.forms[0].roomshape.selectedIndex==4)
				{
					if (document.forms[0].attendance.value>105250)
						{
							alert("Max number of people cannot be more than 105250"); 
							document.forms[0].attendance.focus();
							return false;
						}
					else
						{document.forms[0].result.value=Math.round(9.5 * 0.0929 * document.forms[0].attendance.value);}
				}
				if (document.forms[0].roomshape.selectedIndex==5)
				{
				if (document.forms[0].attendance.value>249300)
					{
						alert("Max number of people cannot be more than 249300"); 
						document.forms[0].attendance.focus();
						return false;
					}
				else
					{
					if (document.forms[0].attendance.value > 35)
					{
					alert("Conference Style setup is not recommenced for groups of more than 35 people");
					}
					document.forms[0].result.value=Math.round(40.1 * 0.0929 * document.forms[0].attendance.value);
					}
				}
				if (document.forms[0].roomshape.selectedIndex==6)
				{
					if (document.forms[0].attendance.value>263000)
						{
							alert("Max number of people cannot be more than 263000"); 
							document.forms[0].attendance.focus();
							return false;
						}
					else
						{
						if ((document.forms[0].attendance.value < 13) || (document.forms[0].attendance.value > 38))
						{
							alert("Hollow square style setup is recommended for groups between 13 and 38 people");
						}
						document.forms[0].result.value=Math.round(38 * 0.0929 * document.forms[0].attendance.value);
						}
				}
		}
		}
	}
}


function getSearchType()
{
		var searchType;
	
		if(document.getElementById("currentSearchType"))
		{	
			 searchType = document.getElementById("currentSearchType").value;
		}	
		
		if(searchType != "NearAddress")
		{
			searchType = "InCity";		
		}
		return searchType;
		
}

function getRoomElement()
{
	var roomElement;
	
	if(document.getElementById("emlandingpg"))
	{
		roomElement = "searchCriteriaVO.guestRoomCount";
	}
	else
	{
		roomElement = "roomCount";
	}

	return roomElement;
}

//Initializes the vary by night section on page load
var groupSales = {

	EVENTOPTIONS : "eventOptionsRadio",
	SEARCHTYPE_CITY : "InCity",
	SEARCHTYPE_ADDRESS : "NearAddress",
	CURRENT_SEARCH_TYPE : "currentSearchType",
	SEARCH_TYPE : "",
	ROOM_ELEMENT : getRoomElement(),
	ROOMCOUNT : "",
	
// Function that initializes the groupSalesSearchForms.
init : function(){

	if(document.getElementById(groupSales.CURRENT_SEARCH_TYPE))
	{ 	
		groupSales.SEARCH_TYPE = getSearchType();
		disableBrand(groupSales.SEARCH_TYPE);
		initializeGroupSalesSearchForms(groupSales.SEARCH_TYPE);
	}
	//Moving this from calendarUtil. Meetings related logic doesn't make sense in CalendarUtil.
	//For these forms, Section is emsearch.
	$('form.group-sales-search-form :input.calendar-module-fromdate, form.group-sales-search-form :input.calendar-module-todate').bind('change emDateSelectEvent', function(e){
			var searchType = '' ;
			var fieldName = this.id;
			if(fieldName.indexOf("_")){
				var splitValue = fieldName.split("_");
				searchType = splitValue[1] ;
			}
			if($(this).hasClass('calendar-module-fromdate')){
				arrivaldate_onchange('true',searchType) ;
			}else if($(this).hasClass('calendar-module-todate')){
				departuredate_onchange('true',searchType) ;
			}
	});
	
	groupSales.registerGroupSalesEvents(groupSales.SEARCH_TYPE);
	
	var propertyUrlLinks = YAHOO.util.Dom.getElementsByClassName('property-page-uri', 'a');
	
	if (propertyUrlLinks)
	{
		for (i=0 ; i < propertyUrlLinks.length ; i++)
		{
			YAHOO.util.Event.addListener(propertyUrlLinks[i], "click", groupSales.showConfirmDialog); 
		}
	}
	$('.rfpRequest-button .button-disabled').click(function(event){event.preventDefault();});
}, 

showConfirmDialog : function(e) {
	YAHOO.util.Event.preventDefault(e);
	var confirmMsg = document.getElementById("confirmMsg").value;
	var propertyUri = this.href;
	displayAlertMessage(propertyUri, confirmMsg);
},
initializeVaryByNights : function(searchType){
	var form = getFormFromType(searchType);
	
	var sgoSearch = $(form).find(':hidden[name=sgoSearch]').val();
	
	var isVaryByNight  = $(form).find(':hidden[name=varybyNights]').val();
  	      
  	if(isVaryByNight != 'true')
  	{	
		determineSGO(searchType, form);
	}	

},

/*
	Function that registers the event Options radio button on Group sales search pages.
*/


registerGroupSalesEvents : function(searchType){

	var eventOptionsArray;
	var isVaryByNight;
	var showDiv;

	// Since, there are City and Address Search forms, loop through each of them to get the eventOptions
	$('form.group-sales-search-form').each(function(){
		eventOptionsArray = $(this).find(':radio[name='+groupSales.EVENTOPTIONS+']');
		
		if($(eventOptionsArray).length > 0)
		{
			/* 
	 	   		We need to call getFormType() as the searchType gets set to the value that would be submitted 
		  	   	when we come to the splash pg from F&R or Home page.
		  	*/
		  	formSearchType = $(this).find(':hidden[name=formType]');
		  	
		  	if($(formSearchType).length > 0)
		  	{
		  		searchType = $(formSearchType).val();
		  	}
		  	else{
		  		searchType = 'InCity';  	
		  	}
		  	
		  	isVaryByNight = $(this).find(':hidden[name=varybyNights]').val();
		  	// Hide all event option sections 
		  	groupSales.hideEventOptions(searchType);
		  	
		  	/*
	   			When pg refreshed (refresh or "yes" for radio button etc.), we need to display the section that was expanded before the submission
	   			of the form (or refresh). Since all the sections are hidden when each of the radio buttons 
	   			are read, hiding all and then showing the section that was expanded while the form was submitted.
	   		*/
	   		
	   		if(showDiv)
	   		{
	   			groupSales.showSection(this.type, showDiv);
	   		}
	   		
	   		var checkedOption = $(eventOptionsArray).filter(':checked');
	   		if($(checkedOption).length > 0)
	   		{
	   			showDiv = groupSales.createDiv($(checkedOption).val(), searchType);	
	   			groupSales.showSection(this.type, showDiv);  
	   			
	   			if($(checkedOption).val() == 'roomsAndSpace' || $(checkedOption).val() == 'spaceOnly')
	   			{
	   				// default sq.ft, sq.mts etc.
					groupSales.defaultMeetingSpaceSection( $(checkedOption).val(), searchType);	
	   			}
	   			
	   			// On Pg refresh, if the VBN section has already been selected and section expanded					
 				if(isVaryByNight == 'true')
				{
		  			determineSGO(searchType, this);			
		  		}
	   		}
	   		
	   		$(eventOptionsArray).click(groupSales.eventOptionsChanged);	   		
		}
	
	});
	
}, // End registerGroupSalesEvents

/*
	Function to hide event options sections
*/
hideEventOptions : function(searchType)
{
	groupSales.hideSection(this.type, "roomsOnly-"+searchType);
   	groupSales.hideSection(this.type, "roomsAndSpace-"+searchType);
	groupSales.hideSection(this.type, "spaceOnly-"+searchType);
},

// Function to default meeting space value and sq.ft/mts radio buttons on page load
defaultMeetingSpaceSection : function(spaceOption, searchType)
{

	var meetingSpace;
	var sqFt;
	var sqMts;
	
	if(spaceOption == 'roomsAndSpace')
	{
		meetingSpace = document.getElementById("largestMeetingSpace-"+searchType+"-1");
		sqFt = document.getElementById("meetingSpaceFt-"+searchType+"1");
		sqMts = document.getElementById("meetingSpaceMts-"+searchType+"1");
	}
	else if(spaceOption == 'spaceOnly')
	{
		meetingSpace = document.getElementById("largestMeetingSpace-"+searchType+"-2");
		sqFt = document.getElementById("meetingSpaceFt-"+searchType+"2");
		sqMts = document.getElementById("meetingSpaceMts-"+searchType+"2");
	}
	
	if((sqMts) && (sqMts.checked))
	{
		sqMts.checked = true;		
	}
	else
	{
		if(sqFt)
		{
			sqFt.checked = true;		
		}
	}
	
},


/*
	Function to set the value for the 'number of rooms' text box of the event options section 
	of the group sales search pages.
*/

setNumRooms : function(form,numRooms)
{
	if(!isBlank(numRooms))
	{				
		numRooms = formatNumber(numRooms);
		$(form).find(':input[name=searchCriteriaVO.guestRoomCount]').val(numRooms);
	}

},


/*
	Function to set the value for the 'meeting space' text box of the event options section 
	of the group sales search pages.
*/

setMeetingSpace : function(form,meetingSpace)
{
	if(!isBlank(meetingSpace))
	{			
		meetingSpace = formatNumber(meetingSpace);
		$(form).find(':input[name=searchCriteriaVO.sizeLargestMeetingRoom]').val(meetingSpace);
	}
},

// Function shows message if the given number is invalid

showInvalidNumMsg : function(number,invalidRoomsText)
{
	if(!checkWeatherNumber(number))
	{
		alert(invalidRoomsText);
		return false;
	}
	return true;
},


/**
	Function that gets called when any of the event options is changed from the GroupSales search forms.
*/
eventOptionsChanged : function() 
{
	var radioName;
	var toggleDiv;
    var searchType;
    var roomElement;
    var spaceElement;
    var isVaryByNight;
    var varyByNight;
    
    if(document.getElementById("emlandingpg"))
	{
		roomElement = "searchCriteriaVO.guestRoomCount";
		spaceElement = "searchCriteriaVO.sizeLargestMeetingRoom";
	}
	else
	{
		roomElement = "roomCount";
		spaceElement = "largestMeetingSpace";
	}
	$('form.group-sales-search-form').each(function(){
		eventOptionsArray = $(this).find(':radio[name='+groupSales.EVENTOPTIONS+']');
		
		if($(eventOptionsArray).length > 0)
		{
			/* 
	 	   		We need to call getFormType() as the searchType gets set to the value that would be submitted 
		  	   	when we come to the splash pg from F&R or Home page.
		  	*/
		  	formSearchType = $(this).find(':hidden[name=formType]');
		  	
		  	if($(formSearchType).length > 0)
		  	{
		  		searchType = $(formSearchType).val();
		  	}
		  	else{
		  		searchType = 'InCity';  	
		  	}
		  	
		  	isVaryByNight = $(this).find(':hidden[name=varybyNights]').val();
		  	/* 	Call disableBrand, if the brand was disabled on selecting wedding and entering meeting space
				On click of the other event option radio button, the brand wasn't getting enabled. Calling
				disabledBrand(searchType) will fix this issue. 
			*/ 

			if(document.getElementById("marriottBrands-InCity") || document.getElementById("marriottBrands-NearAddress"))
			{			
				disableBrand(searchType);
			}
			$(eventOptionsArray).each(function(){
				toggleDiv = groupSales.createDiv($(this).val(), searchType) ;
				if($(this).attr('checked') == true)
				{ 
					groupSales.showSection(this.type, toggleDiv);
						
					if($(this).val() == 'roomsAndSpace' || $(this).val() == 'spaceOnly') 
					{
						groupSales.defaultMeetingSpaceSection($(this).val(), searchType);	
					}	
				}
				else{
					groupSales.hideSection(this.type, toggleDiv);
				}
			});
			
			/* Clear all existing values for the room count and meeting space text box - Since they were being retained when we 
			click one event Option, click another and again click the one previously clicked. */
			
			var roomcountArray = $(this).find(':input[name='+roomElement+']');
			var meetingSpaceArray = $(this).find(':input[name='+spaceElement+']');
			$(roomcountArray).each(function(){
				$(this).val('');
			});
			
			$(meetingSpaceArray).each(function(){
				$(this).val('');
			});
			
			// On Pg refresh, if the VBN section has already been selected and section expanded					
			if(isVaryByNight)
			{
	  			determineSGO(searchType, this);			
	  		}			
		}
	});
},

// Function to create the div for search pages

createDiv : function(divPrefix, searchType)
{
	return (divPrefix + "-" + searchType) ;
},

// Functions to hide and show div blocks

showSection : function(e, divTag)
{
 	var showTag = document.getElementById(divTag);
	if(showTag)
	{	
		showTag.className = "sgo-roomsandmeetingspace-enable";
	}
},

hideSection : function(e, divTag)
{
	var hideTag = document.getElementById(divTag);
	if(hideTag)
	{	
		hideTag.className = "disable-sgo";		
	}	
},

// Function to get the room count. Called from determineSGO().

getRoomCount : function(form, searchType, numRooms) {
	var checkedEventOptionValue = $(form).find(':input[name=eventOptionsRadio]:checked').val();
 	var roomCountId;
 	var roomCount;
 	
 	if(checkedEventOptionValue == 'roomsOnly')
 	{
 		roomCountId = "roomCount-"+searchType+"-1";
 	}
 	else if(checkedEventOptionValue == 'roomsAndSpace')
 	{
 		roomCountId = "roomCount-"+searchType+"-2";	
 	}
 	
	if(roomCountId == null || roomCountId == '' || roomCountId == 'undefined')
	  {
	  		roomCount = "";
	  }
	  else
	  {		
		  roomCount = $(form).find('#'+roomCountId).val();
	  }	

	return roomCount;
},


setRoomElements : function(roomElements,count)
{
		if($(roomElements).length > 0 )
		{
			$(roomElements).each(function(){
				$(this).val(count);
			});
		}
		return;
},


// Function to Display an alert msg when Government event type is selected for sgo splash and stand alone pgs.

displayGovernmentEventMessage : function(form, eventType) {

	var message = document.getElementById("sgoGovernmentTypeMsg");

	if((message) && (eventType != "undefined" && eventType == "Government"))
	{
		alert(message.value);
	}
	return true;
},

// Function to calculate the meeting space

getMeetingSpace : function(form, searchType)
{
	var checkedEventOptionValue = $(form).find(':input[name=eventOptionsRadio]:checked').val();
 	var meetingSpaceId;
 	var roomSize;
 	
 	if(checkedEventOptionValue == 'roomsAndSpace')
 	{
 		meetingSpaceId = "largestMeetingSpace-"+searchType+"-1";
 	}
 	else if(checkedEventOptionValue == 'spaceOnly')
 	{
 		meetingSpaceId = "largestMeetingSpace-"+searchType+"-2";		
 	}
 	
	if(meetingSpaceId == null || meetingSpaceId == '' || meetingSpaceId == 'undefined')
	{
		roomSize = "";
	}
	else
	{		
		roomSize = $(form).find('#'+meetingSpaceId).val();
	}	
	  
	 return roomSize;
}

}


/**
	This function initializes the search forms of group sales search
	when coming from Find and Reserve page.
	This is called when the page loads.

*/
function initializeGroupSalesSearchForms(searchType){

	var form = getFormFromType(searchType);
	var radioCity = $(":radio#inCity");
	var radioAddress = $(":radio#nearAddress");
	var radioAirport = $(":radio#nearAirport");

	if(searchType == "InCity")
	{	
		displayGroupSalesSearch('InCity');
		if($(":hidden#hwsSearchSgo").val() == "false")
		{
			$(radioCity).attr('checked', true);
		}
	}
	else if(searchType == "NearAddress")
	{
		displayGroupSalesSearch('NearAddress');
		$(radioAddress).attr('checked', true);
	}
	else
	{
		displayGroupSalesSearch('city');
		$(radioCity).attr('checked', true);
	}

}

/**
	This function gets called when user adds the hotel to the shopping cart
*/
function requestList(actionPath)
{
	var rfpListSize = document.getElementById("rfpListSize").value;
	var rfpListerrorMessage = document.getElementById("rfpListerrorMessage").value;
	if (rfpListSize >= 3)
	{
		alert(rfpListerrorMessage);
	}
	else
	{
		window.location.href = actionPath;
	}
}

function disableEditSearchFormFields()
{
	if (document.getElementById("sgoSupportedSiteFlag") != undefined && document.getElementById('gs_edit-search-form').elements["eventType"] != undefined)
	{
		var sgoSupported = document.getElementById("sgoSupportedSiteFlag").value;
		var eventType = document.getElementById('gs_edit-search-form').elements["eventType"].value;
		var divTag = document.getElementById('optional-fields');

		if (eventType != 'Meeting' && sgoSupported != 'true') 
		{
			document.getElementById('gs_edit-search-form').elements['roomCount'].disabled = true;				
			document.getElementById('gs_edit-search-form').elements['roomCount'].value ='';
			document.getElementById('gs_edit-search-form').elements['largestMeetingSpace'].disabled = true;
			document.getElementById('gs_edit-search-form').elements['largestMeetingSpace'].value='';
			document.getElementById('gs_edit-search-form').elements['meetingSpaceUnits'][0].disabled = true;
			document.getElementById('gs_edit-search-form').elements['meetingSpaceUnits'][1].disabled = true;
			document.getElementById("submitButton").disabled=true
			document.getElementById("submitButton").className="submit button-disabled";
			if (divTag != undefined && divTag.className == "enable-fields") {
				divTag.className = "disable-fields";			
			}
		}
		else
		{
			document.getElementById('gs_edit-search-form').elements['roomCount'].disabled = false;				
			document.getElementById('gs_edit-search-form').elements['largestMeetingSpace'].disabled = false;
			document.getElementById('gs_edit-search-form').elements['meetingSpaceUnits'][0].disabled = false;
			document.getElementById('gs_edit-search-form').elements['meetingSpaceUnits'][1].disabled = false;
			document.getElementById("submitButton").disabled=false;
			document.getElementById("submitButton").className="submit";
			if (divTag != undefined && divTag.className == "disable-fields") {
				divTag.className = "enable-fields";			
			}

			
		}
	}
}

var groupSalesEditSearch = {

	 INVALID_ROOMS_MSG : "Please enter a valid number greater than zero for 'Maximum number of sleeping rooms.'",
	 INVALID_SPACE_MSG : "Please enter a valid number greater than zero for 'Largest Meeting Room Needed.'",

validateMiniEditSearch : function()
{
	var form = document.getElementById("gs_edit-search-form");
	var kDate = form.elements["kDate"].value;
	var sgoSupported = form.elements["sgoSupportedSiteFlag"].value;
	var siteId = document.getElementById("siteId").value;
	if (form.elements["fromDate"] != undefined && form.elements["toDate"] != undefined)
	{
		var fromDate = form.elements["fromDate"].value;
		var toDate = form.elements["toDate"].value;
		var roomCount;
		var checkIn = null ;
		var checkOut = null ;
		var dateFormatPattern = $(':hidden[name=dateFormatPattern]').val().toLowerCase();
		if(fromDate != null && fromDate.length > 0){
			checkIn = getDate(fromDate,dateFormatPattern) ;
		}

			if(toDate != null && toDate.length > 0){
				checkOut = getDate(toDate,dateFormatPattern) ;
			}

			var testDate = processDate(kDate);
			var daysDiff = calculateNoOfNights(checkIn, checkOut);
			var fdate = new Date();
			fdate.setDate(fdate.getDate()+3) ;
	}
	if(sgoSupported == "true")
	{	
		roomCount = groupSales.getRoomCount(form,"InCity");
		var spaceCount = groupSales.getMeetingSpace(form,"InCity");
		var numRoomsArray = form.elements['roomCount'];
		var meetingSpaceArray = form.elements['largestMeetingSpace'];
		// Set num rooms and meeting space fields. Since, there are two text boxes each for rooms and space,
		// we need to set the value respective fields.
		groupSales.setRoomElements(numRoomsArray, roomCount);
		groupSales.setRoomElements(meetingSpaceArray, spaceCount);
		return true;		
	}
	else
	{
		// validate UK and DE fields
		var minSpace = form.elements['largestMeetingSpace'].value;
		var minGuest = form.elements['roomCount'].value;
		var eventType = form.elements['searchType'].value;
		roomCount = minGuest;
		if(!isBlank(roomCount)){				
			var numRooms = formatNumber(roomCount);
			form.elements['roomCount'].value = roomCount;
		}
		if(!isBlank(minSpace)){			
			var numRooms = formatNumber(minSpace);
			form.elements['largestMeetingSpace'].value = minSpace;
		}

	}	
},

validateMiniEditSgoFields : function(form) {
	var eventsChecked = false;
	var eventOptionsValue;
	var maxRooms;
	var meetingSpace;
	// Retrieve all the error msgs that are supposed to be displayed from the JSP
	var noEventOptionsMsg = document.getElementById("noEventOptionsMsg");
	var roomsOnlyErrorMsg = document.getElementById("roomsOnlyError");
	var roomsAndSpaceErrorMsg = document.getElementById("roomsAndSpaceError");
	var spaceOnlyErrorMsg = document.getElementById("spaceOnlyError");
	var eventType = form.elements['searchType'].value;
	var eventOptionsArray = form.elements[groupSales.EVENTOPTIONS];
	
	if(eventOptionsArray)
	{
		for(var i=0; i<eventOptionsArray.length;i++)
		{
			/* Check to see if any of the radio buttons has been clicked. 
			If clicked, then validate applicable rooms and space info */
			if(eventOptionsArray[i].checked)
			{
				eventsChecked = true;
				eventOptionsValue = eventOptionsArray[i].value;
				if(eventOptionsValue == 'roomsOnly')
				{
					if(document.getElementById("roomCount-InCity-1"))
					{
						maxRooms = document.getElementById("roomCount-InCity-1").value;
					}	
					if((isBlank(maxRooms)) && (roomsOnlyErrorMsg))
					{
						alert(roomsOnlyErrorMsg.value);						
						return false;											
					}
				}  // End roomsOnly if blank
				else if(eventOptionsValue == 'roomsAndSpace')
				{					
					if(document.getElementById("roomCount-InCity-2")){
						maxRooms = document.getElementById("roomCount-InCity-2").value;
					}
					if(document.getElementById("largestMeetingSpace-InCity-1"))	{
						meetingSpace = document.getElementById("largestMeetingSpace-InCity-1").value;
					}
					if((isBlank(maxRooms) || isBlank(meetingSpace)) && (roomsAndSpaceErrorMsg))	{						
							alert(roomsAndSpaceErrorMsg.value);						
							return false;											
					}
				} // End RoomsAndSpace if blank
				else if(eventOptionsValue == 'spaceOnly')
				{
					if(document.getElementById("largestMeetingSpace-InCity-2"))	{
						meetingSpace = document.getElementById("largestMeetingSpace-InCity-2").value;
					}
					if(isBlank(meetingSpace) && (spaceOnlyErrorMsg)){
						alert(spaceOnlyErrorMsg.value);						
						return false;
					}
				}// End spaceOnly if blank
				
				if((maxRooms) && (!isBlank(maxRooms)))
				{
					// If max rooms is an invalid number, display msg.	
					if(!groupSales.showInvalidNumMsg(maxRooms,groupSalesEditSearch.INVALID_ROOMS_MSG)){
						return false;
					}
				}
				// If space is an invalid number, display msg.		
				if((meetingSpace) && (!isBlank(meetingSpace)))
				{
					if(!groupSales.showInvalidNumMsg(meetingSpace,groupSalesEditSearch.INVALID_SPACE_MSG)){
						return false;
					}
				}							
			} // Enf if eventOptions checked
		} // End for loop close
	} // End top most if
	
	// If no Event options radio button is checked, display error msg.
	if((!eventsChecked) && (noEventOptionsMsg))
	{	
			alert(noEventOptionsMsg.value);
			return false;				
	}
	
	return true;	
},

	displaySearchParameters : function() {
	
		// If mini-edit form on the search results page is present and all the fields
		// for sgo search parameters are marked as "disable-sgo" which means they are 
		// not displaying, then display the search parameters.		
		if(document.getElementById("miniEditFormSGO") || document.getElementById("eventsAndMeetingsFormSGO")) {		
		
			var roomsOnly = document.getElementById("roomCount-InCity-1");
			var meetingSpaceWithRooms = document.getElementById("largestMeetingSpace-InCity-1");
			var roomsWithMeetingSpace = document.getElementById("roomCount-InCity-2");
			var meetingSpaceOnly = document.getElementById("largestMeetingSpace-InCity-2");
						
			if(document.getElementById("roomsAndSpace-InCity").className.match("disable-sgo")
				&& document.getElementById("roomsOnly-InCity").className.match("disable-sgo")
				&& document.getElementById("spaceOnly-InCity").className.match("disable-sgo"))
			{
				if(roomsWithMeetingSpace.value != "" && roomsWithMeetingSpace.value != null && roomsWithMeetingSpace.value != "0"
								&& meetingSpaceWithRooms.value != "" && meetingSpaceWithRooms.value != null && meetingSpaceWithRooms.value != "0") {
					document.getElementById("roomsAndSpace-InCity").className = "sgo-roomsandmeetingspace-enable";
					document.getElementById("eventRoomsAndSpace-InCity").checked = "true";
				
					if(document.getElementById("meetingSpaceFt-InCity2").checked == true) {
						document.getElementById("meetingSpaceFt-InCity1").checked = "true";
					}
					else if(document.getElementById("meetingSpaceMts-InCity2").checked == true) {
						document.getElementById("meetingSpaceMts-InCity1").checked = "true";
					}
				}
				else if(roomsOnly.value != "" && roomsOnly.value != null && roomsOnly.value != "0") {
					document.getElementById("roomsOnly-InCity").className = "sgo-roomsandmeetingspace-enable";
					document.getElementById("eventRoomsOnly-InCity").checked = "true";
				}
				else if(meetingSpaceOnly.value != "" && meetingSpaceOnly.value != null && meetingSpaceOnly.value != "0") {
					document.getElementById("spaceOnly-InCity").className = "sgo-roomsandmeetingspace-enable";
					document.getElementById("eventSpaceOnly-InCity").checked = "true";
				}
			}
		//if performing an sgo search from the events and meeting landing page and have already completed the vary by nights stand alone page
		//the session will not reset the very by nights flag when landing on the hws splash page
		// so we must reset the section
		}else if((document.getElementById("hwsSearchSgo") && document.getElementById("searchType") && document.getElementById("roomsOnly-InCity")
			&& document.getElementById("roomsAndSpace-InCity") && document.getElementById("spaceOnly-InCity"))
			&& (document.getElementById("hwsSearchSgo").value == "true" && document.getElementById("searchType").value == "InCity")
			&& (document.getElementById("roomsOnly-InCity").className.match("disable-sgo")
			&& document.getElementById("roomsAndSpace-InCity").className.match("disable-sgo")
			&& document.getElementById("spaceOnly-InCity").className.match("disable-sgo")))
		{
			document.getElementById("InCityVaryByNightModule").style.display = "none";
			document.getElementById("InCityVaryByNightInclude").style.display = "none";
		}
	}
}

function miniEditSearchParameters()
{
	setVDataCookieFromFormNoSubmit(this.form, vsObjectMap);
	var form = document.getElementById('gs_edit-search-form');
	form.submit();
}
//sends current form data to actionPath
function miniEditMoreOptions(actionPath)
{
	var form = document.getElementById('gs_edit-search-form');
	form.action=actionPath;
	form.submit();
}

function displayAlertMessage(uri, confirmMsg)
{
	result = confirm(confirmMsg);
		
	if(result)
	{		
		window.location = uri;
	}
	else
	{
		return;
	}	
}


addLoadEvent(meetingsLanding.init);
addLoadEvent(groupSales.init);
addLoadEvent(disableEditSearchFormFields);
addLoadEvent(groupSalesEditSearch.displaySearchParameters);