var initialized = true;
var selectedTourGuid = "";
var tourDepDate = "";

var dateInfoString = "";
var discountDataString = "";
var tourDate = "";
var supplementalFee = 0;
var pricePerPerson = 0;
var internalAirfare = 0;
var numTravelers = 1;
var singleSupplementChosen = false;
var discount = 0;
var insurancevalue = 0;
var accomUpgPricePerPerson = 0;
var accomUpgSupplementalFee = 0;
var dynamicDiscountsTotal = 0;

function setAllTourOptions(tourStrings) {
    var allOptions = tourStrings.replace(/^\s+/, '');

    // returning the list of dates, price per person, single supplement price, airfare like
    // April 12, 2009#$4,198#$650#|April 19, 2009#$4,198#$650#|....
    if (allOptions.length > 0) {
        dateInfoString = allOptions;
    }
}

function setDiscountDataString(discountStrings) {
    var allOptions = discountStrings.replace(/^\s+/, '');

    if (allOptions.length > 0) {
        discountDataString = allOptions;
    }
}

// The tour guid and tour date can be passed into the booking form.
// If they are, values for prices need to be initialized
// so call init
function initForm(selectedGuid, selectedDepDate) {
  if (selectedGuid != 'null') {
	selectedTourGuid = selectedGuid;
	tourDepDate = selectedDepDate;
    //getDepartureDates(document.bookingForm.toursOptions);
  }
}

function initFormNew(selectedGuid, selectedDepDate) {
  if (selectedGuid != 'null') {
	selectedTourGuid = selectedGuid;
	tourDepDate = selectedDepDate;

        /* On Travcoa, this ajax call is not working. The logic to load the
         * departure dates has been moved to travcoaBookingFormCruise.jsp */
        //getDepartureDatesNew(document.bookingForm.toursOptions);

	displayHideAddlTravInfo(document.bookingForm.numTravelersOptions);
  }
}

function initFormWithAccomUpgrades(selectedGuid, selectedDepDate, inAccomUpgPricePerPerson, inAccomUpgSupplementalFee) {
  if (selectedGuid != 'null') {
	selectedTourGuid = selectedGuid;
	tourDepDate = selectedDepDate;
    if (inAccomUpgPricePerPerson!=null && inAccomUpgPricePerPerson != "") {
	   accomUpgPricePerPerson = inAccomUpgPricePerPerson.replace('$','').replace(',','');
    }

    if (inAccomUpgSupplementalFee!=null && inAccomUpgSupplementalFee != "") {
	   accomUpgSupplementalFee = inAccomUpgSupplementalFee.replace('$','').replace(',','');
    }

    /* On Travcoa, this ajax call is not working. The logic to load the
     * departure dates has been moved to travcoaBookingFormCruise.jsp */
    //getDepartureDatesNew(document.bookingForm.toursOptions);

    displayHideAddlTravInfo(document.bookingForm.numTravelersOptions);
  }
}


  function getRequestParameter(paramerterName) {
    var queryString = window.top.location.search.substring(1);
    var parameterName = paramerterName + "=";
    var parameterValue = "";
    if (queryString.length > 0) {
      // Find the beginning of the string 
      var begin = queryString.indexOf(parameterName);      
      // If the parameter name is not found, skip it, otherwise return the value      
      if ( begin != -1 ) {         
        // Add the length (integer) to the beginning         
        begin += parameterName.length;         
        // Multiple parameters are separated by the "&" sign         
        var end = queryString.indexOf ( "&" , begin );      
	    if (end == -1 ) {         
          end = queryString.length;    
        }
        parameterValue = queryString.substring (begin, end);
      }
      return parameterValue;
    }
  }


	//*************************************************************************************	
	// The following two functions - AJAX function getToursForBookNowPage  is
	// for the "Country" and "Tour Name" Select Boxes on the Book Now page
	// 
	// Makes an AJAX call to /vgn-ext-templating/travcoa/jsp/travcoaGetSearchToursFromCountry.jsp?countryGUID=" + selectedCountryGuid
    // when the user selects a country from the drop down.  It returns the list of individual tours for
    // that country.  If there is only a single tour, then it redirects directly to that tour.
    function getToursForBookNowPage(countryOptionsSelect) {
	    var xmlHttp;
	    try {
		// Firefox, Opera 8.0+, Safari
		    xmlHttp=new XMLHttpRequest();
	    } catch (e) {
		// Internet Explorer
		    try {
		        xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
		    } catch (e) {
			    try {
				    xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
			    } catch (e) {
				    alert("Your browser does not support AJAX!");
				    return false;
			    }
	        }
	    }
	    xmlHttp.onreadystatechange=function() {
		    if(xmlHttp.readyState==4) {
			    document.bookingForm.toursOptions.options.length = 0;
			    document.bookingForm.toursOptions.options[0] = new Option("Select a Tour","blank");
			    document.bookingForm.tourDatesOptions.options.length = 0;
			    document.bookingForm.tourDatesOptions.options[0] = new Option("Select a Departure Date","blank");
			    // get the response from cwGetSearchToursFromCountry.jsp and trim spaces
			    var allOptions=xmlHttp.responseText.replace(/^\s+/, '');
			    // returning the list of tour name and urls in a list like
			    // Walking Italy|url,Walking Paris,url|....
			    if (allOptions.length > 0) {
				    var optionList = allOptions.split("|");
				    for (i=0; i < optionList.length; i++) {
					    // split the tour name from the url
					    var indOpt = optionList[i].split("#");
					    var opt = indOpt[0];
					    var val = indOpt[1];
					    document.bookingForm.toursOptions.options[i + 1] = new Option(opt,val);
			    	}
			    } 		
		    }
	    }
	    var selectedCountryGuid = countryOptionsSelect.options[countryOptionsSelect.selectedIndex].value;
		
	    if (selectedCountryGuid.length != 40) {
		    document.bookingForm.toursOptions.options.length = 0;
		    document.bookingForm.tourDatesOptions.options.length = 0;
		    alert (selectedCountryGuid + "  guid length: " + selectedCountryGuid.length );
		    return true;
	    }
		
		document.getElementById("tourName").innerHTML = "&nbsp;";
		document.getElementById("selectedDepDate").innerHTML = "&nbsp;";
		document.getElementById("numTravelers").innerHTML = "1";
		document.getElementById("pricePerPerson").innerHTML = "&nbsp;";
		document.getElementById("internalAirfare").innerHTML = "&nbsp;";
		document.getElementById("supplementalFee").innerHTML = "&nbsp;";
		document.getElementById("grossTourPrice").innerHTML = "&nbsp;";
		
	    var url = "/vgn-ext-templating/travcoa/jsp/travcoaGetSearchToursFromCountry.jsp?countryGUID=" + selectedCountryGuid;
	    url = url + "&isBookNowPage=true";
	    
	    xmlHttp.open("POST",url ,true);
	    xmlHttp.send(null);
    }
	
	
	// *************************************************************************************	
	// The following two functions - AJAX function getDepartureDates  is
	// for the  "Tour Date" Select Box on the Book Now page
	// 
	// Makes an AJAX call to /vgn-ext-templating/travcoa/jsp/travcoaGetSearchDatesFromTour.jsp?tourGUID=" + tour
    // when the user selects a country from the drop down.  It returns the list of dates and info for
    // that tour.  Returns date, price per person, single supplement price, airfare in the following form:
    // April 12, 2009#$4,198#$650#|April 19, 2009#$4,198#$650#|April 26, 2009#$4,198#$650#|
    function getDepartureDates(tourOptionsSelect) {
	    var xmlHttp;
	    try {
		// Firefox, Opera 8.0+, Safari
		    xmlHttp=new XMLHttpRequest();
	    } catch (e) {
		// Internet Explorer
		    try {
		        xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
		    } catch (e) {
			    try {
				    xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
			    } catch (e) {
				    alert("Your browser does not support AJAX!");
				    return false;
			    }
	        }
	    }
	    xmlHttp.onreadystatechange=function() {
		    if(xmlHttp.readyState==4) {
			    document.bookingForm.tourDatesOptions.options.length = 0;
			    document.bookingForm.tourDatesOptions.options[0] = new Option("Select a Departure Date","blank");
			    // get the response from cwGetSearchToursFromCountry.jsp and trim spaces
			    var allOptions=xmlHttp.responseText.replace(/^\s+/, '');
			    // returning the list of dates, price per person, single supplement price, airfare like
			    // April 12, 2009#$4,198#$650#|April 19, 2009#$4,198#$650#|....
			    if (allOptions.length > 0) {
			    	dateInfoString = allOptions;
				    var optionList = allOptions.split("|");
				    var numTokens = optionList.length - 1;
				    for (i=0; i < numTokens; i++) {
				    	var indOpt = optionList[i].split("#");
					    var opt = indOpt[0];
					    var val = indOpt[0];
					    document.bookingForm.tourDatesOptions.options[i + 1] = new Option(opt,val);
					    if (!initialized && tourDepDate != 0) {
					    	if (document.bookingForm.tourDatesOptions.options[i + 1].value == tourDepDate) {
					          document.bookingForm.tourDatesOptions.options[i + 1].selected=true;
							  setDate(document.bookingForm.tourDatesOptions);
					    	}
						}
			    	}
			    }
			    // initiailized is used to know if the date was passed in as a parameter.  After
			    // the first time through, set this to false.
			    if (!initialized) {
			    	initialized = true;
			    }
		    }
	    }
	    var selectedTourGuid = tourOptionsSelect.options[tourOptionsSelect.selectedIndex].value;
	    selectedTourGuid = selectedTourGuid.replace("\n", '');
	    var selectedTourName = tourOptionsSelect.options[tourOptionsSelect.selectedIndex].text;
	    var tourNameTD = document.getElementById("tourName");
	    tourNameTD.innerHTML = selectedTourName;
	    // + "&nbsp;&nbsp;<a href=\"#\" onclick=document.bookingForm.toursOptions.focus()>"
        //  + "<span class=\"orangebackground\" style=\"padding: 2px\">EDIT</span></a>";
	    document.bookingForm.TOUR_TITLE.value = selectedTourName;
	    var selectedDepDateTD = document.getElementById("selectedDepDate");
	    selectedDepDateTD.innerHTML = "&nbsp;";
	    var pricePerPersonTD = document.getElementById("pricePerPerson");
	    pricePerPersonTD.innerHTML = "&nbsp;";
	    var grossTourPriceTD = document.getElementById("grossTourPrice");
	    grossTourPriceTD.innerHTML = "&nbsp;";
	    
	    if (selectedTourGuid.length != 40) {
		    document.bookingForm.tourDatesOptions.options.length = 0;
		    alert (selectedTourGuid + "  guid length: " + selectedTourGuid.length );
		    return true;
	    }
	    
	    var url = "/vgn-ext-templating/travcoa/jsp/travcoaGetSearchDepDatesFromTour.jsp?tourGUID=" + selectedTourGuid;

	    xmlHttp.open("POST",url ,true);
	    xmlHttp.send(null);
    }
    

   function getDepartureDatesNew(tourOptionsSelect) {
	    var xmlHttp;
	    try {
		// Firefox, Opera 8.0+, Safari
		    xmlHttp=new XMLHttpRequest();
	    } catch (e) {
		// Internet Explorer
		    try {
		        xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
		    } catch (e) {
			    try {
				    xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
			    } catch (e) {
				    alert("Your browser does not support AJAX!");
				    return false;
			    }
	        }
	    }
	    xmlHttp.onreadystatechange=function() {
		    if(xmlHttp.readyState==4) {
			    document.bookingForm.tourDatesOptions.options.length = 0;
			    document.bookingForm.tourDatesOptions.options[0] = new Option("Select a Departure Date","blank");
			    // get the response from cwGetSearchToursFromCountry.jsp and trim spaces
			    var allOptions=xmlHttp.responseText.replace(/^\s+/, '');
			    // returning the list of dates, price per person, single supplement price, airfare like
			    // April 12, 2009#$4,198#$650#|April 19, 2009#$4,198#$650#|....
			    if (allOptions.length > 0) {
			    	dateInfoString = allOptions;
				    var optionList = allOptions.split("|");
				    var numTokens = optionList.length - 1;
				    for (i=0; i < numTokens; i++) {
				    	var indOpt = optionList[i].split("#");
					    var opt = indOpt[0];
					    var val = indOpt[0];
					    document.bookingForm.tourDatesOptions.options[i + 1] = new Option(opt,val);
					    if (!initialized && tourDepDate != 0) {
					    	if (document.bookingForm.tourDatesOptions.options[i + 1].value == tourDepDate) {
					          document.bookingForm.tourDatesOptions.options[i + 1].selected=true;
							  setDate(document.bookingForm.tourDatesOptions);
					    	}
						}
			    	}
			    }
			    // initiailized is used to know if the date was passed in as a parameter.  After
			    // the first time through, set this to false.
				if (!initialized) {
			    	initialized = true;
			    }

		    }
	    }
	    var selectedTourGuid = tourOptionsSelect.value;
	    selectedTourGuid = selectedTourGuid.replace("\n", '');	    
	    var selectedDepDateTD = document.getElementById("selectedDepDate");
	    selectedDepDateTD.innerHTML = "&nbsp;";
	    var pricePerPersonTD = document.getElementById("pricePerPerson");
	    pricePerPersonTD.innerHTML = "&nbsp;";
	    var grossTourPriceTD = document.getElementById("grossTourPrice");
	    grossTourPriceTD.innerHTML = "&nbsp;";
	    
	    if (selectedTourGuid.length != 40) {
		    document.bookingForm.tourDatesOptions.options.length = 0;
		    alert (selectedTourGuid + "  guid length: " + selectedTourGuid.length );
		    return true;
	    }
	    
	    var url = "/vgn-ext-templating/travcoa/jsp/travcoaGetSearchDepDatesFromTour.jsp?tourGUID=" + selectedTourGuid;

	    xmlHttp.open("POST",url ,true);
	    xmlHttp.send(null);
    }
function acceptinsurance(accept) {
	//applyDiscounts();
	getDynamicDiscounts();
	/*
	if (document.bookingForm.acceptinsure[1].checked) {
	    tb_show("","#TB_inline?height=400&width=600&inlineId=declineInsurance","");
	}
	*/
}
    function setDate(tourDatesSelect) {

       	var selectedDate = tourDatesSelect.options[tourDatesSelect.selectedIndex].text;
		var now = new Date();  
		var thisYear= now.getFullYear();
		var selectedDateReal = new Date(selectedDate);
		var selectedYear=selectedDateReal.getFullYear();
		var dec15 = new Date(thisYear, 12, 15);
		var nextYear=thisYear+1;
		var day90=new Date(now.getFullYear(),now.getMonth(),now.getDate()+90);

		var savingsAll = document.getElementById("savingsAll");
		var savings = document.getElementById("savings");
		var savingslabel = document.getElementById("savingslabel");
		var continent = document.getElementById("continent");
		var continentlabel = document.getElementById("continentlabel");
		var subtotal = document.getElementById("subtotal");
		var subtotallabel = document.getElementById("subtotallabel");

		var selectedDepDateTD = document.getElementById("selectedDepDate");
   	    selectedDepDateTD.innerHTML = selectedDate;
   	    // + "&nbsp;&nbsp;<a href=\"#\" onclick=document.bookingForm.tourDatesOptions.focus()>";
        //  + "<span class=\"orangebackground\" style=\"padding: 2px\">EDIT</span></a>";
   	    
		if (dateInfoString.length > 0) {
   	    	var allDateInfo = dateInfoString.split("|");
		    for (var i = 0; i < allDateInfo.length; i++) {
		    	if (allDateInfo[i].indexOf(selectedDate) > -1) {
				    // returning the list of dates, price per person, single supplement price, airfare like
				    // April 12, 2009#$4,198#$650#|April 19, 2009#$4,198#$650#|....
			    	var indOpt = allDateInfo[i].split("#");
				    tourDate = indOpt[0];
				    if (!initialized && accomUpgPricePerPerson!=0) {
					   pricePerPerson = accomUpgPricePerPerson;
				    } else {
					   pricePerPerson = indOpt[1].replace('$','').replace(',','');
					}
					if (!initialized && accomUpgSupplementalFee!=0) {
					   supplementalFee = accomUpgSupplementalFee;
					} else {
					   supplementalFee = indOpt[2].replace('$','').replace(',','');
					}				    
				    internalAirfare = indOpt[3].replace('$','').replace(',','');
		    		break;
		    	}
		    }
   	    }


   	    if (initialized && document.bookingForm.accommodationUpgrade!=null) {
			document.bookingForm.accommodationUpgrade.selectedIndex=0;
	    }
		document.getElementById("pricePerPerson").innerHTML = CurrencyFormatted(pricePerPerson);
   	    document.bookingForm.TOUR_PRICE_PER_PERSON.value = CurrencyFormatted(pricePerPerson);
   		document.getElementById("internalAirfare").innerHTML = CurrencyFormatted(internalAirfare);
   		document.bookingForm.INTRA_TOUR_AIRFARE.value = CurrencyFormatted(internalAirfare);
   		setSingleSupplement();

		calculateTotal();
        //applyDiscounts();
		getDynamicDiscounts();
        
	   }

	   function setAccommodationUpgradePrices(inPricePerPerson, inSupplementalFee) {

		   if (inPricePerPerson!=null && inPricePerPerson != "") {
			   pricePerPerson = inPricePerPerson.replace('$','').replace(',','');
		   }

		   if (inSupplementalFee!=null && inSupplementalFee != "") {
			   supplementalFee = inSupplementalFee.replace('$','').replace(',','');
		   }

		   document.getElementById("pricePerPerson").innerHTML = CurrencyFormatted(pricePerPerson);
   		   document.bookingForm.TOUR_PRICE_PER_PERSON.value = CurrencyFormatted(pricePerPerson);
		   setSingleSupplement();

		   calculateTotal();
		   //applyDiscounts();
		   getDynamicDiscounts();

	   }
       
       function displayHideAddlTravInfo(numTravelersSelect)  {
       	var numberoftravelers = numTravelersSelect.options[numTravelersSelect.selectedIndex].value;
       	
       	var addlTravDiv = document.getElementById("additionalTraveler");
		var addlTravDiv2 = document.getElementById("additionalTraveler2");
       	var singleTravTD = document.getElementById("singleTrav");
		var numTravelersTD = document.getElementById("numTravelers");
		var grossTourPriceLabel = document.getElementById("grossTourPriceLabel");
		grossTourPriceLabel.innerHTML = "Gross Tour Price"; //default - it changes only for 3 or more travelers
       	
		
		if ( numberoftravelers == "3")  {
			alert("Additional travelers' information will be collected at the time of reservation request confirmation with a Journey Consultant");
			document.bookingForm.FIRSTNAME1.value = "";
       		document.bookingForm.LASTNAME1.value = "";
       		document.bookingForm.ADDRESS1.value = "";
   	    	document.bookingForm.APT1.value = "";
   	    	document.bookingForm.CITY1.value = "";
   	    	document.bookingForm.STATE1.value = "";
   	    	document.bookingForm.ZIP1.value = "";
   	    	document.bookingForm.COUNTRY1.selectedIndex = 0;
   	    	document.bookingForm.sameInfoCheckbox.checked = false;
			document.bookingForm.sevenContinentsClubMember1.checked=false;
			document.bookingForm.returnedFromTravcoaTripInLast90Days1.checked=false;
			document.bookingForm.FIRSTNAME2.value = "";
	       	document.bookingForm.LASTNAME2.value = "";
	       	document.bookingForm.ADDRESS2.value = "";
   	    	document.bookingForm.APT2.value = "";
   	    	document.bookingForm.CITY2.value = "";
   	    	document.bookingForm.STATE2.value = "";
   	    	document.bookingForm.ZIP2.value = "";
   	    	document.bookingForm.COUNTRY2.selectedIndex = 0;
   	    	document.bookingForm.sameInfoCheckbox2.checked = false;
			document.bookingForm.sevenContinentsClubMember2.checked=false;
			document.bookingForm.returnedFromTravcoaTripInLast90Days2.checked=false;
   	    	addlTravDiv.style.display = "none";
			addlTravDiv2.style.display = "none";
   	    	singleTravTD.style.display = "none";
   	    	numTravelers = 1;
			numTravelersTD.innerHTML = "3 or more";
			grossTourPriceLabel.innerHTML = "Gross Tour Price Per Person";
			resetSingleSupplement();	

		} else if ( numberoftravelers == "1")  {
       		document.bookingForm.FIRSTNAME1.value = "";
       		document.bookingForm.LASTNAME1.value = "";
       		document.bookingForm.ADDRESS1.value = "";
   	    	document.bookingForm.APT1.value = "";
   	    	document.bookingForm.CITY1.value = "";
   	    	document.bookingForm.STATE1.value = "";
   	    	document.bookingForm.ZIP1.value = "";
   	    	document.bookingForm.COUNTRY1.selectedIndex = 0;
   	    	document.bookingForm.sameInfoCheckbox.checked = false;
			document.bookingForm.sevenContinentsClubMember1.checked=false;
			document.bookingForm.returnedFromTravcoaTripInLast90Days1.checked=false;
			document.bookingForm.FIRSTNAME2.value = "";
	       	document.bookingForm.LASTNAME2.value = "";
	       	document.bookingForm.ADDRESS2.value = "";
   	    	document.bookingForm.APT2.value = "";
   	    	document.bookingForm.CITY2.value = "";
   	    	document.bookingForm.STATE2.value = "";
   	    	document.bookingForm.ZIP2.value = "";
   	    	document.bookingForm.COUNTRY2.selectedIndex = 0;
   	    	document.bookingForm.sameInfoCheckbox2.checked = false;
			document.bookingForm.sevenContinentsClubMember2.checked=false;
			document.bookingForm.returnedFromTravcoaTripInLast90Days2.checked=false;
   	    	addlTravDiv.style.display = "none";
			addlTravDiv2.style.display = "none";
   	    	setSingleSupplement();
			singleTravTD.style.display = "block";
   	    	numTravelers = 1;
			numTravelersTD.innerHTML = numTravelers;
        }  else if (numberoftravelers == "2")  	{
       		addlTravDiv.style.display = "block";
			singleTravTD.style.display = "none";
			document.bookingForm.FIRSTNAME2.value = "";
       		document.bookingForm.LASTNAME2.value = "";
       		document.bookingForm.ADDRESS2.value = "";
   	    	document.bookingForm.APT2.value = "";
   	    	document.bookingForm.CITY2.value = "";
   	    	document.bookingForm.STATE2.value = "";
   	    	document.bookingForm.ZIP2.value = "";
   	    	document.bookingForm.COUNTRY2.selectedIndex = 0;
   	    	document.bookingForm.sameInfoCheckbox2.checked = false;
			document.bookingForm.sevenContinentsClubMember2.checked=false;
			document.bookingForm.returnedFromTravcoaTripInLast90Days2.checked=false;
			addlTravDiv2.style.display = "none";
       		numTravelers = 2;
			numTravelersTD.innerHTML = numTravelers;
       		resetSingleSupplement();		
		} else {
			addlTravDiv.style.display = "block";
			addlTravDiv2.style.display = "block";
			singleTravTD.style.display = "none";
			numTravelers = 3;
			numTravelersTD.innerHTML = numTravelers + " or more";
   			resetSingleSupplement();
		}
		
		calculateTotal();
		//applyDiscounts(); 
		getDynamicDiscounts();
       }

	   function displayHideAddlTravInfoWithNoCalc(numTravelersSelect,ijSupplementalFee)  {
       	var numberoftravelers = numTravelersSelect.options[numTravelersSelect.selectedIndex].value;

       	var addlTravDiv = document.getElementById("additionalTraveler");
		var addlTravDiv2 = document.getElementById("additionalTraveler2");
       	var singleTravTD = document.getElementById("singleTrav");
		var numTravelersTD = document.getElementById("numTravelers");
       	
		if ( numberoftravelers == "3")  {
			alert("Additional travelers' information will be collected at the time of reservation request confirmation with a Journey Consultant");
			document.bookingForm.FIRSTNAME1.value = "";
       		document.bookingForm.LASTNAME1.value = "";
       		document.bookingForm.ADDRESS1.value = "";
   	    	document.bookingForm.APT1.value = "";
   	    	document.bookingForm.CITY1.value = "";
   	    	document.bookingForm.STATE1.value = "";
   	    	document.bookingForm.ZIP1.value = "";
   	    	document.bookingForm.COUNTRY1.selectedIndex = 0;
   	    	document.bookingForm.sameInfoCheckbox.checked = false;
			document.bookingForm.sevenContinentsClubMember1.checked=false;
			document.bookingForm.returnedFromTravcoaTripInLast90Days1.checked=false;
			document.bookingForm.FIRSTNAME2.value = "";
	       	document.bookingForm.LASTNAME2.value = "";
	       	document.bookingForm.ADDRESS2.value = "";
   	    	document.bookingForm.APT2.value = "";
   	    	document.bookingForm.CITY2.value = "";
   	    	document.bookingForm.STATE2.value = "";
   	    	document.bookingForm.ZIP2.value = "";
   	    	document.bookingForm.COUNTRY2.selectedIndex = 0;
   	    	document.bookingForm.sameInfoCheckbox2.checked = false;
			document.bookingForm.sevenContinentsClubMember2.checked=false;
			document.bookingForm.returnedFromTravcoaTripInLast90Days2.checked=false;
   	    	addlTravDiv.style.display = "none";
			addlTravDiv2.style.display = "none";
   	    	singleTravTD.style.display = "none";
   	    	numTravelers = 3;
			numTravelersTD.innerHTML = numTravelers + " or more";
			resetSingleSupplement();	

		} else if ( numberoftravelers == "1")  {
		
       		document.bookingForm.FIRSTNAME1.value = "";
       		document.bookingForm.LASTNAME1.value = "";
       		document.bookingForm.ADDRESS1.value = "";
   	    	document.bookingForm.APT1.value = "";
   	    	document.bookingForm.CITY1.value = "";
   	    	document.bookingForm.STATE1.value = "";
   	    	document.bookingForm.ZIP1.value = "";
   	    	document.bookingForm.COUNTRY1.selectedIndex = 0;
   	    	document.bookingForm.sameInfoCheckbox.checked = false;
			document.bookingForm.sevenContinentsClubMember1.checked=false;
			document.bookingForm.returnedFromTravcoaTripInLast90Days1.checked=false;
			document.bookingForm.FIRSTNAME2.value = "";
	       	document.bookingForm.LASTNAME2.value = "";
	       	document.bookingForm.ADDRESS2.value = "";
   	    	document.bookingForm.APT2.value = "";
   	    	document.bookingForm.CITY2.value = "";
   	    	document.bookingForm.STATE2.value = "";
   	    	document.bookingForm.ZIP2.value = "";
   	    	document.bookingForm.COUNTRY2.selectedIndex = 0;
   	    	document.bookingForm.sameInfoCheckbox2.checked = false;
			document.bookingForm.sevenContinentsClubMember2.checked=false;
			document.bookingForm.returnedFromTravcoaTripInLast90Days2.checked=false;
   	    	addlTravDiv.style.display = "none";
			addlTravDiv2.style.display = "none";
   	    	setIJSingleSupplement(ijSupplementalFee);
			singleTravTD.style.display = "block";
   	    	numTravelers = 1;
			numTravelersTD.innerHTML = numTravelers;
        }  else if (numberoftravelers == "2")  	{
       		addlTravDiv.style.display = "block";
			singleTravTD.style.display = "none";
			document.bookingForm.FIRSTNAME2.value = "";
       		document.bookingForm.LASTNAME2.value = "";
       		document.bookingForm.ADDRESS2.value = "";
   	    	document.bookingForm.APT2.value = "";
   	    	document.bookingForm.CITY2.value = "";
   	    	document.bookingForm.STATE2.value = "";
   	    	document.bookingForm.ZIP2.value = "";
   	    	document.bookingForm.COUNTRY2.selectedIndex = 0;
   	    	document.bookingForm.sameInfoCheckbox2.checked = false;
			document.bookingForm.sevenContinentsClubMember2.checked=false;
			document.bookingForm.returnedFromTravcoaTripInLast90Days2.checked=false;
			addlTravDiv2.style.display = "none";
       		numTravelers = 2;
			numTravelersTD.innerHTML = numTravelers;
       		resetSingleSupplement();
       	} else {
			addlTravDiv.style.display = "block";
			addlTravDiv2.style.display = "block";
			singleTravTD.style.display = "none";
			numTravelers = 3;
			numTravelersTD.innerHTML = numTravelers + " or more";
   			resetSingleSupplement();
		}
   	   		
		//calculateTotal();
		//applyDiscounts(); 
       }
       
       function fillAddlTravInfo(sameInfoCheckbox) {
       	if (sameInfoCheckbox.checked) {
   	    	document.bookingForm.ADDRESS1.value = document.bookingForm.ADDRESS0.value;
   	    	document.bookingForm.APT1.value = document.bookingForm.APT0.value;
   	    	document.bookingForm.CITY1.value = document.bookingForm.CITY0.value;
   	    	document.bookingForm.STATE1.value = document.bookingForm.STATE0.value;
   	    	document.bookingForm.ZIP1.value = document.bookingForm.ZIP0.value;
   	    	document.bookingForm.COUNTRY1.selectedIndex = document.bookingForm.COUNTRY0.selectedIndex;
   	    	document.bookingForm.TELEPHONE1.value = document.bookingForm.TELEPHONE0.value;
   	    	document.bookingForm.EMAIL1.value = document.bookingForm.EMAIL0.value;
   	    	document.bookingForm.VERIFYEMAIL1.value = document.bookingForm.VERIFYEMAIL0.value;
       	}  else  {
   	    	document.bookingForm.ADDRESS1.value = "";
   	    	document.bookingForm.APT1.value = "";
   	    	document.bookingForm.CITY1.value = "";
   	    	document.bookingForm.STATE1.value = "";
   	    	document.bookingForm.ZIP1.value = "";
   	    	document.bookingForm.COUNTRY1.value = 'United States';
   	    	document.bookingForm.TELEPHONE1.value = "";
   	    	document.bookingForm.EMAIL1.value = "";
   	    	document.bookingForm.VERIFYEMAIL1.value = "";
   	    }
       }
          function fillAddlTravInfo2(sameInfoCheckbox) {
       	if (sameInfoCheckbox.checked) {
   	    	document.bookingForm.ADDRESS2.value = document.bookingForm.ADDRESS0.value;
   	    	document.bookingForm.APT2.value = document.bookingForm.APT0.value;
   	    	document.bookingForm.CITY2.value = document.bookingForm.CITY0.value;
   	    	document.bookingForm.STATE2.value = document.bookingForm.STATE0.value;
   	    	document.bookingForm.ZIP2.value = document.bookingForm.ZIP0.value;
   	    	document.bookingForm.COUNTRY2.selectedIndex = document.bookingForm.COUNTRY0.selectedIndex;
   	    	document.bookingForm.TELEPHONE2.value = document.bookingForm.TELEPHONE0.value;
   	    	document.bookingForm.EMAIL2.value = document.bookingForm.EMAIL0.value;
   	    	document.bookingForm.VERIFYEMAIL2.value = document.bookingForm.VERIFYEMAIL0.value;
       	}  else  {
   	    	document.bookingForm.ADDRESS2.value = "";
   	    	document.bookingForm.APT2.value = "";
   	    	document.bookingForm.CITY2.value = "";
   	    	document.bookingForm.STATE2.value = "";
   	    	document.bookingForm.ZIP12.value = "";
   	    	document.bookingForm.COUNTRY2.value = 'United States';
   	    	document.bookingForm.TELEPHONE2.value = "";
   	    	document.bookingForm.EMAIL2.value = "";
   	    	document.bookingForm.VERIFYEMAIL2.value = "";
   	    }
       }    

  function setSingleSupplement() {
    var supplementalFeeTD = document.getElementById("supplementalFee");
	var supplementalFeeTextField = document.getElementById("singleTravelerOptions");
	var numTravelersSelect = document.bookingForm.numTravelersOptions;
	var numberoftravelers = numTravelersSelect.options[numTravelersSelect.selectedIndex].value;

    if (numberoftravelers == "1") {
		singleSupplementChosen = true;
		supplementalFeeTextField.value = "Single Supplement - " + CurrencyFormatted(supplementalFee);
		supplementalFeeTD.innerHTML = CurrencyFormatted(supplementalFee);
		document.bookingForm.SINGLE_SUPPLEMENT.value = CurrencyFormatted(supplementalFee);
    } else {
        resetSingleSupplement();
	}
  }
    
  function resetSingleSupplement()  {
    var supplementalFeeTD = document.getElementById("supplementalFee");
	var supplementalFeeTextField = document.getElementById("singleTravelerOptions");
    supplementalFeeTD.innerHTML = "N/A";
    supplementalFeeTextField.value = "";
    document.bookingForm.SINGLE_SUPPLEMENT.value = "";
    singleSupplementChosen = false;
  }

  function setIJSingleSupplement(ijSupplementalFee) {
	var supplementalFeeTD = document.getElementById("supplementalFee");
	var supplementalFeeTextField = document.getElementById("singleTravelerOptions");
	var numTravelersSelect = document.bookingForm.numTravelersOptions;
	var numberoftravelers = numTravelersSelect.options[numTravelersSelect.selectedIndex].value;

    if (numberoftravelers == "1") {
		singleSupplementChosen = true;
		/*
		if (ijSupplementalFee == null || ijSupplementalFee  == "")
		{
			document.getElementById("supplementalFee").innerHTML="<span class=redText>Call for Information</span>";
		} else {
			supplementalFeeTextField.value = "Single Supplement - " + ijSupplementalFee;
			supplementalFeeTD.innerHTML = ijSupplementalFee;
			document.bookingForm.SINGLE_SUPPLEMENT.value = ijSupplementalFee;
		}
		*/
		
		document.getElementById("supplementalFee").innerHTML="<span class=redText>Call for Information</span>";
		supplementalFeeTextField.value = "Call for Information";
		
		
    } else {
        resetSingleSupplement();
	}

  }




  function enableComments(commentsCheckBox) {
    if (commentsCheckBox.checked) {
      document.bookingForm.commentstextarea.disabled = false;
    }  else  {
      document.bookingForm.commentstextarea.innerHTML = "";
      document.bookingForm.commentstextarea.disabled = true;
    }
  }

  function displayTravelClassOptions(travelClassOptionsCheckbox) {
      if (travelClassOptionsCheckbox.checked)
      {
		  document.getElementById("travelClassOptions").style.display="";
      } else {
		  document.getElementById("travelClassOptions").style.display="none";
		  document.bookingForm.preferToTravelFirstClass.checked=false;
		  document.bookingForm.preferToTravelBusinessClass.checked=false;
		  document.bookingForm.preferToTravelEconomyClass.checked=false;
	  }
  }
  
  function displayTravelAgentOptions(travelAgentOptionsCheckbox) {
	  
	  document.getElementById("travelAgentBlock").style.display="none";
	  document.getElementById("workingWithTravelAgentBlock").style.display="none";
	  document.bookingForm.worksWithAgent_agentName.value="";
	  document.bookingForm.worksWithAgent_agencyName.value="";
	  document.bookingForm.worksWithAgent_phoneNumber.value="";
	  document.bookingForm.agent_agentName.value="";
	  document.bookingForm.agent_agencyName.value="";
	  document.bookingForm.agent_iataNumber.value="";
	  document.bookingForm.agent_PhoneOrEmail.value="";
	  document.bookingForm.TRAVEL_AGENT_OPTION.value="";

	  if (travelAgentOptionsCheckbox.name == "workingWithTravelAgent" && document.bookingForm.workingWithTravelAgent.checked) {
		if (document.bookingForm.travelAgent.checked) {
			document.bookingForm.travelAgent.checked=false;
		}
		if (document.bookingForm.notAffliatedWithTravelAgent.checked) {
			document.bookingForm.notAffliatedWithTravelAgent.checked=false;
		}
		
		document.getElementById("workingWithTravelAgentBlock").style.display="";
		document.bookingForm.TRAVEL_AGENT_OPTION.value="I'm working with a travel agent";
	  } else {
		  document.bookingForm.workingWithTravelAgent.checked=false;
	  }
	  
	  if (travelAgentOptionsCheckbox.name == "travelAgent" && document.bookingForm.travelAgent.checked) {
		if (document.bookingForm.workingWithTravelAgent.checked) {
			document.bookingForm.workingWithTravelAgent.checked=false;
		}
		if (document.bookingForm.notAffliatedWithTravelAgent.checked) {
			document.bookingForm.notAffliatedWithTravelAgent.checked=false;
		}
		
		document.getElementById("travelAgentBlock").style.display="";
		document.bookingForm.TRAVEL_AGENT_OPTION.value="I'm a travel agent";
	  } else {
		  document.bookingForm.travelAgent.checked=false;
	  }
	  
	  if (travelAgentOptionsCheckbox.name == "notAffliatedWithTravelAgent" && document.bookingForm.notAffliatedWithTravelAgent.checked) {
		if (document.bookingForm.travelAgent.checked) {
			document.bookingForm.travelAgent.checked=false;
		}
		if (document.bookingForm.workingWithTravelAgent.checked) {
			document.bookingForm.workingWithTravelAgent.checked=false;
		}
		
		document.getElementById("travelAgentBlock").style.display="none";
		document.getElementById("workingWithTravelAgentBlock").style.display="none";
		document.bookingForm.TRAVEL_AGENT_OPTION.value="No, I'm not affliated with a travel agent";
	  }else{
		  document.bookingForm.notAffliatedWithTravelAgent.checked=false;		  
	  }

  }

  function calculateTotal()  {
    //alert(dateInfoString);
	var total = parseFloat(pricePerPerson) * parseFloat(numTravelers);
    if (numTravelers == 1  && singleSupplementChosen)  {
      total = parseFloat(pricePerPerson) + parseFloat(supplementalFee);
    } 
    if (internalAirfare > 0) {
      total += parseFloat(internalAirfare) * parseFloat(numTravelers);
    }
    
    var grossTourPriceTD = document.getElementById("grossTourPrice");
    grossTourPriceTD.innerHTML = CurrencyFormatted(total);
    document.bookingForm.TOTAL_AMOUNT.value = CurrencyFormatted(total);
	document.bookingForm.GROSS_TOUR_PRICE.value = CurrencyFormatted(total);
	
  }
  function calculateSubTotal() {

	var total = parseFloat(pricePerPerson) * parseFloat(numTravelers);
    if (numTravelers == 1  && singleSupplementChosen)  {
      total = parseFloat(pricePerPerson) + parseFloat(supplementalFee);
    } 
    if (internalAirfare > 0) {
      total += parseFloat(internalAirfare) * parseFloat(numTravelers);
    }
    if (discount > 0) {
	total=total-parseFloat(discount);
    }
    var subtotalTD = document.getElementById("subtotal");
    subtotalTD.innerHTML = CurrencyFormatted(total);
    document.bookingForm.TOTAL_AMOUNT.value = CurrencyFormatted(total);

	var totalinsurancevalue = (total * .085);
	if (document.bookingForm.acceptinsure[0].checked) {
		//insurancevalue = totalinsurancevalue;
                insurancevalue = 0; // only capture request for QUOTE
	} else {
		insurancevalue = 0;
	}
	var insuranceamt = document.getElementById("insurance");
	//insuranceamt.innerHTML = CurrencyFormatted(insurancevalue);
	//document.bookingForm.TOUR_INSURANCE.value = CurrencyFormatted(insurancevalue);
        if (document.bookingForm.acceptinsure[0].checked) {
            document.bookingForm.TOUR_INSURANCE.value = "QUOTE";
        } else {
            document.bookingForm.TOUR_INSURANCE.value = "DECLINED";
        }
  }

  function calculateFinalTotal() {
	var total = parseFloat(pricePerPerson) * parseFloat(numTravelers);
    if (numTravelers == 1  && singleSupplementChosen)  {
      total = parseFloat(pricePerPerson) + parseFloat(supplementalFee);
    } 

    if (internalAirfare > 0) {
      total += parseFloat(internalAirfare) * parseFloat(numTravelers);
    }
    if (discount > 0) {
	total=total-parseFloat(discount);
    }
	
	if (insurancevalue > 0) {
	total = total + parseFloat(insurancevalue);
	
	}

    var totalTD = document.getElementById("total");
    totalTD.innerHTML = CurrencyFormatted(total);
    document.bookingForm.TOTAL_AMOUNT.value = CurrencyFormatted(total);
	
	var now = new Date();
	var selectedDate = document.bookingForm.tourDatesOptions.options[document.bookingForm.tourDatesOptions.selectedIndex].text;
	var selectedDateReal = new Date(selectedDate);

  }

  function CurrencyFormatted(amount) {
  	var i = parseFloat(amount);
  	if(isNaN(i)) { 
  	  i = 0.00;
  	}
  	var minus = '';
  	if(i < 0) {
  	  minus = '-';
  	}
  	i = Math.abs(i);
  	i = parseInt((i + .005) * 100);
  	i = i / 100;
  	s = new String(i);
  	if(s.indexOf('.') < 0) { 
  	  s += '.00';
  	}
  	if(s.indexOf('.') == (s.length - 2)) { 
  	  s += '0';
  	}
  	s = minus + s;
  	//add the comma
  	nStr = s + '';
  	x = nStr.split('.');
  	x1 = x[0];
  	x2 = x.length > 1 ? '.' + x[1] : '';
  	var rgx = /(\d+)(\d{3})/;
  	while (rgx.test(x1)) {
  	  x1 = x1.replace(rgx, '$1' + ',' + '$2');
  	}
  	return '$' + x1 + x2;
  
  }

	function applyDiscounts() {

		////////////////////////////////////////////////////////////
		// COMMON DISCOUNT VARIABLES
		////////////////////////////////////////////////////////////
		var selectedDate = document.bookingForm.tourDatesOptions.options[document.bookingForm.tourDatesOptions.selectedIndex].text;
		var now = new Date();  
		var thisYear = now.getFullYear();
		var selectedDateReal = new Date(selectedDate);
		var selectedYear = selectedDateReal.getFullYear();
		var grossPrice = 0;
				
		
		////////////////////////////////////////////////////////////
		// INCLUDE SINGLE SUPPLEMENT
		////////////////////////////////////////////////////////////
		if (singleSupplementChosen) {
			grossPrice = parseFloat(pricePerPerson) + parseFloat(supplementalFee);
		} else {
			grossPrice = pricePerPerson;
		}


		///////////////////////////////////////////////////////////////////
		// DISCOUNT FOR 7CC and BEEN ON A TRIP IN LAST 90 days
		///////////////////////////////////////////////////////////////////
		var continentDiscount = 0;
		var continentSavings = document.getElementById("continentSavings");
		var continent = document.getElementById("continent");
		var travcoaTripInLast90Days0 = document.getElementById("travcoaTripInLast90Days0");
		var travcoaTripInLast90Days1 = document.getElementById("travcoaTripInLast90Days1");

		if (document.bookingForm.sevenContinentsClubMember0.checked | document.bookingForm.sevenContinentsClubMember1.checked) {
			continentSavings.style.display="";
			if (document.bookingForm.sevenContinentsClubMember0.checked) {
				travcoaTripInLast90Days0.style.display="";
				continentDiscount += grossPrice *.04;
				if (document.bookingForm.returnedFromTravcoaTripInLast90Days0.checked)  {
					continentDiscount += grossPrice *.02;
				}

			} else {
				travcoaTripInLast90Days0.style.display="none";
			}
			if (document.bookingForm.sevenContinentsClubMember1.checked) {
				travcoaTripInLast90Days1.style.display="";
				continentDiscount += grossPrice *.04;
				if (document.bookingForm.returnedFromTravcoaTripInLast90Days1.checked) {
					continentDiscount += grossPrice *.02;
				}
			} else {
				travcoaTripInLast90Days1.style.display="none";
			}
		} else {
			continentSavings.style.display="none";
			document.getElementById("travcoaTripInLast90Days0").style.display="none";
			document.getElementById("travcoaTripInLast90Days1").style.display="none";
		}

		continent.innerHTML=CurrencyFormatted(continentDiscount);
		document.bookingForm.CONTINENTS_CLUB_SAVINGS.value = CurrencyFormatted(continentDiscount);

		/////////////////////////////////////////////////////////////////
		// GET THE TOTAL DISCOUNT AMOUNT
		/////////////////////////////////////////////////////////////////
		var subtotalSavings = document.getElementById("subtotalSavings");
		
		
		if(continentDiscount > parseFloat(dynamicDiscountsTotal)){
			discount  = continentDiscount;
			for (z=0; z < 5; z++) {
			   var doExist = document.getElementById ("discount_" + z);
			   if (typeof(doExist) != 'undefined' && doExist != null)
			   {
					 doExist.style.display="none";
					 var dDiscountVal = document.getElementById ("DYNAMIC_DISCOUNT_" + z);
					 dDiscountVal.value = "";
			   }
			}
			document.getElementById("continentSavings").style.display="";
		}
		else{
			
			discount = parseFloat(dynamicDiscountsTotal);
			document.getElementById("continentSavings").style.display="none";
	
		}
		
		if (discount > 0) {
			subtotalSavings.style.display="";
		} else {
			subtotalSavings.style.display="none";
		}

		calculateSubTotal();				
		calculateFinalTotal();
				
  }

  function getDynamicDiscountsAjax() { /* AJAX not working on Travcoa, moved logic to booking form */
	  ////////////////////////////////////////////////////////////
		// COMMON DISCOUNT VARIABLES
		////////////////////////////////////////////////////////////
		var selectedDate = document.bookingForm.tourDatesOptions.options[document.bookingForm.tourDatesOptions.selectedIndex].text;
		var now = new Date();  
		now.setHours(0,0,0,0);
		var thisYear = now.getFullYear();
		var selectedDateReal = new Date(selectedDate);
		var selectedYear = selectedDateReal.getFullYear();
		var grossPrice = 0;
		

		////////////////////////////////////////////////////////////
		// GET THE DISCOUNTS THRU AJAX CALL
		////////////////////////////////////////////////////////////
		var xmlHttp2;
	    try {
		// Firefox, Opera 8.0+, Safari
		    xmlHttp2=new XMLHttpRequest();
	    } catch (e) {
		// Internet Explorer
		    try {
		        xmlHttp2=new ActiveXObject("Msxml2.XMLHTTP");
		    } catch (e) {
			    try {
				    xmlHttp2=new ActiveXObject("Microsoft.XMLHTTP");
			    } catch (e) {
				    alert("Your browser does not support AJAX!");
				    return false;
			    }
	        }
	    }

		var url = "/vgn-ext-templating/travcoa/jsp/travcoaGetTourDiscounts.jsp?tourGUID=" + selectedTourGuid;

	    xmlHttp2.open("POST",url,true);
	    xmlHttp2.send(null);

		xmlHttp2.onreadystatechange=function() {		    
			if(xmlHttp2.readyState==4 && xmlHttp2.status == 200) {				
				var allOptions=xmlHttp2.responseText.replace(/^\s+/, '');				
			    if (allOptions.length > 0) {
				    discountDataString = allOptions;
					var optionList = allOptions.split("|");
					var totalDiscountAmount = 0;

					//alert(optionList.length);
					for (z=0; z < optionList.length; z++) {
					    // split the discount values from the url
						var indOpt = optionList[z].split("#");
					    var title = indOpt[0];
					    var type = indOpt[1];
						var amount = indOpt[2];
						var availStartDate = indOpt[3];
						var availEndDate = indOpt[4];
						var depStartDate = indOpt[5];
						var depEndDate = indOpt[6];

						var discountAmount = 0;

						//alert(title + "," + type + "," + amount + "," + availStartDate + "," + availEndDate + "," + depStartDate + "," + depEndDate + "," + now);
						
						if (availStartDate != "" && availEndDate != "")
						{

							if (now >= new Date(availStartDate) && now <= new Date(availEndDate))
							{	
								
								if ( (!isValidDate(new Date(depStartDate)) && !isValidDate(new Date(depEndDate))) || 
									 (selectedDateReal >= new Date(depStartDate) && selectedDateReal <= new Date(depEndDate)) ) {

									var discountRow = addDiscountRow(z);									
									discountRow.style.display="";

									if (type == "Price")
									{
										discountAmount = numTravelers * amount;

									} else if (type == "Percent")
									{
										discountAmount = (numTravelers * pricePerPerson) * amount;
									}
									

								
									var spanTags = discountRow.getElementsByTagName ("span");
									if (spanTags.length == 2)
									{
										spanTags [0].innerHTML=title;
										spanTags [1].innerHTML=CurrencyFormatted(discountAmount);
									}
									
									var dDiscountVal = document.getElementById ("DYNAMIC_DISCOUNT_" + z);
									dDiscountVal.value = title + ": " + CurrencyFormatted(discountAmount);
									
									
								} else {
									
									var doExist = document.getElementById ("discount_" + z);
									if (typeof(doExist) != 'undefined' && doExist != null)
									{
										doExist.style.display="none";
										var dDiscountVal = document.getElementById ("DYNAMIC_DISCOUNT_" + z);
										dDiscountVal.value = "";
									}									
								}
							}
						} else if (availStartDate == "" && availEndDate == "") {

							//alert(selectedDateReal);
							if (selectedDateReal >= new Date(depStartDate) && selectedDateReal <= new Date(depEndDate)) {
								
								var discountRow = addDiscountRow(z);									
								discountRow.style.display="";

								if (type == "Price")
								{
									discountAmount = numTravelers * amount;

								} else if (type == "Percent")
								{
									discountAmount = (numTravelers * pricePerPerson) * amount;
								}
							
								var spanTags = discountRow.getElementsByTagName ("span");
								if (spanTags.length == 2)
								{
									spanTags [0].innerHTML=title;
									spanTags [1].innerHTML=CurrencyFormatted(discountAmount);
								}

								var dDiscountVal = document.getElementById ("DYNAMIC_DISCOUNT_" + z);
								dDiscountVal.value = title + ": " + CurrencyFormatted(discountAmount);


							} else {
								var doExist = document.getElementById ("discount_" + z);
								if (typeof(doExist) != 'undefined' && doExist != null)
								{
									doExist.style.display="none";
									var dDiscountVal = document.getElementById ("DYNAMIC_DISCOUNT_" + z);
									dDiscountVal.value = "";
								}
							}

						}

						totalDiscountAmount = totalDiscountAmount + discountAmount;
						
			    	}
					document.bookingForm.dynamicDiscountsTotal.value = totalDiscountAmount;
					dynamicDiscountsTotal = totalDiscountAmount;

			    }	
				applyDiscounts();
			}
		}

  }

function getDynamicDiscounts() {
    ////////////////////////////////////////////////////////////
    // COMMON DISCOUNT VARIABLES
    ////////////////////////////////////////////////////////////
    var selectedDate = document.bookingForm.tourDatesOptions.options[document.bookingForm.tourDatesOptions.selectedIndex].text;
    var now = new Date();
    now.setHours(0,0,0,0);
    var selectedDateReal = new Date(selectedDate);

    ////////////////////////////////////////////////////////////
    // GET THE DISCOUNTS THRU AJAX CALL
    ////////////////////////////////////////////////////////////
    if (discountDataString.length > 0) {
        var optionList = discountDataString.split("|");
        var totalDiscountAmount = 0;

        for (z=0; z < optionList.length; z++) {
            // split the discount values from the url
            var indOpt = optionList[z].split("#");
            var title = indOpt[0];
            var type = indOpt[1];
            var amount = indOpt[2];
            var availStartDate = indOpt[3];
            var availEndDate = indOpt[4];
            var depStartDate = indOpt[5];
            var depEndDate = indOpt[6];
            var discountAmount = 0;

            if (availStartDate != "" && availEndDate != "") {
                if (now >= new Date(availStartDate) && now <= new Date(availEndDate)) {
                    if ( (!isValidDate(new Date(depStartDate)) && !isValidDate(new Date(depEndDate))) || (selectedDateReal >= new Date(depStartDate) && selectedDateReal <= new Date(depEndDate)) ) {

                        var discountRow = addDiscountRow(z);
                        discountRow.style.display="";
                        if (type == "Price") {
                            discountAmount = numTravelers * amount;
                        } else if (type == "Percent") {
                            discountAmount = (numTravelers * pricePerPerson) * amount;
                        }

                        var spanTags = discountRow.getElementsByTagName ("span");
                        if (spanTags.length == 2) {
                            spanTags [0].innerHTML=title;
                            spanTags [1].innerHTML=CurrencyFormatted(discountAmount);
                        }

                        var dDiscountVal = document.getElementById ("DYNAMIC_DISCOUNT_" + z);
                        dDiscountVal.value = title + ": " + CurrencyFormatted(discountAmount);

                    } else {
                        var doExist = document.getElementById ("discount_" + z);
                        if (typeof(doExist) != 'undefined' && doExist != null) {
                            doExist.style.display="none";
                            var dDiscountVal = document.getElementById ("DYNAMIC_DISCOUNT_" + z);
                            dDiscountVal.value = "";
                        }
                    }
                }
            } else if (availStartDate == "" && availEndDate == "") {

                if (selectedDateReal >= new Date(depStartDate) && selectedDateReal <= new Date(depEndDate)) {
                    var discountRow = addDiscountRow(z);
                    discountRow.style.display="";
                    if (type == "Price") {
                        discountAmount = numTravelers * amount;
                    } else if (type == "Percent") {
                        discountAmount = (numTravelers * pricePerPerson) * amount;
                    }

                    var spanTags = discountRow.getElementsByTagName ("span");
                    if (spanTags.length == 2) {
                        spanTags [0].innerHTML=title;
                        spanTags [1].innerHTML=CurrencyFormatted(discountAmount);
                    }

                    var dDiscountVal = document.getElementById ("DYNAMIC_DISCOUNT_" + z);
                    dDiscountVal.value = title + ": " + CurrencyFormatted(discountAmount);
                } else {
                    var doExist = document.getElementById ("discount_" + z);
                    if (typeof(doExist) != 'undefined' && doExist != null) {
                        doExist.style.display="none";
                        var dDiscountVal = document.getElementById ("DYNAMIC_DISCOUNT_" + z);
                        dDiscountVal.value = "";
                    }
                }
            }

            totalDiscountAmount = totalDiscountAmount + discountAmount;
        }
        document.bookingForm.dynamicDiscountsTotal.value = totalDiscountAmount;
        dynamicDiscountsTotal = totalDiscountAmount;
    }
    applyDiscounts();
}

  function cloneElement (template) {
	return template.cloneNode (true);
  }

  function addDiscountRow (nodeID) {
	var doExist = document.getElementById ("discount_" + nodeID);
	if (typeof(doExist) != 'undefined' && doExist != null)
	{
		return doExist;
	}

	var newNode = cloneElement (document.getElementById ("discountTemplate"));

	var table = document.getElementById ("discountsTable");
	var next = document.getElementById ("lastDiscountRow");
	table.insertBefore (newNode, next);

	setDiscountElementIDs(newNode,nodeID);

	return newNode;
  }

  function setDiscountElementIDs(newNode,nodeID){
	newNode.setAttribute ("id",  "discount_" + nodeID);
	
	var spanTags = newNode.getElementsByTagName ("span");
	for (i = 0; i < spanTags.length; i++) {
		spanTags [i].setAttribute ("id", spanTags [i].id.replace (/(##|[0-9]+)/g, nodeID));
	
	}

  }

  function isValidDate(d) {
	if ( Object.prototype.toString.call(d) != "[object Date]" )
	    return false;
	return !isNaN(d.getTime());
  }

	

