// Js for search results 

var useAjax = 0;

	function setDeparturePoint(airport){
		if(isThomascook()){
			if(!isUndefined(airport)){
				var departurePoints = getDeparturePoints();
				if(!isUndefined(departurePoints)){
					var departurePointItems = departurePoints.options;
					var departurePointSelected = false;
					for(var i = 0; i < departurePointItems.length; i++){
						if(!isUndefined(departurePointItems[i].text)){
							if(departurePointItems[i].value.toLowerCase().indexOf(airport.toLowerCase()) != -1){
								departurePoints.selectedIndex = i;
								departurePointSelected = true;
								break;
							}
						}
					}
					if(!departurePointSelected) setDefaultDeparturePoint();
					
				}
			} else {
				setDefaultDeparturePoint();
			}
		}
	}
	
	function setDefaultDeparturePoint(){
		var departurePoints = getDeparturePoints();
		if(!isUndefined(departurePoints)){
			var departurePointItems = departurePoints.options;
			for(var i = 0; i < departurePointItems.length; i++){
				if(!isUndefined(departurePointItems[i].text)){
					if(departurePointItems[i].text.toLowerCase().indexOf("london gatwick") != -1){
						departurePoints.selectedIndex = i;
						break;
					}
				}
			}
		}
	}
	
	function removeAnyDeparturePoints(){
		if(isThomascook()){
			var departurePoints = getDeparturePoints();
			if(!isUndefined(departurePoints)){
				var departurePointItems = departurePoints.options;
				for(var i = 0; i < departurePointItems.length; i++){
					if(!isUndefined(departurePointItems[i].text)){
						if(departurePointItems[i].text.toLowerCase().indexOf("any ") != -1){
							departurePoints.remove(i);
							--i;
						}
					}
				}
			}
		}
	}	
	
	
	
	
	function sortDepartureOptions(){
		if(isThomascook()){
			var lb = getDeparturePoints();
			if(!isUndefined(lb)){
				arrTexts = new Array();
				arrValues = new Array();
				arrOldTexts = new Array();

				for(i=0; i<lb.length; i++){
					arrTexts[i] = lb.options[i].text;
					arrValues[i] = lb.options[i].value;
					arrOldTexts[i] = lb.options[i].text;
				}

				arrTexts.sort();

				for(i=0; i<lb.length; i++){
					lb.options[i].text = arrTexts[i];
					for(j=0; j<lb.length; j++){
						if (arrTexts[i] == arrOldTexts[j]){
							lb.options[i].value = arrValues[j];
							j = lb.length;
						}
					}
				}
			}
		}
	}
	
	
	
	function isThomascook(){
		var url = window.location;
		
		if(!isUndefined(url)) {
			if(url.host.indexOf("thomascook.com") != -1 || url.host.indexOf("tc.com") != -1) return true;
		}
		return false;
	}
	function getDeparturePoints(){
		return document.getElementById('departureSelect');
	}
	
	function getDefaultDeparturePoint(){
		var c_name = "searchCookie"
		if (document.cookie.length>0){
			c_start=document.cookie.indexOf(c_name + "=");
			if (c_start!=-1){
				c_start=c_start + c_name.length+1;
				c_end=document.cookie.indexOf(";",c_start);
				if (c_end==-1) c_end=document.cookie.length;
				return getDepartureFromCookieString(unescape(document.cookie.substring(c_start,c_end)));
			}
	  	}
	  	return null;
	}
	
	function getDepartureFromCookieString(cookieString){
		if(!isUndefined(cookieString)){
			var splitCookie = cookieString.split(":");
			if(!isUndefined(splitCookie) && splitCookie.length > 4){
				return splitCookie[3];
			}
		}
	}
	

	function isUndefined(elem){
		if(typeof(elem) !== 'undefined' && elem != null) {
			return false;
		} else {
			return true;
		}
	}




removeAnyDeparturePoints();
sortDepartureOptions();
setDeparturePoint(getDefaultDeparturePoint());

// Javascript function called on change of propositions drop-down,
	// to populate profile-dependent destinations.
    function populateDestinationDropDown() {
        var profile = dwr.util.getValue("propositionSelect");
        AjaxSearchTools.populateDestinations(profile, updateDestinations);
        AjaxSearchTools.populateDefaultDestination(profile, updateDefaultDest);
        }


	// Refreshing destinations drop-down
    function updateDestinations(data) {
    	var profile = dwr.util.getValue("propositionSelect");
        dwr.util.removeAllOptions("destinationSelect");
        dwr.util.addOptions("destinationSelect", data);
        var destination = dwr.util.getValue("destinationSelect");
        AjaxSearchTools.populateResorts(destination, profile, updateResorts);
	AjaxSearchTools.populateDepartures(destination, profile, updateDepartures);     
	// This line needs to be commented again if we see 2 appearing in the drop down
		AjaxSearchTools.populateDefaultDeparture(destination, updateDefaultDept);
    }
      // Setting default destination in drop-down
    function updateDefaultDest(data) {
       document.getElementById('destinationSelect').value = data;
     }
       // Setting default departure in drop-down
    function updateDefaultDept(data) {
       if (data == '') {
		dwr.util.addOptions("departureSelect", data);
		} else {
			document.getElementById('departureSelect').value = data;
		}
     }
       // Setting default inputnights in drop-down
    function updateDefaultNights(data) {
       document.getElementById('inputnights').value = data;
     }
    
	// Javascript function called on change of propositions drop-down,
	// to populate profile-dependent durations.
   function populateDurationDropDown() {
	    var profile = dwr.util.getValue("propositionSelect");
        AjaxSearchTools.populateDurations(profile, updateDurations);
        }

	//Refreshing durations drop-down
   function updateDurations(data) {
	    var profile = dwr.util.getValue("propositionSelect");
        dwr.util.removeAllOptions("inputnights");
        dwr.util.addOptions("inputnights", data);
        AjaxSearchTools.populateDefaultDuration(profile, updateDefaultNights);
        }

// Javascript function called on change of propositions drop-down,
  // to populate profile-dependent departure date.
	function populateDepartureDate(depDateID) {
		  var profile = dwr.util.getValue("propositionSelect");
		  var profile = dwr.util.getValue("propositionSelect");
		  var depDate = document.getElementById('departureDate').value;
		  var holidayType = document.getElementById('propositionSelect');
		  if(holidayType.options[holidayType.selectedIndex].text == "Snow holidays"){
			   populateSnowDepDate();
		  }else{
			  AjaxSearchTools.populateDepDate(profile,depDate, updateDepartureDate);
		  }
	   }

// setting departure date
   function updateDepartureDate(data){
	   arrDateTokens = data.split("-");
	   if(arrDateTokens.length > 0)
	       document.getElementById('defaultDay').innerHTML = arrDateTokens[1];
		   document.getElementById('departureDate').value = arrDateTokens[0];
   }
   
   function refresher(searchPanelType){
   	if(searchPanelType != 'extras'){
   		window.location.href = unescape(window.location.pathname) + "?passedSearchPanelTypeUrl="+searchPanelType;
   	} else {
   		parent.location.replace('http://tcs4agents.thomascook.com/ge')
   	}
   }


// For Budgets

 // Setting default budgets in drop-down
    function updateDefaultBudgets(data) {		
       document.getElementById('inputbudget').value = data;		
     }
    
	// Javascript function called on change of propositions drop-down,
	// to populate profile-dependent budgets.
   function populateBudgetDropDown(tourOpsName) {
        var profile = dwr.util.getValue("propositionSelect");
        AjaxSearchTools.populateBudgets(profile,tourOpsName, updateBudgets);
    }

	//Refreshing budgets drop-down
   function updateBudgets(data) {
	    var profile = dwr.util.getValue("propositionSelect");
        dwr.util.removeAllOptions("inputbudget");
        dwr.util.addOptions("inputbudget", data);
		//making another async call to server
		AjaxSearchTools.populateDefaultBudget(profile, updateDefaultBudgets);
   }


		//For Board basis
 // Setting default updateDefaultBoardBasis in drop-down
    function updateDefaultBoardBasis(data) {
       document.getElementById('inputboard').value = data;
     }
    
	// Javascript function called on change of propositions drop-down,
	// to populate profile-dependent updateBoardBasis.
   function populateBBDropDown() {
        var profile = dwr.util.getValue("propositionSelect");
        AjaxSearchTools.populateBoardBasis(profile, updateBoardBasis);
        }

	//Refreshing inputboard drop-down
   function updateBoardBasis(data) {
	   var profile = dwr.util.getValue("propositionSelect");
        dwr.util.removeAllOptions("inputboard");
        dwr.util.addOptions("inputboard", data);
        AjaxSearchTools.populateDefaultBB(profile, updateDefaultBoardBasis);
        }

// For star rating

 // Setting default updateDefaultBoardBasis in drop-down
    function updateDefaultStarRating(data) {
       document.getElementById('inputstarrating').value = data;
     }
    
	// Javascript function called on change of propositions drop-down,
	// to populate profile-dependent updateBoardBasis.
   function populateStarRatingDropDown() {
        var profile = dwr.util.getValue("propositionSelect");
        AjaxSearchTools.populateStarRating(profile, updateStarRating);
        }

	//Refreshing inputboard drop-down
   function updateStarRating(data) {
	   var profile = dwr.util.getValue("propositionSelect");
        dwr.util.removeAllOptions("inputstarrating");
        dwr.util.addOptions("inputstarrating", data);
		AjaxSearchTools.populateDefaultStarRating(profile, updateDefaultStarRating);
        }

	// Javascript function called on change of destinations drop-down,
	// to populate destination-dependent resorts.
    function onDestinationChange() {
    	var proposition = dwr.util.getValue("propositionSelect");
        var destination = dwr.util.getValue("destinationSelect");
       // alert("destination -"+destination);
        AjaxSearchTools.populateResorts(destination, proposition, updateResorts);
        AjaxSearchTools.populateDepartures(destination, proposition, updateDepartures);
    	// This line needs to be commented again if we see 2 appearing in the drop down
        AjaxSearchTools.populateDefaultDeparture(destination, updateDefaultDept);
        }

	// Refreshing resorts drop-down
    function updateResorts(data) {
        dwr.util.removeAllOptions("resortSelect");
        dwr.util.addOptions("resortSelect", data);
        }

	//Refreshing departures drop-down
     function updateDepartures(data) {  
		     dwr.util.removeAllOptions("departureSelect"); 
		     dwr.util.addOptions("departureSelect", data);
		     	removeAnyDeparturePoints();
		     	sortDepartureOptions();
		     	setDeparturePoint(getDefaultDeparturePoint());
			
     }
     
     
      function onReviewDestinationChange() { 
        var tourOps = dwr.util.getValue("tourOpsSelect");
        var destination = dwr.util.getValue("destinationSelect");
        AjaxSearchTools.populateReviewResorts(destination,tourOps, updateReviewResorts);
      }
      
	function onMbcDeparturePointChange(filter, searchPanel) {
		var destination = dwr.util.getValue("destination");
			var departurePoint = dwr.util.getValue("departurePoint");

		if(useAjax == 2 || useAjax == 0){
			useAjax = 2;
			 AjaxSearchTools.mbcPointFilter(searchPanel, departurePoint, filter, 'childValues', mbcUpdateDestinations);
		}
	    }

	function onMbcDestinationChange(filter, searchPanel) { 
		var destination = dwr.util.getValue("destination");
		var departurePoint = dwr.util.getValue("departurePoint");

		if(useAjax == 1 ||  useAjax == 0){
			useAjax = 1;
			AjaxSearchTools.mbcPointFilter(searchPanel, destination, filter, 'parentValues', mbcUpdateDeparturePoints);
		}

	}
	
	function onMbcCountryChange(filter, searchPanel) { 
		var destination = dwr.util.getValue("region");
		if(useAjax == 1 ||  useAjax == 0){
			useAjax = 1;
			AjaxSearchTools.mbcPointFilter(searchPanel, destination, filter, 'childValues', mbcUpdateCountryPoints);
		}
	}
	
	function onMbcPfaCountryCookieChange(filter, searchPanel) {
		var destination = dwr.util.getValue("region");
		if(useAjax == 1 ||  useAjax == 0){
			useAjax = 1;
			AjaxSearchTools.mbcPointFilter(searchPanel, destination, filter, 'childValues', mbcUpdatePfaCountryPointsCookie);
		}
	}
	
	function onMbcAoCountryCookieChange(filter, searchPanel) {
		var destination = dwr.util.getValue("region");
		if(useAjax == 1 ||  useAjax == 0){
			useAjax = 1;
			AjaxSearchTools.mbcPointFilter(searchPanel, destination, filter, 'childValues', mbcUpdateAoCountryPointsCookie);
		}
	}
	
	function onMbcCrxCountryCookieChange(filter, searchPanel) {
		var destination = dwr.util.getValue("region");
		if(useAjax == 1 ||  useAjax == 0){
			useAjax = 1;
			AjaxSearchTools.mbcPointFilter(searchPanel, destination, filter, 'childValues', mbcUpdateCrxCountryPointsCookie);
		}
	}

	function onMbcDestinationPointChange(filter, searchPanel) { 
		var destination = dwr.util.getValue("country");
		if(useAjax == 1 ||  useAjax == 0){
			useAjax = 1;
			AjaxSearchTools.mbcPointFilter(searchPanel, destination, filter, 'childValues', mbcUpdateDestinationPoints);
		}
	}
	
	function onMbcDestinationPointCookieChange(filter, searchPanel) { 
		var destination = getCookie("flightAndHotelCountryDestination");
		if(useAjax == 1 ||  useAjax == 0){
			useAjax = 1;
			AjaxSearchTools.mbcPointFilter(searchPanel, destination, filter, 'childValues', mbcUpdateDestinationPointsCookie);
		}
	}
	
	function onMbcCityChange(filter, searchPanel) { 
		var destination = dwr.util.getValue("country");
		if(useAjax == 1 ||  useAjax == 0){
			useAjax = 1;
			AjaxSearchTools.mbcPointFilter(searchPanel, destination, filter, 'childValues', mbcUpdateCityPoints);
		}
	}
	
	function onMbcCityCookieChange(filter, searchPanel) { 
		var destination = getCookie("hotelOnlyCountryDestination");
		if(useAjax == 1 ||  useAjax == 0){
			useAjax = 1;
			AjaxSearchTools.mbcPointFilter(searchPanel, destination, filter, 'childValues', mbcUpdateCityCookiePoints);
		}
	}

	function onMbcPickupDropoffChange(filter, searchPanel) { 
		var destination = dwr.util.getValue("country");

		if(useAjax == 1 ||  useAjax == 0){
			useAjax = 1;
			AjaxSearchTools.mbcPointFilter(searchPanel, destination, filter, 'childValues', mbcUpdatePickupDropoff);
		}
	}
	
	function onMbcPickupDropoffCookieChange(filter, searchPanel) { 
		var destination = getCookie("carCountryDestination");

		if(useAjax == 1 ||  useAjax == 0){
			useAjax = 1;
			AjaxSearchTools.mbcPointFilter(searchPanel, destination, filter, 'childValues', mbcUpdatePickupDropoffCookie);
		}
	}

	function mbcUpdateDestinations(data){
		dwr.util.removeAllOptions("destination");
		dwr.util.addOptions("destination", data);
	}

	function mbcUpdateDeparturePoints(data){
		dwr.util.removeAllOptions("departurePoint");
		dwr.util.addOptions("departurePoint", data);
	}

	function mbcUpdateCountryPoints(data){
		dwr.util.removeAllOptions("country");
		dwr.util.addOptions("country", ["Pick country"]);
		dwr.util.addOptions("country", data);
	}
	
	function mbcUpdatePfaCountryPointsCookie(data){
		dwr.util.removeAllOptions("country");
		dwr.util.addOptions("country", ["Pick country"]);
		dwr.util.addOptions("country", data);
		var countryText = getCookie("flightAndHotelCountryDestination");
		if(countryText != null && countryText != ""){
			document.getElementById("country").value = countryText;
		}
	}
	
	function mbcUpdateAoCountryPointsCookie(data){
		dwr.util.removeAllOptions("country");
		dwr.util.addOptions("country", ["Pick country"]);
		dwr.util.addOptions("country", data);
		var countryText = getCookie("hotelOnlyCountryDestination");
		if(countryText != null && countryText != ""){
			document.getElementById("country").value = countryText;
		}
	}
	
	function mbcUpdateCrxCountryPointsCookie(data){
		dwr.util.removeAllOptions("country");
		dwr.util.addOptions("country", ["Pick country"]);
		dwr.util.addOptions("country", data);
		var countryText = getCookie("carCountryDestination");
		if(countryText != null && countryText != ""){
			document.getElementById("country").value = countryText;
		}
	}

	function mbcUpdateDestinationPoints(data){
		dwr.util.removeAllOptions("DESTINATION");
		dwr.util.addOptions("DESTINATION", ["Pick destination"]);
		dwr.util.addOptions("DESTINATION", data);
	}
	
	function mbcUpdateDestinationPointsCookie(data){
		dwr.util.removeAllOptions("DESTINATION");
		dwr.util.addOptions("DESTINATION", ["Pick destination"]);
		dwr.util.addOptions("DESTINATION", data);
		var destination = getCookie("flightAndHotelResortDestination");
		if(destination != null && destination != ""){
			setDropDownToCookieValueName("DESTINATION", getCookie("flightAndHotelResortDestination"));
		}
	}
	
	function mbcUpdateCityPoints(data){
		dwr.util.removeAllOptions("DESTINATION");
		dwr.util.addOptions("DESTINATION", ["Pick destination"]);
		dwr.util.addOptions("DESTINATION", data);
	}
	
	function mbcUpdateCityCookiePoints(data){
		dwr.util.removeAllOptions("DESTINATION");
		dwr.util.addOptions("DESTINATION", ["Pick destination"]);
		dwr.util.addOptions("DESTINATION", data);
		var destination = getCookie("hotelOnlyResortDestination");
		if(destination != null && destination != ""){
			setDropDownToCookieValueName("DESTINATION", getCookie("hotelOnlyResortDestination"));
		}
	}

	function mbcUpdatePickupDropoff(data){
		dwr.util.removeAllOptions("pickupLocation");
		dwr.util.removeAllOptions("dropoffLocation");
		dwr.util.addOptions("pickupLocation", ["Choose pickup"]);
		dwr.util.addOptions("dropoffLocation", ["Choose dropoff"]);
		dwr.util.addOptions("pickupLocation", data);
		dwr.util.addOptions("dropoffLocation", data);
	}
	
	function mbcUpdatePickupDropoffCookie(data){
		dwr.util.removeAllOptions("pickupLocation");
		dwr.util.removeAllOptions("dropoffLocation");
		dwr.util.addOptions("pickupLocation", ["Choose pickup"]);
		dwr.util.addOptions("dropoffLocation", ["Choose dropoff"]);
		dwr.util.addOptions("pickupLocation", data);
		dwr.util.addOptions("dropoffLocation", data);
		var pickup = getCookie("carPickup");
		if(pickup != null && pickup != ""){
			setDropDownToCookieValueName("pickupLocation", getCookie("carPickup"));
		}
		var dropoff = getCookie("carDropoff");
		if(dropoff != null && dropoff != ""){
			setDropDownToCookieValueName("dropoffLocation", getCookie("carDropoff"));
		}
	}
	

  	function checkform(searchPanel) {
  		
  		if (searchPanel == 'pfa') {
			// Child age error message
			for (i=1;i<=6;i++) {
				var childDisplay = "child"+i;
				var childCombo = "child"+i+"Combo";
				if (document.getElementById(childDisplay).style.display != 'none') {
					if (document.getElementById(childCombo).value == "") {
						document.getElementById("childAgeError").style.display = 'block';
						return false;
					}
				}
			}
			document.getElementById("childAgeError").style.display = 'none';
		}
		
		if (searchPanel != 'crx') {
			var dateValid = validateDate(document.getElementById("departureDate").value);
			if (dateValid != 'true') {
				document.getElementById("dateError").style.display = 'block';
				return false;
			}
		}
		
		
		
		if (document.getElementById("region").value == '-1') {
			document.getElementById("dateError").style.display = 'none';
			document.getElementById("regionError").style.display = 'block';
			return false;
		}
		else if (document.getElementById("country").value == 'Pick country') {
			document.getElementById("dateError").style.display = 'none';
			document.getElementById("regionError").style.display = 'none';
			document.getElementById("countryError").style.display = 'block';
			return false;
		}
		else if (searchPanel == 'crx') {
			if (document.getElementById("pickupLocation").value == 'Choose pickup') {
				document.getElementById("dateError").style.display = 'none';
				document.getElementById("regionError").style.display = 'none';
				document.getElementById("countryError").style.display = 'none';
				document.getElementById("pickupLocationError").style.display = 'block';
				return false;
			}
			else if (document.getElementById("dropoffLocation").value == 'Choose dropoff') {
				document.getElementById("dateError").style.display = 'none';
				document.getElementById("regionError").style.display = 'none';
				document.getElementById("countryError").style.display = 'none';
				document.getElementById("pickupLocationError").style.display = 'none';
				document.getElementById("dropoffLocationError").style.display = 'block';
				return false;
			}
		}
		else if (searchPanel != 'crx') {
			if (searchPanel == 'ao') {
				if (document.getElementById("DESTINATION").value == 'Pick destination') {
					document.getElementById("dateError").style.display = 'none';
					document.getElementById("regionError").style.display = 'none';
					document.getElementById("countryError").style.display = 'none';
					document.getElementById("destinationError").style.display = 'block';
					return false;
				}
			}
			
			if (searchPanel == 'pfa' || searchPanel == 'pra' || searchPanel == 'pfc') {
				if (document.getElementById("DESTINATION").value == 'Pick destination') {
					document.getElementById("dateError").style.display = 'none';
					document.getElementById("regionError").style.display = 'none';
					document.getElementById("countryError").style.display = 'none';
					document.getElementById("destinationError").style.display = 'block';
					return false;
				}
				if (document.getElementById("departurePoint").value == '-1') {
					document.getElementById("dateError").style.display = 'none';
					document.getElementById("regionError").style.display = 'none';
					document.getElementById("countryError").style.display = 'none';
					document.getElementById("destinationError").style.display = 'none';
					document.getElementById("departureError").style.display = 'block';
					return false;
				}
			}
		}
		else {
			return true;
		}
		
		if (searchPanel == 'pfa') {
			flightAndHotelSubmit();
		}
		if (searchPanel == 'ao') {
			hotelOnlySubmit();
		}
		if (searchPanel == 'crx') {
			if(validatePickupAndDropOffDates(document.getElementById("pickupDate"),document.getElementById("returnDate"),document.getElementById("fromDateTime_hour"),document.getElementById("toDateTime_hour"))){
				carSubmit();
				return true;
			}
			else
				return false;
		}
	  }

	  function validatePickupAndDropOffDates(pickUpDateObj,dropOffDateObj,pickUpTimeObj,dropOffTimeObj){
		  var canSubmit = true;
		 
		  if(!isValidDate(pickUpDateObj)){
			  document.getElementById('dateError').innerHTML = "Please choose a valid date";
			  canSubmit = false;
		  }if(!isValidDate(dropOffDateObj)){
			  document.getElementById('dateError').innerHTML = "Please choose a valid date";
			  canSubmit = false;
		  }if(canSubmit){
				var pickUpDate=new Date();
				var dropOffDate=new Date();
				var pickUpDateSplit = pickUpDateObj.value.split("/"); 
				var dropOffDateSplit = dropOffDateObj.value.split("/"); 
				pickUpDate.setFullYear(20+pickUpDateSplit[2],pickUpDateSplit[1]-1,pickUpDateSplit[0]);
				dropOffDate.setFullYear(20+dropOffDateSplit[2],dropOffDateSplit[1]-1,dropOffDateSplit[0]);
				if(pickUpTimeObj != null && dropOffTimeObj != null){
					pickUpDate.setHours(pickUpTimeObj.value);
					dropOffDate.setHours(dropOffTimeObj.value);
				}
				if(pickUpDate.getTime()>dropOffDate.getTime()){
					document.getElementById('dateError').innerHTML = "Dropoff date must be after the Pickup date";
					canSubmit = false;
				}else if(pickUpDate.getTime()==dropOffDate.getTime()){
					document.getElementById('dateError').innerHTML = "Pickup date and time, Dropoff date and time should not be same";
					canSubmit = false;
				}
		   }
		   if(!canSubmit)
			   document.getElementById('dateError').style.display = 'inline';
		   else
   			   document.getElementById('dateError').style.display = 'none';
		   return canSubmit;
	  }

	  function mbcSearchSwitch(url, productType){
	  	  AjaxSearchTools.getInclude(url, productType, changeSearch);  
	  }
	  
	  function changeSearch(data){
		 var currentSearchPanel = dwr.util.getValue("rightcont"); 
		 dwr.util.setValue("rightcont", data);
	  }
	  
      // Refreshing resorts drop-down
      function updateReviewResorts(data) {

        	dwr.util.removeAllOptions("resortSelect");
        	dwr.util.addOptions("resortSelect", data);
        	//calling this because on change of destination to default "select destination"
			//should also change the accommodation in addition to resorts.
			onReviewResortChange();
      }
      
      function onReviewResortChange() { 
        var resort = dwr.util.getValue("resortSelect");
        var tourOps = dwr.util.getValue("tourOpsSelect");
        AjaxSearchTools.populateAccommodations(resort,tourOps, updateReviewAccommodations);
      }

           // Refreshing Accommodation drop-down
      function updateReviewAccommodations(data) {
         dwr.util.removeAllOptions("accommodationSelect");
         dwr.util.addOptions("accommodationSelect", data);
       
      }   
        

	  function updateCompareList(action,selectedID,successURL,errorURL){
		  //selectedID is of the format 2x2_CurrentPackageID / 3x3_CurrentPackageID / CurrentPackageID -(for 1x1).
		  //So stripping of 2x2_ & 3x3_ if it exists.
		  if(selectedID.indexOf("_")!= -1){
               selectedID = selectedID.substring(selectedID.indexOf("_")+1);
		  }

		  //making an asynchronous java method call
		  AjaxSearchResultTools.reqUpdateComparisonList(action,selectedID,successURL,errorURL,updateCompareCount);
	  }

	  function updateCompareCount(data){
		  if(document.getElementById("holDetPopSpanID") || document.getElementById("holInfoPopSpanID")){
			  //pushing the d ata to the parent window.
			  if(window.opener.document.getElementById("compCountSpanID"))
			  {
                  window.opener.document.getElementById("compCountSpanID").innerHTML = data;
				  window.opener.globCompCount = data;
			  }
		  }else{
			 if(document.getElementById("compCountSpanID")){
				document.getElementById("compCountSpanID").innerHTML = data;
			 }
		  }
      }

	  function updateCompareList_AltFlight(action,selectedID,successURL,errorURL){
          AjaxSearchResultTools.reqUpdateComparisonListForAlternateFlightPackage(action,selectedID,successURL,errorURL,updateCompareCount)
	  }

	  function ajaxAddToShortList(action,selectedID,shortListURL,resultIndex)
	  {
		  //selectedID is of the format 2x2_CurrentPackageID / 3x3_CurrentPackageID / CurrentPackageID -(for 1x1).
		  //So stripping of 2x2_ & 3x3_ if it exists.
		  if(selectedID.indexOf("_")!= -1){
               selectedID = selectedID.substring(selectedID.indexOf("_")+1);
		  }

		  //making an asynchronous java method call
		  if(action == "Add"){
				AjaxSearchResultTools.reqAddToShortList(action,selectedID,shortListURL,updateShortListCount);
		  }else if(action == "Remove"){
                AjaxSearchResultTools.reqRemoveFromShortList(action,selectedID,shortListURL,updateShortListCount);
		  }

	  }


      /**
	   * This function updates the shortlist count on holidayplanner.jsp & correspondingly shows/hides save my 
	   * shortlist link.(checkUserStatus() & checkUserStatus_popup() does this).
	   */
      function updateShortListCount(data){

  		  if(document.getElementById("holDetPopSpanID") || document.getElementById("holInfoPopSpanID")){
        	  //calls a method that is defined in holidayInfoPopup.jsp/holidayDetailsPopup.jsp
			  checkUserStatus_popup(data);
		  }else{
			  if(document.getElementById("shortLstSpanID")){
				  document.getElementById("shortLstSpanID").innerHTML = data;
				  //calls a method that is defined in searchResults.jsp/myCompareList.jsp/myShortlist.jsp
				  checkUserStatus(data);
				  if(data > 0){
					   //fix for ACE issue # 850
						if(document.getElementById("errorBlock")){
								//document.getElementsByName("contentLeftDiv")[0].style.display ='block';
								 //document.getElementsByName("contentRightDiv")[0].style.display ='block';
								document.getElementById("errorBlock").style.display ='none';
						}
				  }else{
						//fix for ACE issue # 850
						if(document.getElementById("errorBlock")){
								document.getElementById("bodyLeft").style.display ='none';
								document.getElementById("bodyRight").style.display ='none';
								//document.getElementById("errorBlock").style.display ='block';
								document.getElementById("errorBlock").style.display ='block';
						}
				  }
			  }
		  }
	  }


     function ajaxAddToShortList_AltFlights(action,selectedID,shortListURL,resultIndex){
		  //alert("ajaxAddToShortList_AltFlights");
		  if(action == "Add"){
				AjaxSearchResultTools.reqAddAlternateFlightPackageToShortList(action,selectedID,shortListURL,updateShortListCount);
				
		  }else if(action == "Remove"){
                AjaxSearchResultTools.reqRemoveAlternateFlightPackageToShortList(action,selectedID,shortListURL,updateShortListCount);
		  }
	 }

     /* function updateShortListCount_AltFlights(data){
		  //document.getElementById("shortLstSpanID").innerHTML = "View My Shortlist ("+data+")";
		  document.getElementById("shortLstSpanID").innerHTML = data;
		  alert(data);
		  if(data > 0){
				document.getElementById("saveShrtLstSpanID").style.display = "block";
				//document.getElementById("currShrtLstSpanID").style.display = "none";

	      }else{
		        document.getElementById("saveShrtLstSpanID").style.display = "none";
	            //document.getElementById("currShrtLstSpanID").style.display = "block";
		  } 
	  } */

	 // This function will update the recently viewed list without refreshing the page.
      var selectedPackId = "";
	  var currency = "";
	  function updateRecentlyViewedList(selectedPackageId, currencyCode){
		    selectedPackId = selectedPackageId;
			currency = currencyCode;			
			AjaxSearchResultTools.reqUpdateRecentlyViewed(selectedPackageId,currencyCode,updateRVList);	
	  }
      
	  //This call back method takes a map as an input.
	  function updateRVList(data) {
		   var tmpInnerHTML = "";
		   var holidayDetailPopup ="/search/holiday/holidayDetailPopup.jsp";
		   var counter =0;
		  for (var property in data) {
				// Are there any elements with that id or name
				  //alertMe(property);
				  //alert(counter);
				  if (property != null) {
						var tmpArray = new Array();
						var tmpValue = data[property];
					 if(tmpValue.indexOf("#") > 0){
						 tmpArray = tmpValue.split("#");
					  }
					  if(tmpArray.length ==3){
						  tmpInnerHTML = tmpInnerHTML+ "<li><a href='javascript:openHolidayPopup('"+tmpArray[0]+"','"+holidayDetailPopup+"')' >"+tmpArray[1]+"</a> - "+tmpArray[2]+"</li>";
					  }
					  //else{
						//  tmpInnerHTML = tmpInnerHTML+ "<li><a href='#')' >"+tmpArray[0]+"</a> - £"+tmpArray[1]+"</li>";
					  //} 
					  
				}
			counter++;
		  }
		  selectedPackId = "";
		  if(document.getElementById("lastviewedul") != null){
		 document.getElementById("lastviewedul").innerHTML =tmpInnerHTML;
	  }
	  }
	  
	  function sendRedirect(){
		  if(window.self == window.top){
			var url = getQueryVariable("url");
			if(url != null && url != undefined){
				var point = url.lastIndexOf('&amp;_requestid');
				if(point != -1){		 	
					url = url.substring(0, point);
				}
			parent.location.replace(url);
			}
		  } else {
			 parent.location.replace(window.self.location)
		  }
	  }
	  
	  
	  function getQueryVariable(variable) {
  		var query = window.location.search.substring(1);
		var queryLength = query.length;
		var equalsPosition = query.search("=") + 1;
		return query.substring(equalsPosition, queryLength);
	   } 

	/*Fix for the issue INC700005974197  [P1 Critical priority ] & INC700005916972 [P3 Medium Priority]
	New Ajax methods created for population of all the drop downs on search
	panel specific to Clubbing Holiday Type. The new methods created are:
	populateClubbingDestinationDropDown(),populateClubbingDurationDropDown(),
	updateClubbingDurations(),populateClubbingBudgetDropDown() ,updateClubbingBudgets(),
	populateClubbingBBDropDown(),updateClubbingBoardBasis(),populateClubbingStarRatingDropDown(),
	updateClubbingStarRating(),populateClubbingDepartureDate(),updateClubbingDepartureDate()
	*/

// Javascript function called  to populate Clubbing -dependent destinations.
	function populateClubbingDestinationDropDown() {
        var profile = dwr.util.getValue("propositionSelect"); /*Clubbing proposition ID */
        AjaxSearchTools.populateDestinations(profile, updateDestinations);
        AjaxSearchTools.populateDefaultDestination(profile, updateDefaultDest);
    }
// Javascript function called  to populate Clubbing -dependent durations.
   function populateClubbingDurationDropDown() {
	    var profile = dwr.util.getValue("propositionSelect"); /*Clubbing proposition ID */		
        AjaxSearchTools.populateDurations(profile, updateClubbingDurations);
        }

	//Refreshing durations drop-down
   function updateClubbingDurations(data) {
	    var profile = dwr.util.getValue("propositionSelect"); /*Clubbing proposition ID */
        dwr.util.removeAllOptions("inputnights");
        dwr.util.addOptions("inputnights", data);
        AjaxSearchTools.populateDefaultDuration(profile, updateDefaultNights);
        }

	// Javascript function called  to populate Clubbing -dependent budgets.
   function populateClubbingBudgetDropDown() {
        var profile = dwr.util.getValue("propositionSelect"); /*Clubbing proposition ID */
        AjaxSearchTools.populateBudgets(profile, "CLB", updateClubbingBudgets);
    }

	//Refreshing budgets drop-down
   function updateClubbingBudgets(data) {
	    var profile = dwr.util.getValue("propositionSelect"); /*Clubbing proposition ID */
        dwr.util.removeAllOptions("inputbudget");
        dwr.util.addOptions("inputbudget", data);
		//making another async call to server
		AjaxSearchTools.populateDefaultBudget(profile, updateDefaultBudgets);
   }

  
// Javascript function called  to populate Clubbing-dependent BoardBasis.
   function populateClubbingBBDropDown() {
        var profile = dwr.util.getValue("propositionSelect"); /*Clubbing proposition ID */
        AjaxSearchTools.populateBoardBasis(profile, updateClubbingBoardBasis);
        }

	//Refreshing inputboard drop-down
   function updateClubbingBoardBasis(data) {
	    var profile = dwr.util.getValue("propositionSelect"); /*Clubbing proposition ID */
        dwr.util.removeAllOptions("inputboard");
        dwr.util.addOptions("inputboard", data);
        AjaxSearchTools.populateDefaultBB(profile, updateDefaultBoardBasis);
        }
// Javascript function called  to populate Clubbing -dependent Star rating.
   function populateClubbingStarRatingDropDown() {
		var profile = dwr.util.getValue("propositionSelect"); /*Clubbing proposition ID */
        AjaxSearchTools.populateStarRating(profile, updateClubbingStarRating);
        }

	//Refreshing Star Rating drop-down
   function updateClubbingStarRating(data) {
		var profile = dwr.util.getValue("propositionSelect"); /*Clubbing proposition ID */
        dwr.util.removeAllOptions("inputstarrating");
        dwr.util.addOptions("inputstarrating", data);
		AjaxSearchTools.populateDefaultStarRating(profile, updateDefaultStarRating);
        }

// Javascript function called  to populate Clubbing -dependent departure date
	function populateClubbingDepartureDate(depDateID) {
		var profile = dwr.util.getValue("propositionSelect"); /*Clubbing proposition ID */
		  var depDate = document.getElementById('departureDate').value;
		  AjaxSearchTools.populateDepDate(profile,depDate, updateClubbingDepartureDate);
	   }

// setting departure date
   function updateClubbingDepartureDate(data){
	   arrDateTokens = data.split("-");
	   if(arrDateTokens.length > 0)
	       document.getElementById('defaultDay').innerHTML = arrDateTokens[1];
		   document.getElementById('departureDate').value = arrDateTokens[0];
   }  
/**
* FF9159 Bin Range Recognition
* Global Variables for Bin Range
*/
var validChars = "0123456789 "; /*Numerical and space characters only allowed */
var currentCharForCC = 0;/*Global Var required in getCreditCardNumberLength method */

   
/**
 * FF9159 Bin Range Recognition function1
 * This method is used to disable the all fields 
 * on tcBinRangePaymentDetails.jsp
 */
function creditCardDisable()
{
		document.getElementById("nameoncard").disabled=true;
		document.getElementById("fromDateMonth").disabled=true;
		document.getElementById("fromDateYear").disabled=true;
		document.getElementById("ccv").disabled=true;
		document.getElementById("cvvInputDiv").disabled=true;
		document.getElementById("cardissue").disabled=true;
		document.getElementById("ExpiryDateMonth").disabled=true;
		document.getElementById("ExpiryDateYear").disabled=true;
		document.getElementById("nameOnCardLabel").disabled=true;
		document.getElementById("validFromLabel").disabled=true;
		document.getElementById("expiryDateLabel").disabled=true;
		document.getElementById("ccvLabel").disabled=true;
		document.getElementById("cardIssueLabel").disabled=true;
		/*Commented out for defect 10
		document.getElementById("frmDtMnthOption").disabled=true;
		document.getElementById("frmDtYrOption").disabled=true;
		document.getElementById("expDtMnthOption").disabled=true;
		document.getElementById("expDtYrOption").disabled=true;
		*/
		document.getElementById("inputCvvLabel").disabled=true;
		document.getElementById("extraInfoDiv").style.display = "none";
		
}
/**FF9159 Bin Range Recognition function2
*This method is used to enable the all fields 
* on tcBinRangePaymentDetails.jsp
*/
function creditCardEnable()
{
    var fullPaymentByTP = 'false' ;
	if(document.getElementById("fullPaymentByTP")){
		fullPaymentByTP = document.getElementById("fullPaymentByTP").value;	
	}
	if(fullPaymentByTP != 'true'){

		
		if(document.getElementById("creditCardTypeId").value == ''){

			document.getElementById("creditCardTypeId").value = 'visa';
			
		}

		document.getElementById("nameoncard").disabled=false;
		document.getElementById("fromDateMonth").disabled=false;
		document.getElementById("fromDateYear").disabled=false;
		document.getElementById("ccv").disabled=false;
		document.getElementById("cvvInputDiv").disabled=false;
		document.getElementById("cardissue").disabled=false;
		document.getElementById("ExpiryDateMonth").disabled=false;
		document.getElementById("ExpiryDateYear").disabled=false;
		document.getElementById("nameOnCardLabel").disabled=false;
		document.getElementById("validFromLabel").disabled=false;
		document.getElementById("expiryDateLabel").disabled=false;
		document.getElementById("ccvLabel").disabled=false;
		document.getElementById("cardIssueLabel").disabled=false;
		/*Commented out for ACE defect 10
		document.getElementById("frmDtMnthOption").disabled=false;
		document.getElementById("frmDtYrOption").disabled=false;
		document.getElementById("expDtMnthOption").disabled=false;
		document.getElementById("expDtYrOption").disabled=false;
		*/
		document.getElementById("inputCvvLabel").disabled=false;
		document.getElementById("extraInfoDiv").style.display = "block";
	}
		
}
/**
 * FF9159 Bin Range Recognition function#
 * This method is used to reset all input 
 * parameters
 * 
 */
function resetInput()
{

	/**
	 * Reset the CCname,CCimage,fees  
	 */
	document.getElementById("ccName").innerHTML='';
	document.getElementById("ccImage").innerHTML='';
	document.getElementById("ccfees").innerHTML=''; 
	/*******************************************************
	  As part of issue 125 the CC Number should not be reset.
	   Hence block below commented out
	 ******************************************************/
	 /**if (document.getElementById("numberoncard").value!='')
	 { 
    	document.getElementById("numberoncard").value='';
    	setTimeout(function(){document.getElementById('numberoncard').focus();},100);
	 }*/
	 
	 /*******Change for #125 - bin Range ends ***************/
	
}
/**FF9159 Bin Range Recognition function4
* This method has been called from binRangePaymentDetails.jsp & tcBinRangePaymentDetails.jsp
* When the user has entered 8 digits, in the creditcardnumber input box.
* On keypress of 9th digit, the following function is called
*/
function getCreditCardNumberLength()
{ 
			var inputCCNoValue = document.getElementById("numberoncard").value;
			var inputCCNoLength = document.getElementById("numberoncard").value.length;	
			
			var inputCCNoValueWihoutSpace = inputCCNoValue;			
			var intIndexOfMatch = inputCCNoValueWihoutSpace.indexOf(' ');

			while (intIndexOfMatch != -1){
				inputCCNoValueWihoutSpace = inputCCNoValueWihoutSpace.replace( ' ', '' )
			     intIndexOfMatch = inputCCNoValueWihoutSpace.indexOf( ' ' );
			}
			var inputCCNoLengthWithoutSpace = inputCCNoValueWihoutSpace.length;
			
		    /**
		     *  if user has  deleted/emptied the Credit Card number
		     */
		  	if ((inputCCNoLength == '0')&&(inputCCNoValue == ''))
		  	{    			  	 
				 if (document.getElementById("ccName").style.display == "block")
				 {
					 document.getElementById("ccName").style.display = "none";
			    	 document.getElementById("ccfees").style.display = "none";
			    	 document.getElementById("ccImage").style.display = "none"; 
			    	 document.getElementById("justToCheck").style.display = "none";
			    	 document.getElementById("ccName").innerHTML='';
				     document.getElementById("ccImage").innerHTML='';
				     document.getElementById("ccfees").innerHTML='';		
				 }
				 else if (document.getElementById("invalidBinError").style.display == "block")
				 {
					 if (document.getElementById("numberoncard").focus())
					 {
						 document.getElementById("invalidBinError").style.display = "none";	 
					 }
				 }
		  	}
		  	else 		   
			  	{	
			  		/**
			  		 * when inputCCNoLength >0 && inputCCNoValue != null
			  		 */		  		
			     	var thisChar = inputCCNoValue.charAt(currentCharForCC); 
				    /**
				     * Checking the character(key) entered is numeric, space or not
				     */
				    if(validChars.indexOf(thisChar)!=-1)
					  {  
				    			
				    	        if (inputCCNoLengthWithoutSpace == '8')
				    			{
						  			/**
						  			 *Setting global Var to true so that
						  			 *findCCType is not called onPaste also
						  			 */
						  			findCreditCardType(inputCCNoValueWihoutSpace);
				    			}
				    			currentCharForCC=currentCharForCC+1;
					  }else
					  {
						  		currentCharForCC=0;
		
							  	if (document.getElementById("invalidBinError").style.display == "none")
							  	{
							  		document.getElementById("invalidBinError").style.display = "block";
							  		
							  	}
							  	 var timelagReset = setTimeout("resetInput();",200);
					  }
			}
}
/**
 * FF9159 Bin Range Recognition function5
 * This method is used to check when user has copy pasted 
 * on the credit card number field,if the input entered is numeric or not
 */
function isNumeric(strNum) 
{
	    var isNumber=true;
	    var thisChar;
	    for (i = 0; i < strNum.length; i++) 
	    {  
		    thisChar = strNum.charAt(i); 
		    if (validChars.indexOf(thisChar)==-1){
		    	isNumber = false;
		    }
	    }
	    return isNumber;
}

/**
 * FF9159 Bin Range Recognition function #
 * To show waiting/loading image 
 * on key press event
 * - Not used and removed for ACE#39 -7.6 Bin Range
 */
function showBinWaitPageOnKeyPress()
{ 
	var inputCCNoLength = document.getElementById("numberoncard").value.length;	
	if(inputCCNoLength == '0'){
		document.getElementById("binWaitImage").style.display = "none";
		 document.getElementById("justToCheck").style.display = "none";
		}
	if(inputCCNoLength == '1'){
	document.getElementById("binWaitImage").style.display = "block";
	 document.getElementById("justToCheck").style.display = "block";
	}
}
/**
 * FF9159 Bin Range Recognition function #
 * To show waiting/loading image 
 * on paste event - Not used and removed for ACE#39 -7.6 Bin Range
 */
function showBinWaitPageOnPaste()
{ 

	var inputCCNoLength = document.getElementById("numberoncard").value.length;	

	
	if(inputCCNoLength == '0'){
		document.getElementById("binWaitImage").style.display = "none";
		 document.getElementById("justToCheck").style.display = "none";
		}

	document.getElementById("binWaitImage").style.display = "block";
	 document.getElementById("justToCheck").style.display = "block";
	
	
}

function handleOnBlur()
{
	var timelagBlur = setTimeout("handleInput();",500);
	/*TODO handle if other events already run*/
}
function handleOnPaste()
{
	var timelagPaste = setTimeout("handleInput();",500);
}
function handleOnCut()
{
	 var timelagCut = setTimeout("handleInput();",500);
}
function handleInput()
{

	var inputCCNoValue = document.getElementById("numberoncard").value;
	var inputCCNoLength = document.getElementById("numberoncard").value.length;	
	var inputCCNoValueWihoutSpace = inputCCNoValue;			
	var intIndexOfMatch = inputCCNoValueWihoutSpace.indexOf(' ');

	while (intIndexOfMatch != -1){
		inputCCNoValueWihoutSpace = inputCCNoValueWihoutSpace.replace( ' ', '' )
	     intIndexOfMatch = inputCCNoValueWihoutSpace.indexOf( ' ' );
	}
	var inputCCNoLengthWithoutSpace = inputCCNoValueWihoutSpace.length;	

	
	if(inputCCNoLengthWithoutSpace >= '9')
	{	
		/**
		 * For Bin Check we will use only the first 8 digits of CC number 
		 */
		var inputCCBinVal = inputCCNoValueWihoutSpace.substr(0,8);	
		var inputCompleteValue = inputCCNoValueWihoutSpace;
	
		getCreditCardLengthOtherwise(inputCCBinVal,inputCompleteValue);
		
	} 
	/**
	 * if user has entered/pasted equal to  8 digits execute below
	 */
	if (inputCCNoLengthWithoutSpace == '8')
	{

		var inputCCBinVal = inputCCNoValueWihoutSpace;	
		var inputCompleteValue = inputCCNoValueWihoutSpace;
	
		getCreditCardLengthOtherwise(inputCCBinVal,inputCompleteValue);
		
	}	
	/**
	 * If user has entered less than 8 digits do not do anything
	 */
	/**
	 * if user has not entered or the entry has been deleted by user
	 */
	if((inputCCNoLengthWithoutSpace == '0')&&(inputCCNoValueWihoutSpace == ''))
	{	 
		if (document.getElementById("ccName").style.display == "block")
		 {
			 document.getElementById("ccName").style.display = "none";
	    	 document.getElementById("ccfees").style.display = "none";
	    	 document.getElementById("ccImage").style.display = "none";
	    	 document.getElementById("justToCheck").style.display = "none";
	    	 document.getElementById("ccName").innerHTML='';
		     document.getElementById("ccImage").innerHTML='';
		     document.getElementById("ccfees").innerHTML='';
		     
	    	 
		 }
		 else if (document.getElementById("invalidBinError").style.display == "block")
		 {
			 if (document.getElementById("numberoncard").focus())
			 {
				 document.getElementById("invalidBinError").style.display = "none";	
			 }
		 }		 				 
	}
	
}
/**
 * 
 */
function getCreditCardLengthOtherwise(inputCCNoBinValue,inputCompleteValue)
{ 	
		if (isNumeric(inputCompleteValue)== true)
		{   
			findCreditCardType(inputCCNoBinValue);
		}
		if (isNumeric(inputCompleteValue)== false)
		{
			if (document.getElementById("invalidBinError").style.display == "none")
		  	{
		  		document.getElementById("invalidBinError").style.display = "block";
			}
		    var timelagReset = setTimeout("resetInput();",200);
		}
}

/**
* FF9159 Bin Range Recognition function7
*The above method passes the 
* It passes the control to java class and the method
* @ params = first 8 digits of card number user has entered
* This is the Ajax method
*/
function findCreditCardType(userBinRange)
{

		var pageSiteId = document.getElementById('pageSite').value;
		var isCardFeeFixed = document.getElementById('cardFeeFixedId').value;
		
		if (userBinRange!= null && userBinRange!='')
		{		
			if ((pageSiteId != null) && (pageSiteId != '') && (isCardFeeFixed != null) && (isCardFeeFixed != ''))
			{		
				BinRangeValidatorTool.getCreditCardType(userBinRange,pageSiteId,isCardFeeFixed,updateCreditCardType);
			}
		}
}
/**
 * FF9159 Bin Range Recognition function8
 * Whatever return is received from Java method ,
 * the following method is used to set the output 
 * to the jsp.
 */
function updateCreditCardType(data)
{    
	  var counter = 1;
      var tmpArray = new Array();
	   var isResetRequired = false;  
	  for (var property in data)
	 {	    		 
		if (property != null )
		{	
	        
	      if (property == 'binCheckError')
		     {	/**
	     	  	 * Fetch the bin error from the data map if any exist
	     	  	 */	    	 
			     var binError = data['binCheckError'];
			 	 if (binError == true)
			 	 {  /**
			 		  * Disable the payment input fields
			 		  */
			 		 creditCardDisable();

			 		 document.getElementById("invalidCardError").style.display = "block";
			 		 isResetRequired = true;
					 
			 		 /**
			 		  * Disabling the 'pay now' button as well as showing 
			 		  * a div which  has a message for user
			 		  */
			 		document.getElementById("paynow").disabled=true;
			 		document.getElementById("onBinErrorUserInfo").style.display="block";
					 
			 		
			 		
			 	 }else{
			 		 document.getElementById("invalidCardError").style.display = "none";
			 		 /**
			 		  * Enabling the 'pay now' button as well as hiding
			 		  * the user message div.
			 		  */
			 		document.getElementById("paynow").disabled=false;
			 		document.getElementById("onBinErrorUserInfo").style.display="none";
			 		 
			 		 
			 	 }
		     }
	      	if (property == 'ccNumberIsNaN')
		     {/**
	    	   * Fetch the invalid CCnum error from the data map if any exist
	    	   */	    
			    var invalidCCNum = data['ccNumberIsNaN'];
			    if (invalidCCNum == true)
		    	 {  /**
		    		  * Disable the payment input fields
		    		  */
		    		 creditCardDisable();
		    		 document.getElementById("invalidBinError").style.display = "block";
		    		 isResetRequired = true;
                    
		    		 /**
			 		  * Disabling the 'pay now' button as well as showing 
			 		  * a div which  has a message for user
			 		  */
		    		 document.getElementById("paynow").disabled=true;
		    		 document.getElementById("onBinErrorUserInfo").style.display="block";

		    	 }else{
		    		
		    		 document.getElementById("invalidBinError").style.display = "none";
		    		 /**
			 		  * Enabling the 'pay now' button as well as hiding
			 		  * the user message div.
			 		  */
		    		 document.getElementById("paynow").disabled=false;
		    		 document.getElementById("onBinErrorUserInfo").style.display="none";
			 		 
		    	 }  
	        }
	      	if (property == 'cardType')
		     {      var ccTypeVal = data['cardType'];
			    	 /**
			    	  * Fetch the card type from the data map
			    	  */
			    	 document.getElementById("creditCardTypeId").value = ccTypeVal; 
			    	 if (ccTypeVal != null)
			    	 {  /**
				    	  * In case of laser, CVV box need not be shown.
				    	  */
				    	 if (ccTypeVal == 'laser')
					    	 {
					    		 document.getElementById("cvvInputDiv").style.visibility = 'hidden';
					    	 }
				    	 else
					    	 {
				    		 	document.getElementById("cvvInputDiv").style.visibility = 'visible';
					    	 }
			    	 }
		     }
	      	if (property == 'displayName')
			{  		/**
		    		 * Fetch the credit card display name from the data map
		    		 */
		         	document.getElementById('ccName').innerHTML=data['displayName']; 
		     }
	      	if (property == 'issueNumberExists')
		     {  	var issueNumExists=data['issueNumberExists'];
		    	 	if (issueNumExists == true)
		    	 	{  /**
		    	    	 * showing issue number div in case of Solo and maestro cards
		    	    	 */
		    	 		document.getElementById("issueNumber").style.visibility = 'visible';
		    	 	}			    	 	
		    	 	else if (issueNumExists == false)
		    	 	{
		    	 		document.getElementById("issueNumber").style.visibility = 'hidden';
		    	 	}
		     }	  
	      	if (property == 'imagePath')
		     {  /**
	    		 *  Fetch the credit card image path from the data map
	    		 */
			    	var cardImagePath = "\'"+data['imagePath']+"\'";	
			        document.getElementById('ccImage').innerHTML="<img src="+cardImagePath+"/>";
		     }
		     if (property == 'percentageFees' || property == 'fixedFees')
		     { 
					var percFeeVar = 0.0;
					var fixedFeeVar = 0.0;
				  /**
					* Fetch fees from the data map and call to the calculate fees method in paymentJs.jsp
					**/
					percFeeVar = data['percentageFees'];
					fixedFeeVar = data['fixedFees'];
			    	calculateFees(percFeeVar,fixedFeeVar);
			    	document.getElementById('feesCalculated').value= percFeeVar;    	
		     }
		
			    	   if ((property != 'binCheckError')||(property != 'ccNumberIsNaN')||(property!='inputCardNumber'))
				     {
							var tmpValue = data[property];
							tmpArray[counter]= tmpValue;
							counter++;
				     }		 			
		}
	 }
		 	 /**
		 	  * If fields are to be reset based on the validation above
		 	  */
	    	if(isResetRequired == true || tmpArray == ''){
	    				 
                       
					/*	document.getElementById("invalidBinError").style.display = "none";*/
						document.getElementById("ccName").style.display = "none";
		    	 		document.getElementById("ccfees").style.display = "none";
		    			document.getElementById("ccImage").style.display = "none";
		    			document.getElementById("justToCheck").style.display = "none";
		    			var timelagReset = setTimeout("resetInput();",200);
		    			
		    			
		    			
			 }else{
	    		 		 
				 		creditCardEnable();
	    		 		document.getElementById("ccName").style.display = "block";
	    		 		document.getElementById("ccfees").style.display = "block";
		    	        document.getElementById("ccImage").style.display = "block";
		    	        document.getElementById("justToCheck").style.display = "block";
					    
	    	 } 	 	 	
	    	/**
	    	 *  finally removing the waiting image from page 
	    	 *  document.getElementById("binWaitImage").style.display = "none";
	    	 */
	
    	
}

/* End of BinRange Recognition Methods */
	

	function populateSnowDepDate(){
		var curDate = new Date;
		var snowDate = new Date;
		snowDate.setDate(curDate.getDate()+3);
			var month = snowDate.getMonth();
			if(month == 11 || month == 0 || month == 1 || month == 2 || month == 3) {
				if(month < 4)
					month = "0"+(month+1);
				var dateNum = snowDate.getDate();
				//dateNum=dateNum+3;
				if(dateNum<10)
					dateNum = "0"+dateNum;

				document.getElementById('departureDate').value = dateNum+"/"+month+"/"+(snowDate.getFullYear()-2000);
			}else{
				document.getElementById('departureDate').value = "01/12/"+(snowDate.getFullYear()-2000);
			}
	}
	
	var searchTerm = null;
	var results = null;
	var currentSearchTerm = null;
	var keepSuggestions = false;
	var executeSearch=true;
	var loading=false;
	
	function changedSearch(elem){
		if(executeSearch){
			currentSearchTerm = elem.value;

			if(!isUndefined(currentSearchTerm)){
				document.getElementById('productID').value = '';	

				if(isAJAXSearchRequired()){
					searchTerm = currentSearchTerm;
					populateResults();
				} else {
					updateSelections()
				}
			}
		} else {
			executeSearch = true;
		}
	}
	
	
	function updateSelections(){
		var filteredResults = {};
		if(currentSearchTerm.length > 2) {
			populateFilteredResults(filteredResults);
			updateSuggestions(filteredResults);
			checkMatch(filteredResults);
		} else {
			results = null;
			searchTerm = null;
			removeSuggestions();
		}
	}
	
	function isAJAXSearchRequired(){
		if(!isUndefined(searchTerm) && currentSearchTerm.length > 2){
			return isSearchCriteriaDifferent();
		} else if(currentSearchTerm.length > 2) {
			return true;
		}
		return false;
	}
	
	function checkMatch(filteredResults){
		if(!isUndefined(filteredResults)){
			for(var key in filteredResults){
				if(filteredResults[key].toLowerCase() == currentSearchTerm.toLowerCase()){
					loadSelection(key, filteredResults[key]);
				}
			}
		}
	}
	
	function populateFilteredResults(filteredResults){
		if(!isUndefined(results)){
			for (var key in results) {
				if(!isUndefined(results[key])){
					if(results[key].toLowerCase().indexOf(currentSearchTerm.toLowerCase()) != -1){
						filteredResults[key] = results[key];
					}
				}
			}
		}
	}
	
	function checkAccomValidations(){
		var productID = document.getElementById('productID').value;
		var productName = document.getElementById('accommodationSearch').value;
		if(!isUndefined(productID) && !isUndefined(productName) && productID != '' && productName != ''){
			return true;
		} else {
			document.getElementById('accommodationSearchError').innerHTML = '<p>Sorry, no matches could be found.</p><p><strong>Suggestions:</strong><br />Make sure you select a hotel from the suggestions list and then select \'Go\'</p>';
			return false;
		}
	}
	
	function updateSuggestions(filteredResults){
		var htmlTxt = "";
		if(!loading){
			if(!isUndefined(filteredResults) && !isUndefined(getMapSize(filteredResults)) && getMapSize(filteredResults) > 0){
				htmlTxt = '<div style="height:200px; width:200px; background:#fff; z-index:99; margin-top:-8px; position:absolute; overflow:scroll; overflow-x: hidden;" id="sugResCont"><ul style="list-style:none; font-size:0.8em; text-align:left;">';
				for (var key in filteredResults) {
					var accomName = getHTMLFormattedAccom(filteredResults[key]);
					htmlTxt = htmlTxt + '<li class="suggestionsA"><a name="suggestionsLinks" href="Javascript:initializeLinks();" id="'+key+'">' + accomName + '</a><br /></li>';
				}
				htmlTxt = htmlTxt + '</ul></div>';

			} else {
				htmlTxt = '<div style="height:100px; width:200px; font-size:0.8em; background:#fff; z-index:99; margin-top:-10px; position:absolute; overflow:scroll; overflow-x: hidden;" id="sugResCont"><span class="noSuggestions"><em>No matches found</em></span></div>';
			}
		} else {
			htmlTxt = '<div style="height:100px; width:200px; font-size:0.8em; background:#fff; z-index:99; margin-top:-10px; position:absolute; overflow:scroll; overflow-x: hidden;" id="sugResCont"><span class="noSuggestions"><em>Loading suggestions...</em></span></div>';
		}
		
		document.getElementById('suggestions').innerHTML = htmlTxt;
		initializeLinks();
	}
	
	
	function getHTMLFormattedAccom(str){
		if(str.toLowerCase().indexOf(currentSearchTerm.toLowerCase()) != -1){
			var currentSearchTermStartPoint = str.toLowerCase().indexOf(currentSearchTerm.toLowerCase())
			var currentSearchTermEndPoint = currentSearchTerm.length + currentSearchTermStartPoint;
			var searchStr = str.substring(currentSearchTermStartPoint, currentSearchTermEndPoint);
			if(!isUndefined(searchStr)){
				str = str.replace(searchStr, "<strong>"+searchStr+"</strong>");
			}
		}
		return str;
	}
	
	
	
	function initializeLinks(){
		var links = document.getElementsByName('suggestionsLinks');
		var suggestionsDiv = document.getElementById('sugResCont');
		if(!isUndefined(links)){
			for(var i = 0; i < links.length; i++){
				if(!isUndefined(links[i])){
					links[i].onmousedown = function(){
						keepSuggestions=false;
						loadSelection(this.id, this.innerHTML);
						removeSuggestions()
						return false;
					}
				}
			}
		}
		if(!isUndefined(suggestionsDiv)){
			suggestionsDiv.onmousedown = function(){
				keepSuggestions=true;
			}
			
			suggestionsDiv.onmouseout = function(){
				keepSuggestions=false;
				executeSearch=false
				var inputBox = document.getElementById('accommodationSearch');
				if(!isUndefined(inputBox)){
					inputBox.focus();
				}
			}
		}
	}
	

	var illegalTerms = {"<strong>": "", "</strong>": "", "&amp;": "&", "<STRONG>": "", "</STRONG>": ""};

	function removeHTML(str){
		for(var key in illegalTerms){
			str = str.replace(key, illegalTerms[key]);
		}
		return str;
	}
	
	function getMapSize(map){
		if(!isUndefined(map)){
			var i = 0;
			for (var key in map) {
				++i;
			}
			return i;
		}
		return null;
	}
	
	function loadSelection(elemID, elemText){
		if(!isUndefined(elemID) && !isUndefined(elemText)){
			document.getElementById('productID').value = elemID;
			document.getElementById('accommodationSearch').value = removeHTML(elemText);
		}
	}
	
	function isSearchCriteriaDifferent(){
		if(currentSearchTerm.indexOf(searchTerm) == 0){
			return false;
		} else {
			return true;
		}
	}
	function removeSuggestions(){
		if(!keepSuggestions && !isUndefined(document.getElementById('sugResCont'))){
			document.getElementById('sugResCont').style.display = "none";
		}
	}
	function displaySuggestions(){
		if(!isUndefined(document.getElementById('sugResCont'))){
			changedSearch(document.getElementById('accommodationSearch'));
			document.getElementById('sugResCont').style.display = "block";
		}
	}

	function populateResults(){
		loading=true;
		AjaxAccommodationSearch.getAccommodationsForSearchTerm(currentSearchTerm, createResults);
	}
	
	
	function createResults(data){
		loading=false;
		results = data;
		updateSelections();
	}
	function pause(milliseconds) {
		var dt = new Date();
		while ((new Date()) - dt <= milliseconds) { /* Do nothing */ }
	}

	function isUndefined(elem){
		if(typeof(elem) !== 'undefined' && elem != null) {
			return false;
		} else {
			return true;
		}
	}	
	   	function onTourOpChange() { 
	        var tourOps = dwr.util.getValue("tourOpsSelect");
	        AjaxSearchTools.populateDestinationsForTourOps(tourOps, updateReviewDestinations);
	        AjaxSearchTools.populateReviewResorts("","", updateReviewResorts);
	      }
	
	       // Refreshing resorts drop-down
	      function updateReviewDestinations(data) {
	
	         dwr.util.removeAllOptions("destinationSelect");
	         dwr.util.addOptions("destinationSelect", data);
	         //calling this because on change of destination to default "select destination"
	   //should also change the accommodation in addition to resorts.
	   	onReviewResortChange();
      		}
	
	
	
	
function checkTravelPound()
{
    
	var testValidation = false;
	var TCCard = document.getElementById('thomasCookCreditCardNumId').value;
	var intIndexOfMatch = TCCard.indexOf(' ');
	while (intIndexOfMatch != -1){
		TCCard = TCCard.replace( ' ', '' );
	    intIndexOfMatch = TCCard.indexOf( ' ' );
	}
	
	var isNumericFlag=isNumeric(TCCard);
	if(isNumericFlag==false){
		if(document.getElementById("TCnoAvailableAmountError"))
			document.getElementById("TCnoAvailableAmountError").style.display = 'none';

		if(document.getElementById("TCUnidentifiedCardError"))
			document.getElementById("TCUnidentifiedCardError").style.display = 'none';

		if(document.getElementById("TCInvalidLenghtError"))
			document.getElementById("TCInvalidLenghtError").style.display ='none';

		if(document.getElementById("TCAlphaNumericError"))
			document.getElementById("TCAlphaNumericError").style.display ='block';

		if(document.getElementById("travelPoundsRedeemInfo"))
			document.getElementById("travelPoundsRedeemInfo").style.display = 'none';

		testValidation=false;
	}
	else {	


			var validationFlag=thomasCreditCardLengthValidation(TCCard);		
			if(validationFlag==true)
			{
				if(document.getElementById("TCnoAvailableAmountError"))
					document.getElementById("TCnoAvailableAmountError").style.display = 'none';

				if(document.getElementById("TCUnidentifiedCardError"))
					document.getElementById("TCUnidentifiedCardError").style.display = 'none';

				if(document.getElementById("TCInvalidLenghtError"))
					document.getElementById("TCInvalidLenghtError").style.display ='none';

				if(document.getElementById("TCAlphaNumericError"))
					document.getElementById("TCAlphaNumericError").style.display ='none';

				if(document.getElementById("travelPoundsRedeemInfo"))
			        document.getElementById("travelPoundsRedeemInfo").style.display = 'none';

				AjaxPaymentTools.getTPEnquiryOutput(TCCard,populateAvailableTravelPound);
				testValidation = false;
			}
			else
			{
				if(document.getElementById("TCnoAvailableAmountError"))
					document.getElementById("TCnoAvailableAmountError").style.display = 'none';

				if(document.getElementById("TCUnidentifiedCardError"))
					document.getElementById("TCUnidentifiedCardError").style.display = 'none';

				if(document.getElementById("TCInvalidLenghtError"))
					document.getElementById("TCInvalidLenghtError").style.display ='block';

				if(document.getElementById("TCAlphaNumericError"))
					document.getElementById("TCAlphaNumericError").style.display ='none';

				if(document.getElementById("travelPoundsRedeemInfo"))
			        document.getElementById("travelPoundsRedeemInfo").style.display = 'none';

				testValidation=false;
			}
			 
    }
	return testValidation;
}


function populateAvailableTravelPound(data)
{

		if(data!=null && data != 'ERROR' && data != 'INVALID_CARD')
		{

			if(document.getElementById("TCnoAvailableAmountError"))
			    document.getElementById("TCnoAvailableAmountError").style.display = 'none';

			if(document.getElementById("TCUnidentifiedCardError"))
				document.getElementById("TCUnidentifiedCardError").style.display = 'none';

			if(document.getElementById("TCInvalidLenghtError"))
				document.getElementById("TCInvalidLenghtError").style.display ='none';

			if(document.getElementById("TCAlphaNumericError"))
				document.getElementById("TCAlphaNumericError").style.display ='none';

			document.getElementById("travelPoundsRedeemInfo").style.display = 'block';
			data = new Number(data);
			document.getElementById('travelPoundsRedeemBalanceIdText').innerHTML = '<p>Your available Travel Pounds balance is: £ ' + data.toFixed(2) +'</p>' ;
			document.getElementById('travelPoundsRedeemBalanceId'). value = data;

		}

		else
		{
			if(data == 'INVALID_CARD'){
				if(document.getElementById("TCnoAvailableAmountError"))
				document.getElementById("TCnoAvailableAmountError").style.display = 'none';

				if(document.getElementById("TCUnidentifiedCardError"))
				document.getElementById("TCUnidentifiedCardError").style.display = 'block';

				if(document.getElementById("TCInvalidLenghtError"))
					document.getElementById("TCInvalidLenghtError").style.display ='none';

				if(document.getElementById("TCAlphaNumericError"))
					document.getElementById("TCAlphaNumericError").style.display ='none';

				if(document.getElementById("travelPoundsRedeemInfo"))
			         document.getElementById("travelPoundsRedeemInfo").style.display = 'none';

			}
			if(data == 'ERROR' || data == null){
				if(document.getElementById("TCnoAvailableAmountError"))
				document.getElementById("TCnoAvailableAmountError").style.display = 'block';

				if(document.getElementById("TCUnidentifiedCardError"))
				document.getElementById("TCUnidentifiedCardError").style.display = 'none';

				if(document.getElementById("TCInvalidLenghtError"))
					document.getElementById("TCInvalidLenghtError").style.display ='none';

				if(document.getElementById("TCAlphaNumericError"))
					document.getElementById("TCAlphaNumericError").style.display ='none';

				if(document.getElementById("travelPoundsRedeemInfo"))
			        document.getElementById("travelPoundsRedeemInfo").style.display = 'none';

			}
		}

}



function thomasCreditCardLengthValidation(TCCard)
{
	var length=TCCard.length;
	
	if(length >15)
		return true;
		else
	   return false;
}


/**
 * start --> functions specific to - Hotel Search Default FF 10261
 **/


function populateDestinationDropDownForDestination(selectedDestination) {
        var profile = dwr.util.getValue("propositionSelect");		
		setTimeout("delayInAjaxCallOfDestination("+profile+","+selectedDestination+")",1000);	
		setTimeout("delayInDestination("+selectedDestination+")",1600);
		setTimeout("delayInAjaxCallOfResort("+selectedDestination+","+profile+")",2100);

 }

function populateDestinationDropDownForResort(selectedDestination,selectedResort) {
        var profile = dwr.util.getValue("propositionSelect");
		populateDestinationDropDownForDestination(selectedDestination);      
		setTimeout("delayInAjaxCallOfResort("+selectedDestination+","+profile+")",2800);
		AjaxSearchTools.populateDepartures(selectedDestination, profile, updateDepartures);
		AjaxSearchTools.populateDefaultDeparture(selectedDestination, updateDefaultDept);
		setTimeout("delayInResort("+selectedResort+")",3000);



 }

function populateDestinationDropDownForAccom(propositionId,selectedDestination,selectedResort,selectedAccom){
		var profile = propositionId;
		setTimeout("delayInAjaxCallOfDestination("+profile+","+selectedDestination+")",2200);
		document.getElementById('propositionSelect').value = propositionId;
		setTimeout("delayInDestination("+selectedDestination+")",4300);
		document.getElementById('destinationSelect').value = selectedDestination;
		setTimeout("delayInAjaxCallOfResort("+selectedDestination+","+profile+")",5000);
		AjaxSearchTools.populateResorts(selectedDestination, profile, updateResorts);
		setTimeout("delayInResort("+selectedResort+")",6000);
		AjaxSearchTools.populateDepartures(selectedDestination, profile, updateDepartures);
		AjaxSearchTools.populateDefaultDeparture(selectedDestination, updateDefaultDept);
		document.getElementById('destinationSelect').value = selectedDestination;
		document.getElementById('resortSelect').value= selectedResort;		
		document.getElementById('accomSelect').value= selectedAccom;
}

function delayInAjaxCallOfDestination(profile,selectedDestination){
	  AjaxSearchTools.populateDestinations(profile, updateDestinations);	
}

function delayInAjaxCallOfResort(selectedDestination,profile){
	  AjaxSearchTools.populateResorts(selectedDestination, profile, updateResorts);
}
function delayInDestination(selectedDestination){
	  document.getElementById('destinationSelect').value = selectedDestination;
}

function delayInResort(selectedResort){
	  document.getElementById('resortSelect').value= selectedResort;
}
function delayInAccom(selectedAccom){
	  document.getElementById('accomSelect').value= selectedAccom;
}



     // Javascript function called on change of resort drop-down,
	// to populate hotels resorts.
    function onResortChange(browsePageIsTrue) {
		   
		   if(browsePageIsTrue == 'true'){
			
			var proposition = dwr.util.getValue("propositionSelect");
			var destination = dwr.util.getValue("destinationSelect");
			var resort = dwr.util.getValue("destinationSelect");
			AjaxSearchTools.populateHotels(destination, proposition, resort, updateHotel);
		   }
           
        
		}
    	

	// Refreshing hotel drop-down
    function updateHotel(data) {
        dwr.util.removeAllOptions("accomSelect");
        dwr.util.addOptions("accomSelect", data);
        }
 

    /**
     * end --> functions specific to - Hotel Search Default FF 10261
     **/