/////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Custom Validators for Booking Module Big : START
/////////////////////////////////////////////////////////////////////////////////////////////////////////////
function validateDestinationCustom(controlName,destId)
{
    var noOfMatchesFound;
    var result = true;
    
    noOfMatchesFound = validateDestination(controlName,destId);
            
    if ((noOfMatchesFound == 0) || (noOfMatchesFound > 1))
    {
        $fn(_endsWith(destId)).value = "";
    }
    
    if (noOfMatchesFound == 0)
    {
        result = false;
    }
    
    return result;
}
//Function To Handle Custom Rule That Value Should not be equal to value in rel of the control-Ashish
function validateDefaultHotelText(hotelNameField)
{
   if($fn(_endsWith(hotelNameField)).value==$fn(_endsWith(hotelNameField)).getAttribute('rel'))
   {
       return false;     
   }
   return true;   
}


function validateDestinationDuplicate(controlName,destId)
{
    var noOfMatchesFound;
    var result = true;
    
    noOfMatchesFound = validateDestination(controlName,destId);
    
    if ((noOfMatchesFound == 0) || (noOfMatchesFound > 1))
    {
        $fn(_endsWith(destId)).value = "";
    }
    
    // If there are multiple destinations found, then 
    // we ask user to choose one destination from the list.
    if(noOfMatchesFound > 1)
    {        
        result = false;
    }
    
    return result;
}

function validateDestination(controlName,destId)
{
    if($fn(_endsWith(destId)).value == "")
    {
        var matchingCityDestinations;
        var totalCities;
        var totalHotels;
        var searchStringAfterExclusion      = getDestinationAfterExclusion($fn(_endsWith(controlName)).value);
        var noOfMatchesFound                = 0;
        var cityNameAfterExclusion;
        var hotelNameAfterExclusion;
        var IsSearchStringToCompare         = false;
        
        // Get the search string replaced with regex mapping attributes to nordi characters.
        // AMS BUG FIX: artf720557
        searchString = getStringAfterReplace(searchStringAfterExclusion);
        
        // Fetch all CityDestinations which are matching with the string 
        // entered by the user. 3rd parameter made as "false" as we are 
        // going to compare the whole string.
        matchingCityDestinations = getMatchingDestinations(nonBookableHotelList, searchString, IsSearchStringToCompare);
    
        // When we get matching CityDestinations then we will further 
        // identiy whether it is matching with CITY or HOTEL
        if (matchingCityDestinations != null)
        {
            totalCities = matchingCityDestinations.length;
        
            // Looping through all the cities
            for (var cityCtr = 0; cityCtr < totalCities; cityCtr++)
            {
                cityNameAfterExclusion = getDestinationAfterExclusion(matchingCityDestinations[cityCtr].name);
                
                // Verifying if the search string matches with the city name
                // if(cityName.toLowerCase() == searchString.toLowerCase())
                
                // BUG FIX: artf711351 | Partial search should not be supported on Search and Refine search.
                // We are also comparing the length of string, as .matches() returns TRUE 
                // when city name startswith the searchString. But we need to see the 
                // exact match between the cityName and searchString.
                if (matchingCityDestinations[cityCtr].matches(searchString, IsSearchStringToCompare) && 
                cityNameAfterExclusion.length == searchStringAfterExclusion.length)
                {
                    $fn(_endsWith(destId)).value = "CITY:" + matchingCityDestinations[cityCtr].ID;
                    
                    //Res2.2.8 | Artifact artf1233484 : Scanweb - Search in Find a Hotel page is not working properly 
                    $fn(_endsWith(controlName)).value = matchingCityDestinations[cityCtr].name;
                    
                    // We are using the counter "noOfMatchesFound", to see if there 
                    // are multiple cities with same name
                    noOfMatchesFound = noOfMatchesFound + 1;
                }
                else
                {
                    // Verifying if the hotels in the cities are matching
                    if(matchingCityDestinations[cityCtr].hotels != null)
                    {
                        // Fetching all hotels available in the city
                        totalHotels = matchingCityDestinations[cityCtr].hotels.length;
                        
                        for(var hotelCtr = 0; hotelCtr < totalHotels; hotelCtr++)
                        {
                            hotelNameAfterExclusion = getDestinationAfterExclusion(matchingCityDestinations[cityCtr].hotels[hotelCtr].name);
                            
                            //if(hotelName.toLowerCase() == searchString.toLowerCase())
                            
                            // BUG FIX: artf711351 | Partial search should not be supported on Search and Refine search.
                            // We are also comparing the length of string, as .matches() returns TRUE 
                            // when hotel name startswith the searchString. But we need to see the 
                            // exact match between the hotelName and searchString.
                            if (matchingCityDestinations[cityCtr].hotels[hotelCtr].matches(searchString, IsSearchStringToCompare) && 
                            hotelNameAfterExclusion.length == searchStringAfterExclusion.length)
                            {
                                $fn(_endsWith(destId)).value = "HOTEL:" + matchingCityDestinations[cityCtr].hotels[hotelCtr].ID;
                                
                                //Res2.2.8 | Artifact artf1233484 : Scanweb - Search in Find a Hotel page is not working properly 
                                $fn(_endsWith(controlName)).value = matchingCityDestinations[cityCtr].hotels[hotelCtr].name;
                                
                                // We are using the counter "noOfMatchesFound", to see if there 
                                // are multiple hotels with same name
                                noOfMatchesFound = noOfMatchesFound + 1;
                            }
                        }
                    }
                }
            }
        }           
    }
    else
    {
        noOfMatchesFound = 1;
    }
    
    return noOfMatchesFound;
}

function validateNoOfNights1To99(value)
{
    if (validateNumeric(value))
    {
        if (value < 1 || value > 99)
        {
            return false;
        }
        else
        {
            return true;
        }
    }
    else
    {
        return false;
    }
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Custom Validators for Booking Module Big : END
/////////////////////////////////////////////////////////////////////////////////////////////////////////////

/////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Common Custom Validators  : START
/////////////////////////////////////////////////////////////////////////////////////////////////////////////
function ValidateDepartureDateGreaterThanArrivalDate(arrivalDate, departureDate)
{    

     var noOfNight = differenceDay(departureDate, arrivalDate);
     if(noOfNight<1 || noOfNight>99)
	 {
	    return false;
	 }
	 else
	 {
	    return true;
	 }

}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Common Custom Validators  : END
/////////////////////////////////////////////////////////////////////////////////////////////////////////////

/////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Custom Validators for EnrollGuestProgram.ascx : START
/////////////////////////////////////////////////////////////////////////////////////////////////////////////
function validateCreditCardExpiry(expiryMonth, expiryYear)
{
    var presentDate     = new Date();
    var presentMonth    = presentDate.getMonth()+1;
    var presentyear     = presentDate.getFullYear();
            
    if(expiryYear == presentyear)
    {
        if(expiryMonth <= presentMonth)
        {   
            return false;
        }   
    }
    
    return true;
}

function validateDateOfBirth(indexPosDD, indexPosMM, indexPosYY)
{
    if (indexPosDD <= 0 || indexPosMM <= 0 || indexPosYY <=0)
        return false
    else
        return true;
}

function validatePhone(areaCode, telephoneNo)
{
    var result = true;
    
    if (Trim(telephoneNo) == "")
    {
        if (validateDropdownWithSeparator(areaCode))
        {
            result = false;
        }
    }
    else
    {
        if (!validateDropdownWithSeparator(areaCode))
        {
            result = false;
        }
        else
        {
            if (!validateNumeric(telephoneNo))
            {
                result = false;
            }
        }
    }
        
    return result;
}

function validatePartnerProgramAcctNo(indexPos, accountNo)
{
    if (validateDropdownSelected(indexPos))
    {
        if(!validateNonEmpty(accountNo))
        {
            return false
        }
    }
    
    return true;
}

function validatePartnerProgram(indexPos, accountNo)
{
    if (validateNonEmpty(accountNo))
    {
        if (!validateDropdownSelected(indexPos))
        {
            return false;
        }
    }
    
    return true;
}

function validatePasswordMatch(password, retypePassword)
{
    if (password != retypePassword)
    {
        return false;
    }
    
    return true;
}

function validateSecurityAnswer(indexPos, securityAnswer)
{
    if (validateDropdownSelected(indexPos))
    {
        if (!validateNonEmpty(securityAnswer))
        {
            return false;
        }
        else
        {
            return true;
        }
    }
    
    
    return true;
}

//Defect Fix - Artifact artf652899(R1.3)
function validateSecurityQuestion(indexPos, securityAnswer)
{
    if (!validateDropdownSelected(indexPos))
    {
        if (validateNonEmpty(securityAnswer))
        {
            return false;
        }
        else
        {
            return true;
        }
    }
    
    
    return true;
}
//Defect Fix - Artifact artf652899(R1.3) ends here

/////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Custom Validators for EnrollGuestProgram.ascx : START
/////////////////////////////////////////////////////////////////////////////////////////////////////////////

/////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Custom Validators for UserBookingContactDetails.ascx : START
/////////////////////////////////////////////////////////////////////////////////////////////////////////////

function ValidateCreditCardNumberForChanges(orginalCardNumber, newCardNumber)
{    
    var result = true;    
    
    if(orginalCardNumber != newCardNumber)
    {
        result = validateNumeric(newCardNumber);
    }
    
    return result;
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Custom Validators for UserBookingContactDetails.ascx : END
/////////////////////////////////////////////////////////////////////////////////////////////////////////////

/////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Generic Custom Validators : START
/////////////////////////////////////////////////////////////////////////////////////////////////////////////

//method called on Tab out of Arrival date text Box and on validateAll method call
//to validate the Arrival date and update Departure date accordingly.
function validateArrivalDate()
{   
    clearDisplayError();
    
    if ((at.value == "") && (! validateDate(at.value))) 
    {
        setDefaultFields("Arrival");
        errorMessagesArray.push(invalidArrivalDate);
        displayClientError(invalidArrivalDate,errorTextClass);
        errorMessagesArray.pop();
        AddClassName(aDiv, "errorText");
    }
    else 
    {   
        //Check date is crossing lower boundary(current date) 
        //and upper boundary(two year from current date) 
        //this method returns true if the validations fails              
        if(validatePastDate(at.value, true)) 
        {
            setDefaultFields("Arrival");
            errorMessagesArray.push(invalidArrivalDate);
            displayClientError(invalidArrivalDate,errorTextClass);
            errorMessagesArray.pop();
            AddClassName(aDiv, "errorText");
		} 
		else 
		{   
            var noOfNight = parseInt(nt.value,10);
           		
			if(noOfNight<1 || noOfNight>99)
			{
				noOfNight =  differenceDay(dt.value,at.value);
				nt.value = noOfNight;                   
			}

			var calculatedDepDate = addDays(at.value,noOfNight);	
			//If the calculated destination date is exceeding upperboundary(2+ from the current)
			//then throw the error
			if(validatePastDate(calculatedDepDate, false)) 
            {
                setDefaultFields("Arrival");
                errorMessagesArray.push(invalidArrivalDate);
                displayClientError(invalidArrivalDate,errorTextClass);
                errorMessagesArray.pop();
                AddClassName(aDiv, "errorText");
                
                noOfNight =  differenceDay(dt.value,at.value);
                nt.value =  noOfNight;
		    } 
		    else
		    {
			    dt.value = calculatedDepDate;			
			}
		}
		
		var arrivalDate = at.value;
		var arrivalDateArray = arrivalDate.split("/");
        ad = parseInt(arrivalDateArray[0],10);
        am = parseInt(arrivalDateArray[1],10);
        ay = parseInt(arrivalDateArray[2],10);
    }        	
}

//method called on Tab out of Departure date text Box and on validateAll method call
//to validate the Departure date and update no of nights accordingly.
function validateDepartureDate()
{	
    clearDisplayError();    
    
	if ((dt.value == "") && (! validateDate(dt.value))) 
	{
        setDefaultFields("Departure");
        errorMessagesArray.push(invalidDepartureDate);
        displayClientError(invalidDepartureDate,errorTextClass);
        errorMessagesArray.pop();
        AddClassName(dDiv, "errorText");
    } 
    else 
    {  
        //Populate other date fields
        if(validatePastDate(dt.value, false)) {
            setDefaultFields("Departure"); 
            errorMessagesArray.push(invalidDepartureDate);
            displayClientError(invalidDepartureDate,errorTextClass);
			
            errorMessagesArray.pop();
            AddClassName(dDiv, "errorText");
        } 
        else if((validateDate(at.value)) && (at.value!="")) 
        {               
            //Code for populating the No of Night
            var noOfNight =differenceDay(dt.value,at.value);
         	if(noOfNight<1 || noOfNight>99)
			{
			    setDefaultFields("Departure"); 
				errorMessagesArray.push(invalidDepartureDate);
				displayClientError(invalidDepartureDate,errorTextClass);
				errorMessagesArray.pop();
				AddClassName(dDiv, "errorText");
			}
			else
			{
				nt.value = noOfNight;                           
			}
        } 
        else 
        {
            setDefaultFields("Departure"); 
            errorMessagesArray.push(invalidDepartureDate);
            displayClientError(invalidDepartureDate,errorTextClass);
            errorMessagesArray.pop();			
            AddClassName(dDiv, "errorText");
        } 
		// Begin : GB | Synchronising the form field value & open calendar
		var departureDate = dt.value;
		var departureDateArray = departureDate.split("/");
        dd = parseInt(departureDateArray[0],10);
        dm = parseInt(departureDateArray[1],10);
        dy = parseInt(departureDateArray[2],10); 
    }              
}

// 	Function to validate ArrivalDate in the page
function validateArrivalDate1() 
{
    displayClientError("noError","");
	   
    RemoveClassName(aDiv1, "errorText");
    RemoveClassName(dDiv1, "errorText");
    if ((at1.value == "") && (! validateDate(at1.value))) 
    {
        errorMessagesArray.push(invalidArrivalDate1);
        displayClientError(invalidArrivalDate1,errorTextClass);
        errorMessagesArray.pop();
        AddClassName(aDiv1, "errorText");
    } 
    else 
    {
		var diffDay = differenceDay(dt1.value,at1.value);
		if(diffDay<1 || diffDay>99)
		{	
		    errorMessagesArray.push(invalidArrivalDate1);
            displayClientError(invalidArrivalDate1,errorTextClass);
            errorMessagesArray.pop();
            AddClassName(aDiv1, "errorText");
		
		}
		var arrivalDate1 = at1.value;
		var arrivalDateArray = arrivalDate1.split("/");
        ad = parseInt(arrivalDateArray[0],10);
        am = parseInt(arrivalDateArray[1],10);
        ay = parseInt(arrivalDateArray[2],10);
    }  

}

// 	Function to validate ArrivalDate in the page
function validateDepartureDate1() 
{	
    displayClientError("noError","");

    RemoveClassName(aDiv1, "errorText");
    RemoveClassName(dDiv1, "errorText");
   
	if ((dt1.value == "") && (! validateDate(dt1.value))) 
	{
        errorMessagesArray.push(invalidDepartureDate1);
        displayClientError(invalidDepartureDate1,errorTextClass);
        errorMessagesArray.pop();
        AddClassName(dDiv1, "errorText");
    } 
    else if ((validateDate(at1.value)) && (at1.value != ""))
    { 
		var diffDay = differenceDay(dt1.value,at1.value);
		if(diffDay<1 || diffDay>99)
		{		
		   errorMessagesArray.push(invalidDepartureDate1);
		   displayClientError(invalidDepartureDate1,errorTextClass);			
		   errorMessagesArray.pop();
		   AddClassName(dDiv1, "errorText");
		}
	
		var departureDate1 = dt1.value;
		var departureDateArray = departureDate1.split("/");
        dd = parseInt(departureDateArray[0],10);
        dm = parseInt(departureDateArray[1],10);
        dy = parseInt(departureDateArray[2],10); 
    }  
}

//method called on Tab out of number of nights text Box to validate 
//the number of nights and update Departure date accordingly.
function validateNoOfNightOnChange()
{	
	resetLabelColor();  
	clearDisplayError();
    if(validateNumeric(nt.value)!= false)
    {
        if(nt.value=="")
        {
            nt.value = differenceDay(dt.value,at.value);
        }       
        else if(parseInt(nt.value,10)==0)
        {
            nt.value = differenceDay(dt.value,at.value);            
			
        }
	    if((validateDate(at.value)) && (at.value!=""))
        {               
            var noOfNight = nt.value;
			if(noOfNight<1 || noOfNight>99)
			{
				dt.value = addDays(at.value,1);
				nt.value = differenceDay(dt.value,at.value); 
			}
	    }
        if(validateDate(at.value)!=false)
        {
            var diff1 = addDays(at.value,parseInt(nt.value,10));
            if(validatePastDate(diff1, false) == false)
            {
                dt.value = diff1;
            }
            else
            {
                nt.value = differenceDay(dt.value,at.value); 
            }
        }
        else if(validateDate(dt.value)!=false)
        {   
            var diff2 = subtractDays(dt.value,parseInt(nt.value,10));
            if(validatePastDate(diff2, true) == false)
            {
                at.value = diff2
            }
            else
            {
                nt.value = differenceDay(dt.value,at.value); 
            }
        }  
    }
    else
    { 
        nt.value = differenceDay(dt.value,at.value);      
    }
}

//This function add a class to a control
function AddClassName(objControl, strClassName)
{   
    var strExistingClassName = objControl["className"];
    var classes = strExistingClassName.split(" ");
    var flagClassAlreadyExists = false;
    // Check if provided class is already there
    for (var clas = 0; clas < classes.length; clas++)
    {
       if(classes[clas] == strClassName)
       {
            flagClassAlreadyExists = true;
            break;
       }
    }
    // If class is not there append the provided class name to the existing
    if(flagClassAlreadyExists == false)
    {
       objControl["className"] = objControl["className"]+ " " + strClassName;
    }
}

//This function remove  a class from a control
function RemoveClassName(objControl, strClassName)
{   
    var strExistingClassName = objControl["className"];
    var classes = strExistingClassName.split(" ");
    var strNewClassName = "";
    // Create a new string with all the existing classes apart from the provided class
    for (var clas = 0; clas < classes.length; clas++)
    {
       if(classes[clas] != strClassName)
       {
            strNewClassName = strNewClassName + " " + classes[clas];
       }
    }
    objControl["className"] = strNewClassName;
}

function clearDisplayError()
{
    displayClientError("noError","");
	//RemoveClassName(aDiv, "errorText");
    //RemoveClassName(dDiv, "errorText");
    
    setLabelCss('lblUserName', "");
    setLabelCss('lblPassword', "");
    setLabelCss('destCont', "");
    setLabelCss('atCont', "");
    setLabelCss('dtCont', "");
    setLabelCss('nnCont', "");
    setLabelCss('spanRegularCode', "");
    setLabelCss('spanNegotiatedCode', "");
    setLabelCss('spanVoucherCode', "");    
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Generic Custom Validators : END
/////////////////////////////////////////////////////////////////////////////////////////////////////////////

/////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Formate Booking Code : Start
/////////////////////////////////////////////////////////////////////////////////////////////////////////////
function formateBookingCode(bookingCode)
{
    bookingCode = bookingCode.replace(/\s+/g,'');
    bookingCode = bookingCode.replace(/-/g, "");
    return bookingCode;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Formate Booking Code : End
/////////////////////////////////////////////////////////////////////////////////////////////////////////////

/*R1.5.3 | Artifact artf871521 : Merge the Booking tabs.
The Automatic switch to corporate tab is no more required so removing the entire function*/
/////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Automatic switch to corporate tab : Start
/////////////////////////////////////////////////////////////////////////////////////////////////////////////
/*function validateDNumberInRegularBooking()
{
    var tabValue                = $fn(_endsWith("sT")).value;
    var cntrlRegularCode        = $fn(_endsWith("txtRegularCode"));
    var cntrlNegotiatedCode     = $fn(_endsWith("txtNegotiatedCode"));
    var selBookingType          = $fn(_endsWith("ddlBookingType"));
    var bookingCode             = Trim(cntrlRegularCode.value);
    var errDisplay              = "";
    var errDiv                  = $fn(_endsWith("clientErrorDiv"));
    var returnVal               = true;
    
    R1.5.3 | Artifact artf871521 : Merge the Booking tabs.*/
    // If "Booking" tab is selected, then we proceed further to check 
    // if a Dnumber format value is entered by the user in special 
    // booking code field.
    /*if (tabValue == "Tab1")
    {
        // Validating if it is a DNumber only when the user has entered 
        // some value in "Special booking code" field, hence "bookingCode.length > 0".
        if(bookingCode.length > 0)
        {
            //R1.4.1 | artf799566 | D-Number Enhancement
            //This method is used to remove the space or hyphen from D-number or L-number.
            bookingCode = formateBookingCode(bookingCode);
            var dNumberTrue = validateDNumber(bookingCode);
            var lNumberTrue = validateLNumber(bookingCode);
            if (dNumberTrue || lNumberTrue)        
            {
                // If it found to be a Dnumber being entered in special 
                // booking code field, then we are changing the tab to 
                // "Corporate rates".
                // When BookingModuleMedium / BookingModuleSmall is loaded 
                // then there is the dropdown available rather than the tabs. 
                // Hence checking if there is dropdown then showing 
                // appropriate option in the dropdown or else changing 
                // the tab in BookingModuleBig.
                if (selBookingType != null)
                {
                    selBookingType.value = 2;                
                }
                else
                {
                    changeActiveTab('aTab2');
                }
                
                // After changing the Tab to "Corporate rates", show 
                // the contents of the associated tab.
                showTabContent("Tab2");
                
                // Displaying appropriate message to the user of switching to "Corporate rates" tab.
                errDisplay                  = errDisplay + "<div class = 'errorText'>";
                if(dNumberTrue)
                {
			        errDisplay                  = errDisplay + $fn(_endsWith("specialCodeToDNumber")).value;
			    }
			    else
			    {
			        errDisplay                  = errDisplay + $fn(_endsWith("specialCodeToTravelAgent")).value;
			    }
			    errDisplay                  = errDisplay + "</div>";
    			
			    errDiv.style.visibility     = isVisible;
		        errDiv.style.display        = "block";
			    errDiv.innerHTML            = errDisplay;
                
                // Fill the DNumber value in D-number field of 
                // "Corporate rates" tab and clearing the 
                // Special booking code field in "Booking" tab.
                cntrlNegotiatedCode.value   = bookingCode;
                cntrlRegularCode.value      = '';
                
                returnVal = false;
            }
            else
            {
                errDiv.style.visibility     = isHidden;
	            errDiv.style.display        = "none";
            }
        }
    }
    
    return returnVal; 
}*/
        
/////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Automatic switch to corporate tab : End
/////////////////////////////////////////////////////////////////////////////////////////////////////////////

/////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Customer Service Contact Us QueryTypeValidation : Start
/////////////////////////////////////////////////////////////////////////////////////////////////////////////

/// R1.4 | CR# 7 | Contact Us
function queryTypeValidation()
{
    var selNatureOfQuery            = $fn(_endsWith("ddlNatureOfQuery"));
    var selHotelList                = $fn(_endsWith("ddlHotelList"));
    
    if (selNatureOfQuery != null && selHotelList != null)
    {
        if ((selNatureOfQuery.selectedIndex == 0) || 
        (selNatureOfQuery.selectedIndex == 1) || 
        (selNatureOfQuery.selectedIndex == 3) ||
        (selNatureOfQuery.selectedIndex == 4) ||
        (selNatureOfQuery.selectedIndex == 5))
        {
            selHotelList.selectedIndex = 0;
            selHotelList.disabled = true;
        }
        else
        {
            selHotelList.disabled = false;
        }
    }
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Customer Service Contact Us QueryTypeValidation : End
/////////////////////////////////////////////////////////////////////////////////////////////////////////////

/////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Custom Validators for Confirm Cancel Booking : START
/////////////////////////////////////////////////////////////////////////////////////////////////////////////
//Method to check if any single room check box is checked for cancellation.
function validateRoomSelectedToCancel()
{
    var noOfRoomsToCancel=0;
    var result = false;
    
    noOfRoomsToCancel = getNoOfRoomsToCancel();
    if (noOfRoomsToCancel > 0)
    {
        result = true;
    }
    return result;
}

//Count the number of room selected for cancellation.
function getNoOfRoomsToCancel()
{
    var roomCount;
    var resultCount=0;
    for(roomCount = 1; roomCount<= 4; roomCount++)
    {
        if($fn(_endsWith("divRoom"+ roomCount)) != null)
        {
            if($fn(_endsWith("Room"+ roomCount + "chkCancel")).checked == true)
            {
                resultCount++;
            }
        }
     }
     return resultCount;
}

//Validate Mobile phone number & mobile phone code if properly entered or not,
//if the SMS confirmation check box is selected.
function validateForRoom(roomCnt)
{    
    var result = true;
    if($fn(_endsWith("divRoom"+ roomCnt)) != null)
    {
        if($fn(_endsWith("Room"+ roomCnt + "chkCancel")).checked == true)
        {
            if($fn(_endsWith("chkSMSRoom"+ roomCnt)).checked == true)
            {
                result = validateDropdownWithSeparator($fn(_endsWith("ddlPhoneCodeRoom"+ roomCnt)).value);
                if(result == true)
                {
                    result = validateNonEmpty($fn(_endsWith("txtMobileNumberRoom"+ roomCnt)).value);
                }
                if(result == true)
                {
                    result = validateAlphanumeric($fn(_endsWith("txtMobileNumberRoom"+ roomCnt)).value);
                }
            }
        }
    }
    return result;

}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Custom Validators for Confirm Cancel Booking : START
/////////////////////////////////////////////////////////////////////////////////////////////////////////////


/////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Selecting phone code based on country code : Start
/////////////////////////////////////////////////////////////////////////////////////////////////////////////

function selectPhoneCode(countryCodeID,mobileNumberID)
{ 
    //RK: Reservation 2.0 | modified the input parameters as same method is used even for enrollment
//    var currentCountryCodeObject = eval($fn(_endsWith(("RoomInformation" + roomNumber + "_ddlCountry"))));
//    var currentMobileNumberObject = eval($fn(_endsWith(("RoomInformation" + roomNumber + "_ddlMobileNumber"))));
    
    var currentCountryCodeObject = eval($fn(_endsWith(countryCodeID)));
    var currentMobileNumberObject = eval($fn(_endsWith(mobileNumberID)));
    
    var currentcountryCode; var currentmobileCode;
    
    if( currentCountryCodeObject != null)
    {
     currentcountryCode = currentCountryCodeObject.value; 
     currentmobileCode = currentMobileNumberObject; 
     }
    var phoneCtr        = 0;
    var matchingFound   = false;
    
    // Verifying if all country codes and phone codes are loaded onto the collection "phoneCodesWithCountry"
    if(phoneCodesWithCountry != null)
    {
        // Looping through each item in the collection "phoneCodesWithCountry", and matching if the country 
        // selected in the drop down with each item int he collection "phoneCodesWithCountry".
        for(var countryCtr = 0; countryCtr < phoneCodesWithCountry.phoneCodes.length; countryCtr++)
        {
            if((currentcountryCode != null) && (phoneCodesWithCountry.phoneCodes[countryCtr].countryCode == currentcountryCode))
            {
               //alert(currentcountryCode);
               //alert(phoneCodesWithCountry.phoneCodes[countryCtr].countryCode);
                for(phoneCtr = 0; phoneCtr < currentmobileCode.options.length; phoneCtr++)
                {
                    if(currentmobileCode.options[phoneCtr].value == phoneCodesWithCountry.phoneCodes[countryCtr].phoneCode)
                    {   
                        // Once the matching phone code found, further looping should stop.
                       // alert(currentmobileCode.selectedIndex)
                        currentmobileCode.selectedIndex = phoneCtr;
                        matchingFound = true;
                        break;
                    }
                }
                
                // Once the matching selected country code found, further looping should stop.
                break;
            }

        }
        
        if (!matchingFound)
        {
            // When there is no any matching phone code found for the chosen country, 
            // default option should be selected in the phone code drop down.
            currentmobileCode.selectedIndex = 0;
        }
          

    }
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Selecting phone code based on country code : End
/////////////////////////////////////////////////////////////////////////////////////////////////////////////

/////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Custom Validators for Booking Dettails : START
/////////////////////////////////////////////////////////////////////////////////////////////////////////////

// This method will check whether nametobecomparedwith is equal to nameone or nametwo or namethree
function CompareNames(nametobecomparedwith, nameone, nametwo, namethree)
{
    var result = true;
    if(nametobecomparedwith != null)
    {
        if (    (nameone != null && nametobecomparedwith == nameone ) 
             || (nametwo != null && nametobecomparedwith == nametwo )
             || (namethree != null && nametobecomparedwith == namethree ))
        {
            result = false;
        } 
    }
    return result;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Custom Validators for Booking Dettails : START
/////////////////////////////////////////////////////////////////////////////////////////////////////////////

/////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Custom Validators for Campaign Landing Page : START
/////////////////////////////////////////////////////////////////////////////////////////////////////////////
function ValidateCampaignCode(promoCodeEnteredByuser, promoCodeAssociatedToPage)
{
    var result = true;
    
    if (Trim(promoCodeEnteredByuser.toLowerCase()) != Trim(promoCodeAssociatedToPage.toLowerCase()))
    {
        result = false;
    }
    
    return result;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Custom Validators for Campaign Landing Page : END
/////////////////////////////////////////////////////////////////////////////////////////////////////////////

/////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Custom Validators for Kids Page : START
/////////////////////////////////////////////////////////////////////////////////////////////////////////////

/**********************************************************************
Collect the choosed value and stores in the hidden field.

This function will be called while proceeding to the next 
screen after seleting the bed type preferences for all children.

The purpose is to collect the bet type preference chosen for 
each kid for booking kids and modify booking kids pages.
***********************************************************************/
function collectSelectedAccomodationFromUI()
{    
    var accomodationString  = "";
    var maxChild            = parseInt($fn(_endsWith("noOfChildrenHidden")).value);
    
    // Loop through age drop down of each kid and collect the radio option chosen.
    // Then store all the bed type preferences for all children in the form of a 
    // concatenated string and store it in the hidden field "childrenInfoHidden".
    for (var childCount = 0; childCount < maxChild; childCount++)
    {
        var allSelect       = $fn(_endsWith("DropDown" + childCount));
        var allRadio        = document.getElementsByName("RadioButtonRadioDiv" + childCount);
        
        // Loop through each radio option buttons nd checking if it is selected.
        for (var radioCount = 0; radioCount < allRadio.length; radioCount++)
        {
            if (allRadio[radioCount].checked)
            {
                accomodationString += allSelect.value + ',' + allRadio[radioCount].nextSibling.nodeValue + '|';
                break;
            }
        }
    }
    
    // Storing the concatenated bed type preference of all children in the hidden field.
    $fn(_endsWith("childrenInfoHidden")).value = accomodationString;
    
    return true;
}

/**********************************************************************
This gets executed each time the age drop down of each child is changed.

Based on the age chosen in the age drop down, associated bed type 
preferences will be diplayed in the form of radio options.

User can choose any one of the radio option for each child.
***********************************************************************/
function GenerateRadioStr(radioDiv, dropDownName)
{
    var radioString         = "";
    var radioDivObj         = $fn(radioDiv);    
    var dropNameObj         = $fn(dropDownName);
    
    radioDivObj.innerHTML   = "";
    
    if (dropNameObj.value != "Default")
    {
        // Fetches the allowed bed types for an age group for each child.
        var bedTypes        = GetBedTypes(dropNameObj.value);
        
        // Loop through each bet type preference and generate a HTML radio option string.
        for (var bedCount=0; bedCount < bedTypes.length; bedCount++)
        {
            radioString += '<span><input id="RadioButton' + radioDiv + '"type = radio name = "RadioButton' + radioDiv + '" value = "' + bedTypes[bedCount] + '" onclick = CheckforDuplicates()>';
            radioString += bedTypes[bedCount];
            radioString += '</input></span>'
        }
        
        // The concatenated HTML radio option string is assigned to DIV, 
        // hence gets displayed beside the age drop down for each child.
        radioDivObj.innerHTML = radioString;
    }
}

/**********************************************************************
AMS Artifact :artf964810, Prod Patch R 1.6.2 -This method is used to check whether the Radio Buttons are visible or not when 
the Drop Down have selected value other than default i.e Select Age.
This validation is mainly to cope the Back Button issue adding an extra level
of Validation.
***********************************************************************/
function CheckforRadioButtonVisiblity()
{

var isError=0;
var flag=0;

 var maxChild = parseInt($fn(_endsWith("noOfChildrenHidden")).value);
 
 for(var childCount = 0;childCount<maxChild;childCount++)
 {
        var allSelect       = $fn(_endsWith("DropDown" + childCount));
        var allRadio        = document.getElementsByName("RadioButtonRadioDiv" + childCount);
        
        
   var dropdownIndex = allSelect.selectedIndex;
   var dropdownValue = allSelect[dropdownIndex].value;
   if(dropdownValue!="Select Age")
   {
   
      if(allRadio.length ==0)
      {
     
      GenerateRadioStr("RadioDiv" + childCount,"DropDown" + childCount);
      isError=1;
     
      }
   
   }

 }

return isError;

}

/**********************************************************************
This method returns an array of bed types for the age selected 
for each child in the age drop down in booking kids and 
modify booking kids pages.
***********************************************************************/
function GetBedTypes(selectedAge)
{
    var criteria        = $fn(_endsWith("childrenCriteriaHidden")).value;
    var eachCriteria    = criteria.split(',');
    
    for (var index = 0; index < eachCriteria.length; index++)
    {
        var bedEntity   = eachCriteria[index].split('|');
        var ages        = bedEntity[0].split('-');
        var bedTypes    = new Array();
        
        if ((parseInt(selectedAge) >= parseInt(ages[0])) && (parseInt(selectedAge) <= parseInt(ages[1])))
        {
            var bed     = bedEntity[1].split('_');
            
            for (var count=0; count < bed.length; count++)
            {
                bedTypes.push(bed[count]);
            }
            
            // Return the collection of selected bed types for the chosen age in an array.
            return bedTypes;
        }
    }
}

/**********************************************************************
This is called each time any of the radio button is selected for 
the bed type preferences for each child.

This will return with an error message if the total no. of CIPB selected 
exceeds the total no. of adults.
***********************************************************************/
function CheckforDuplicates()
{
    //This needs to be refactored
    var CIPBCount           = 0;
    var isCIPBErrorFlag     = 0;
    var adults              = parseInt($fn(_endsWith("noOfAdults")).value);        
    var maxChild            = parseInt($fn(_endsWith("noOfChildrenHidden")).value);
    var CIPBstr             = $fn(_endsWith("CIPBString")).value;
    
    $fn(_endsWith("kidsErrorDiv")).innerHTML    = "";
    $fn(_endsWith("kidsErrorDiv")).style.display = "none";
    
    for (var childCount = 0; childCount < maxChild; childCount++)
    {
        var allRadio = document.getElementsByName("RadioButtonRadioDiv" + childCount);
        
        for (var radioCount = 0; radioCount < allRadio.length; radioCount++)
        {
            if ((allRadio[radioCount].checked) && (allRadio[radioCount].value == CIPBstr))
            {
                CIPBCount++;
                
                if (CIPBCount > adults)
                {
                    // Shows the error message.
                    ShowCIPBError();
                    
                    isCIPBErrorFlag = 1;
                    break;
                }
            }
        }
    }
    
    return isCIPBErrorFlag;
 }
 
 /********************************************************************************************
AMS Artifact :artf964810 ,Prod Patch R 1.6.2 - This shows the error message when the Drop Down has selected value other than
default and the radio buttons do not appear.This would prompt the user to select the radio buttons.
**********************************************************************************************/
  function ShowBedtypeError()
 {
 var errDisplayStart     = "";
 var errDisplayEnd       = "";
            errDisplayStart     = errDisplayStart + "<!-- BEGIN: Conditional Error Div with Horizontal-line -->";
			errDisplayStart     = errDisplayStart + "<div id='errorReport' class='formGroupError'>";
			errDisplayStart     = errDisplayStart + "<!-- Error Message -->";
			errDisplayStart     = errDisplayStart + "<div class='redAlertIcon'>";
			errDisplayStart     = errDisplayStart + $fn(errMsgTitle).value;
			errDisplayStart     = errDisplayStart + "</div>";
			errDisplayStart     = errDisplayStart + "<ul class='circleList'>";
			
			errDisplayEnd       = "</ul><!-- Error Message --></div>";
			
    
    var div                 = $fn(_endsWith("kidsErrorDiv"));
    
    div.innerHTML           = errDisplayStart + $fn(_endsWith("InvalidBedType")).value+ errDisplayEnd;
    div.style.visibility    = isVisible;
	div.style.display       = "block";
 }
/**********************************************************************
This shows the error message on booking kids and modify booking kids pages 
if total no of CIPB exceeds total no of adults.
***********************************************************************/
 function ShowCIPBError()
 {
    var errorString         = "<div id = 'errorReport' class = 'formGroupError'>";
    errorString             += "<div class='redAlertIcon'>";
    errorString             += $fn(_endsWith("errMessage")).value;
    errorString             += "</div></div>";
    
    var div                 = $fn(_endsWith("kidsErrorDiv"));
    
    div.innerHTML           = errorString;
    div.style.visibility    = isVisible;
	div.style.display       = "block";
 }
/////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Custom Validators for Kids Page : END
/////////////////////////////////////////////////////////////////////////////////////////////////////////////

/////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Custom Validators for Missing Points : START
/////////////////////////////////////////////////////////////////////////////////////////////////////////////
function StaysForMissingPoint()
{
    this.stays = new Array();    
}

// Verifies if the new stay added is already exisitng in the collection.
StaysForMissingPoint.prototype.isDuplicate = function(newStay)
{
    var eachStay        = null;
    var duplicateFound  = false;
    var dateArray       = null;
    
    dateArray               = newStay.arrivalDate.split("/");
    var newStayArrival      = new Date(dateArray[2], dateArray[1] - 1, dateArray[0]);
    
    dateArray               = newStay.departureDate.split("/");
    var newStayDeparture    = new Date(dateArray[2], dateArray[1] - 1, dateArray[0]);
        
    for(ctr = 0;ctr < this.stays.length; ctr++)
    {
        eachStay                = this.stays[ctr];
        
        dateArray               = eachStay.arrivalDate.split("/");
        var eachStayArrival     = new Date(dateArray[2], dateArray[1] - 1, dateArray[0]);
        
        dateArray               = eachStay.departureDate.split("/");
        var eachStayDeparture   = new Date(dateArray[2], dateArray[1] - 1, dateArray[0]);
        
        // If the arrival and departure dates are same then, it should not allow to add stay.
        if (
            (newStayArrival >= eachStayArrival && newStayArrival < eachStayDeparture) ||
            (newStayDeparture > eachStayArrival && newStayDeparture <= eachStayDeparture) ||
            (newStayArrival < eachStayArrival && newStayDeparture > eachStayDeparture)
           )
            {
                duplicateFound = true;
            }
    }
    
    return duplicateFound;
}

// Add the new stay tot he collection.
StaysForMissingPoint.prototype.addStay = function(newStay)
{
    this.stays.push(newStay);    
}

// Delete a stay from the collection which is marked to delete. 
StaysForMissingPoint.prototype.deleteStay = function(stayRowNoToRemove)
{
    this.stays.splice(stayRowNoToRemove, 1);
}

// This will returns all stays which are already added to the collection in the form of a single string.
StaysForMissingPoint.prototype.getStaysInString = function()
{
    var eachStay = null;
    var totalStaysInString = "";
    
    for(ctr = 0;ctr < this.stays.length; ctr++)
    {
        eachStay = this.stays[ctr];
        totalStaysInString += eachStay.bookingNo + ",";
        totalStaysInString += eachStay.arrivalDate + ",";
        totalStaysInString += eachStay.departureDate + ",";
        totalStaysInString += eachStay.city + ",";
        totalStaysInString += eachStay.hotel + ",%";
    } 
    
    return totalStaysInString;
}

// Object to hold the attributes of each stay.
function MissingPointStay(bookingNo, arrivalDate, departureDate, city, hotel)
{
    this.bookingNo      = bookingNo;
    this.arrivalDate    = arrivalDate;
    this.departureDate  = departureDate;
    this.city           = city;
    this.hotel          = hotel;
}

function ValidateForDuplicateStays(bookingNum, arrivalDt, departureDt, city, hotel)
{    
    var newStay            = new MissingPointStay(bookingNum, arrivalDt, departureDt, city, hotel);
    
    return !staysForMissingPoint.isDuplicate(newStay);
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Custom Validators for Missing Points : END
/////////////////////////////////////////////////////////////////////////////////////////////////////////////
//Vrushali : Defect fix for bedtypes not getting populated, the function IsDestinationInBookableHotelList must take tabvalue as parameter.
function IsDestinationInBookableHotelList(tabValue)
{
    var bookable = masterCityList;
    var flag = false;
    if(null != bookable)
    {
    // To fix Defect No 439162 - Bhavya - pick the hotel name from the hotelname textbox of the respective accordian in home page.
        var hotelName = "";
        switch(tabValue)
        {            
            case "Tab1":
                hotelName = $fn(_endsWith('txtHotelName')).value;  
                break;
            case "Tab2":
                hotelName = $fn(_endsWith('txtHotelNameBNC')).value;  
                break;
            case "Tab3":
                hotelName = $fn(_endsWith('txtHotelNameRewardNights')).value;  
                break;
        }      
        //var hotelName = $fn(_endsWith('txtHotelName')).value; 
        for(var cityCount=0;cityCount<bookable.length;cityCount++)
        {
            if(bookable[cityCount].name.toUpperCase() == hotelName.toUpperCase())
            {
                flag = true;
                break;
            }
            var aHotels = bookable[cityCount].hotels;
            if(null != aHotels)
            {
                for(var hotelCount = 0; hotelCount<aHotels.length;hotelCount++)
                {
                    if(hotelName.toUpperCase() == aHotels[hotelCount].name.toUpperCase())
                    {
                        flag = true;
                        break;
                    }
                }
            }
            if(flag == true)
            {
                break;
            }
        }
    }
    return flag;
}

function validatePasswordForDollarSign(password)
{
    var dollorPosition = password.indexOf('$');
    if (dollorPosition != -1)
    {
        return false;
    }
    else
    {
        return true;
    }
}

function populateDropDown(age)
{    
    var bedTypes        = GetBedTypes(age);
    var optionString         = "";
    if(null != bedTypes)
    {
        // Loop through each bet type preference and generate a HTML radio option string.
        for (var bedCount=0; bedCount < bedTypes.length; bedCount++)
        {
            optionString += '<option value="'+ bedTypes[bedCount] +'">'+ bedTypes[bedCount] +'</option>';
        }
    }
    return optionString;
}


function performValidationForChildAge()
{
    var noOfChildPerNewRoom;
    var errorOccured = false;  
    var newRoomObject = $fn(_endsWith('ddlChildPerNewRoom'));
    var errormsg ; 

    if(newRoomObject != null)
    {
        noOfChildPerNewRoom = parseInt($fn(_endsWith('ddlChildPerNewRoom')).value);

        if(noOfChildPerNewRoom != null && noOfChildPerNewRoom > 0)
        {
              var CIPBCount           = 0;
              var AdultsCount=$fn(_endsWith("ddlAdultsPerNewRoom")).value;
              for(var i=1; i <= noOfChildPerNewRoom; i++)
              {
                    var selectDropDownObject = $fn(_endsWith("childAgeforNewRoomChild"+ i));
                    //RK: Reservation 2.0 | Check for Not a Number instead of text
                    if(isNaN(selectDropDownObject.value))
                    {
                      $(selectDropDownObject).addClass('mandatory');
                      errorOccured = true;
                      errormsg = $fn(_endsWith('InvalidKidsAge')).value; 
                      continue;
                    }
                    else
                    {
                        $(selectDropDownObject).removeClass('mandatory');
                    }
                    //RK: Added validation for the bedtype
                    if ($fn(_endsWith("bedTypeforNewRoomChild"+i)).value == $fn(_endsWith('childInAdultsBedType')).value)
                    {
                       CIPBCount++;                
                       if (CIPBCount > AdultsCount)
                       {
                         // Shows the error message.
                         errorOccured = true;
                         errormsg=$fn(_endsWith('childInAdultBedandAdultCountError')).value;     
                         continue;
                       }
                    }
                }
          }
        if(errorOccured)
        {
          var errorDiv = $fn(_endsWith('RegShoppingCartClientErrorDiv'));
          errorDiv.innerHTML = "<div id='errorReport' class='formGroupError'><div class='redAlertIcon'>"+ errormsg +"</div></div>";
          //errorDiv.style.visibility     = true;
          errorDiv.style.display        = "block";
          return false;
        }
     }
}


