//Changed by Rubesh for RENFE enhancement starts
$(document).ready(function() {
	if ($(".ptp_request").length > 0 &&  document.getElementById("trip-frame") != undefined) {
    var contents = document.getElementById("trip-frame").innerHTML;
    var index = contents.indexOf("<div class=\"error-message\">");
    if (index < 0){
      index = contents.indexOf("<DIV class=error-message>");
      if (index < 0){     
		    roundTripCheck();
      }
    }
	}
  if ($(".form-fill").length > 0 && $(".amtrakform").length == 0) {
		atoc_city_check();
	}	
});
//Changed by Rubesh for RENFE enhancement ends

function getPassFamilyNames(myJSONObject) {
	var familyNames = new Array();
	var x;
	for (x in myJSONObject.activePasses) {
		familyNames.push(myJSONObject.activePasses[x].familyName);
	}
	familyNames.sort();		
	return familyNames;
}

function getAllPassNames(myJSONObject) {
	var allPassNames = new Array();
	var x;
	for (x in myJSONObject.allPasses) {
		allPassNames.push(myJSONObject.allPasses[x].familyName);
	}
	allPassNames.sort();
	return allPassNames;
}

function updatePassAction(formName, myJSONObject) {

	portionForm = document.forms[formName];
	var strVal = $("#combotable2_input").val();

	var x;
	url = '';
	for (x in myJSONObject.allPasses) {
		if (myJSONObject.allPasses[x].familyName == strVal) {
			url = myJSONObject.allPasses[x].url;
		}

	}
	portionForm.action = url;
}

function passHolderSelectPass(formName, myJSONObject) {
	portionForm = document.forms[formName];
	// alert(' pass select ' + myJSONObject.activePasses[0].familyId);
	var strVal = $("#combotable_input").val();

	var x;
	for (x in myJSONObject.activePasses) {
		if (myJSONObject.activePasses[x].familyName == strVal) {
			portionForm.nCountries.value = myJSONObject.activePasses[x].nCountries;
			portionForm.familyId.value = myJSONObject.activePasses[x].familyId;
			// alert(' nCountries ' + myJSONObject.activePasses[x].nCountries);
			if (myJSONObject.activePasses[x].nCountries > 0) {
				$("#select-country").show();
				onLoadSetup(formName);
      }
      else {
				$("#select-country").hide();
			}
		}

	}

}

function passHolderFormSubmit(formName) {
	portionForm = document.forms[formName];
	// get nCountries value and check whether countries selected or not
	nCountries = portionForm.nCountries.value;
	for (i = 1; i <= nCountries; i++) {
		var select = portionForm.elements["selCountry" + i].value;
		if (select == '') {
			alert('Please select all applicable countries for the Pass');
			return false;
		}

	}	 
	portionForm.submit();
}

function aafTripSchedulerFormSubmit(formName) {
 portionForm = document.forms[formName];
 portionForm.submit();
}


function scheduleSearchSubmit() {
	var objForm = document.form1;
	populateRoundTrip();
	objForm.fn.value = 'fsScRequest';
	objForm.v.value = 'S';
	if (objForm.oldFromCity != undefined) {
		objForm.oldFromCity.disabled = true;
	}
	if (objForm.oldToCity != undefined) {
		objForm.oldToCity.disabled = true;
	}	
	objForm.submit();
}

function scheduleSubmit(formName, strAction) {
	portionForm = document.forms[formName];
	portionForm.strAction.value = strAction;
	portionForm.submit();
}

function viewFaresSubmit(formName, strAction) {
	portionForm = document.forms[formName];
	portionForm.action = strAction;
	portionForm.submit();
}
function searchFaresSubmit() {
	var objForm = document.form1;
	populateRoundTrip();

	if (objForm.isAtocRequest != undefined
			&& objForm.isAtocRequest.value == '1') {
		objForm.fn.value = 'fsAtocRequest';
		// temporary fix to change selection anytime to afternoon for atoc
		if(objForm.time0.value == 'anytime') {
			$('#time0').val('12');
		}
		if(objForm.time1 != undefined && objForm.time1.value == 'anytime') {
			$('#time1').val('12');
		}

	} else {
		objForm.fn.value = 'fsRequest';
	}
	objForm.v.value = '';
	if (objForm.oldFromCity != undefined) {
		objForm.oldFromCity.disabled = true;
	}
	if (objForm.oldToCity != undefined) {
		objForm.oldToCity.disabled = true;
	}	
	objForm.submit();
}

function editSchedule(formName, portionId) {
	// alert('edit button ' + portionId);
	var objForm = document.forms[formName];
	objForm.portionId.value = portionId;
	objForm.action = getURLPathString(window.location.pathname) + 'scheduleresult.htm?strAction=edit';
	objForm.submit();
}

function getSaleCountry() {
	var saleCountry = $('#saleCountry').val();
	if (saleCountry == undefined)
		saleCountry = 'us';
	return saleCountry;
}

function getLang() {
  var lang = $('#lang').val();
  if (lang != undefined && lang != '')
    return lang;
  else
    return '';
}

function addPortionTrip(index, roundtrip, isAmtrakReq) {
	var output = new Array();
	output.push("<div class='trip-search-field'><div class='trip' id='trip'>Trip "+ (index + 1) + " <br /> &nbsp;</div>");
	output.push("<div class='from'> From:<br> <input id='from" + index+ "' name='from" + index + "'  autocomplete='off' ");
	if (index == 0) {
		output.push("onBlur='populateRoundTrip(), atoc_city_check()' ");
	}
	output.push(" class='from-field city-input' value='' type='text'></div>");
	output.push("<div class='to'>To:<br> <input id='to" + index + "' name='to" + index + "' autocomplete='off'   ");
	if (index == 0) {
		output.push("onBlur='populateRoundTrip(), atoc_city_check();' ");
	}
	output.push(" class='to-field city-input' value='' type='text'></div>");
	output.push("<div class='departure'>Departure Date:<br> <input name='deptDate" + index + "' id='deptDate" + index + "'  class='departure-field' value='' type='text'></div>");
  // Changed by Rubesh for new requirement to show 24 hours time span start
  output.push("<div class='trip-time'>Time:<br> <span class='field-float-left'> <select name='time"+ index+ "' id='time"+ index+ "' class='time-field'>");
  for(i=0;i<24;i++){
    if (i == 0)
      j = "12 am";
    else if (i < 10)
      j = "0" + i + " am";
    else if (i < 12)
      j = i + " am";
    else if (i == 12)
      j = i + " pm";
    else if (i < 22)
      j = "0" + (i-12) + " pm";
    else
      j = (i-12) + " pm";
      output.push("<option value='"+i+"' >"+j+"</option>");
  } 
  // Changed by Rubesh for new requirement to show 24 hours time span end    
	if (isAmtrakReq != 1) {
		output.push("<option value='anytime'  selected='selected'>Anytime</option> ");
	}
	output.push("</select> </span> </div>");
	output.push("</div>");
	output.push("<div class='clear'></div> <div class='trip-table'><!--clear--> </div> <!--trip-table-->");
	return output.join("");
}

function addRoundTrip(index, isAmtrakReq) {
	var output = new Array();
	output.push("<div class='trip-search-field'><div class='trip' id='trip'> Trip " + (index + 1) + " <br /> </div>");
	output.push("<div class='from'> From: <br> <input id='fromCity" + index+ "' name='fromCity" + index + "' class='from-field' value='' type='text'/> <input id='from" + index+ "' name='from" + index + "' type='hidden'> </div>");
	output.push("<div class='to'>To:<br> <input id='toCity" + index+ "' name='toCity" + index + "' class='to-field' value='' type='text'/> <input id='to" + index+ "' name='to" + index + "' type='hidden'> </div>");
	output.push("<div class='departure'>Return Date:<br> <input name='deptDate" + index + "' id='deptDate" + index + "'  class='departure-field' value='' type='text'></div>");
  // Changed by Rubesh for new requirement to show 24 hours time span start
  output.push("<div class='trip-time'>Time:<br> <span class='field-float-left'> <select name='time"+ index+ "' id='time"+ index+ "' class='time-field'>");
  for(i=0;i<24;i++){
    if (i == 0) 
      j = "12 am";
    else if (i < 10)
      j = "0" + i + " am";
    else if (i < 12)
      j = i + " am";
    else if (i == 12)
      j = i + " pm";
    else if (i < 22)
      j = "0" + (i-12) + " pm";
    else
      j = (i-12) + " pm";
    output.push("<option value='"+i+"' >"+j+"</option>");
  }   
  // Changed by Rubesh for new requirement to show 24 hours time span end
	if (isAmtrakReq != 1) {
		output.push("<option value='anytime'  selected='selected'>Anytime</option> ");
	}
	output.push("</select> </span> </div>");
	output.push("</div>");
	output.push("<div class='clear'></div> <div class='trip-table'><!--clear--> </div> <!--trip-table-->");
	if (isAmtrakReq != 1) {
		$('#deptDate' + index).dpSetEndDate(new Date().addDays(365).asString());
        }
         else {
		$('#deptDate' + index).dpSetEndDate(new Date().addDays(335).asString());
	}
	return output.join("");
}

// For How To Book Customized function
function populateHowToRoundTrip() {
	var objForm = document.form1;
	indexVal = 0;
	if (objForm != undefined) {
		indexVal = $('input:radio[name=roundtrip]:checked').val();
	}
	if (indexVal == 1) {
		// get trip 1 details
		if (eval('document.form1.from1') == undefined) {
			howToRoundTripCheck();
		}
		$("#fromCity1").val($("#to0").val());
		$("#toCity1").val($("#from0").val());
		$("#from1").val($("#to0").val());
		$("#to1").val($("#from0").val());
	}
	
	amtrakReq = $('input[name=isAmtrakRequest]').val();    			
	if (amtrakReq == 1) {
		populateCarField();
	}
}

function getTotalPax() {
	var objForm = document.form1;

	adult = parseInt(objForm.nA.value);
	if (adult == NaN) {
		adult = 0;
	}
	youth = parseInt(objForm.nY.value);
	if (youth == NaN) {
		youth = 0;
	}
	child = parseInt(objForm.nC.value);
	if (child == NaN) {
		child = 0;
	}
	senior = parseInt(objForm.nS.value);
	if (senior == NaN) {
		senior = 0;
	}
	nPax = (adult + youth + child + senior);

	return nPax;
}

function populateRoundTrip() {	 
	indexVal = $('input:radio[name=roundtrip]:checked').val();
	if (indexVal == 1) {
		// get trip 1 details
		$("#fromCity1").val($("#to0").val());
		$("#toCity1").val($("#from0").val());
		$("#from1").val($("#to0").val());
		$("#to1").val($("#from0").val());
		$("#fromCity1").attr("disabled", "disabled");
		$("#toCity1").attr("disabled", "disabled");		
	}
	
	amtrakReq = $('input[name=isAmtrakRequest]').val();		
	if (amtrakReq == 1) {
		populateCarField();
	}
}

function getNextMonthDate() {

	var myDate = new Date();
	myDate.setMonth(myDate.getMonth() + 1);

	month = parseInt(myDate.getMonth()) + 1;
	day = myDate.getDate();
	year = myDate.getFullYear();
	mm = month > 9 ? month : "0" + month;
	dd = (day > 9 ? day : "0" + day);
	newDate = mm + "/" + dd + "/" + year;

	return newDate;
}


function getDefaultDepartureDate() {
  var myDate = new Date();
  myDate.setDate(myDate.getDate()+7);
  month = parseInt(myDate.getMonth()+1);
  day = myDate.getDate();
  year = myDate.getFullYear();
  mm = month > 9 ? month : "0" + month;
  dd = (day > 9 ? day : "0" + day);
  newDate = mm + "/" + dd + "/" + year;
  return newDate;
}

function addNDaysToDate(deptDate, nDays) {
	str1 = deptDate.split("/");
	month = parseInt(str1[0], 10) - 1;
	day = parseInt(str1[1], 10);
	year = str1[2];
	var myDate = new Date();
	myDate.setFullYear(year, month, day);
	myDate.setDate(myDate.getDate() + nDays);			
	month = parseInt(myDate.getMonth()) + 1;
	day = myDate.getDate();
	year = myDate.getFullYear();
	mm = month > 9 ? month : "0" + month;
	dd = (day > 9 ? day : "0" + day);
	newDate = mm + "/" + dd + "/" + year;
	return newDate;
}

function updateRoundTripDate() {
	var objForm = document.form1;
	indexVal = $('input:radio[name=roundtrip]:checked').val();
	if (indexVal == 1) {
		// get trip 1 details
		deptDate = document.form1.deptDate0.value;
		deptDate1 = document.form1.deptDate1.value;

		if (deptDate1 == '' || (deptDate1 <= deptDate)) {
			newDate = addNDaysToDate(deptDate, 5);

			// document.form1.deptDate1.value = newDate;
			$('#deptDate1').datePicker().val(newDate).trigger('change');
			$('#deptDate1').dpSetStartDate(deptDate);
    }
    else {
			if((Date.parse(deptDate1) < Date.parse(deptDate))) {
				$('#deptDate1').datePicker().val(deptDate).trigger('change');
      }
      else {
				$('#deptDate1').datePicker().val(deptDate1).trigger('change');
			}
			$('#deptDate1').dpSetStartDate(deptDate);
		}

		$('#deptDate1').dpSetEndDate(new Date().addDays(365).asString());
	}

	if (indexVal == 2) {
		for (i = 1; i < 12; i++) {
			if (eval('document.form1.deptDate' + i) != undefined) {
				pDate = eval('document.form1.deptDate' + (i - 1) + '.value');
				cDate = eval('document.form1.deptDate' + i + '.value');

				if (cDate < pDate) {
					// eval('document.form1.deptDate' + i + '.value='+pDate);
					$('#deptDate' + i).dpSetStartDate(pDate);
					$('#deptDate' + i).datePicker().val(pDate)
							.trigger('change');

        }
        else {
					$('#deptDate' + i).dpSetStartDate(pDate);
				}
      }
      else {
				break;
			}
		}
	}

}

function checkNoOfPax() {
	var objForm = document.form1;

	adult = parseInt(objForm.nA.value);
	if (adult == NaN) {
		adult = 0;
	}
	youth = parseInt(objForm.nY.value);
	if (youth == NaN) {
		youth = 0;
	}
	child = parseInt(objForm.nC.value);
	if (child == NaN) {
		child = 0;
	}
	senior = parseInt(objForm.nS.value);
	if (senior == NaN) {
		senior = 0;
	}
	nPax = (adult + youth + child + senior);

	return true;
}

function populateHomeYouthAge() {
	var objForm = document.form1;
	noYouth = parseInt(objForm.nY.value);

	if (checkNoOfPax()) {
		var contents = document.getElementById("youthAge");
		contents.innerHTML = "";
		var output = new Array();
		// get the ages value
		for (i = 0; i < noYouth; i++) {
			output.push(" <input name='youthAge" + i
					+ "' value='20'  type='hidden'/> ");
		}

		if (noYouth > 0) {
			contents.innerHTML = contents.innerHTML + output.join("");
		}
	}
}

function getAllYouthAges() {
  var startYouthAge = 12; // youth age starts at 12
  var endYouthAge = 25;   // youth age ends at 25 (inclusive)
  var arrayLen = endYouthAge - startYouthAge + 1;  // 1 for inclusive
  // Array initialization
  var ages = new Array(arrayLen);
  for (var i=0; i<arrayLen; i++) {
    ages[i] = startYouthAge+i;
  }
  return ages;
}
/**
 * This function create the HTML code for the youth age widget.
 * Params:
 * 
 * widgetType: could be one of - select, hidden, text (default)
 */
function populateYouthAge(youthAges, headerText, youthPaxAge, widgetType) {
  // alert('Inside populateYouthAge with youthAges='+youthAges);
  if (typeof(widgetType)=='undefined' || widgetType==null) widgetType = 'text';
	var objForm = document.form1;

  var noYouth = parseInt(objForm.nY.value);

	if (checkNoOfPax()) {
		var contents = document.getElementById("youthAge");
		contents.innerHTML = "";

		var output = new Array();

		output.push(" <p class='youth-note'>" + headerText + "</p> ");
		output.push("<div class='trip-passenger-field '>");
		// get the ages value
    var tmp = new Array(noYouth);
    if (youthAges.length>0) {
		tmp = youthAges.split("-");
    }
    else {
      // populate youth age values from the existing widgets if available
      for (i = 0; i < noYouth; i++) {
        var widgetName = 'youthAge'+i;
        var widgetValue = '';
        if (objForm[widgetName]!=null) {
          widgetValue = objForm[widgetName].value;
        }
        tmp[i] = widgetValue;
      }
    }

		// alert(' tmp ' + tmp);
		for (i = 0; i < noYouth; i++) {
      var widgetName = 'youthAge'+i;
      var widgetValue = (typeof(tmp[i])!='undefined' && tmp[i]!=null) ? 
        tmp[i] : '';
			output.push(" <div class='deals-form-field'> " + youthPaxAge + " #"
          + (i + 1) + " <br/>");
      
      if ('select'==widgetType) {
        output.push("<select name='"+ widgetName + "' >");
        var allYouthAges = getAllYouthAges();
        for (var a=0; a<allYouthAges.length; a++) {
          var selected = 
            (allYouthAges[a]==widgetValue)? "selected='selected'" : "";
          output.push("<option value='"+ allYouthAges[a] + "' "+ selected +">" + 
            allYouthAges[a] + "</option>");
				}
        output.push("</select>");
			}
      else if ('hidden'==widgetType) {
        output.push("<input type='hidden' name='"+ widgetName + 
          "' value='"+widgetValue+"' />");
      }
      else { // if ('text'==widgetType) {
        output.push(" <input type='text' name='" + widgetName +
          "' size='2' class='tiny' value='"+widgetValue+"'>");
      }
      output.push("</div>");
		}
		output.push(" </div>");

		if (noYouth > 0) {
			contents.innerHTML = contents.innerHTML + output.join("");
		}
	}
}

function populateHiddenYouthAge(youthAges, formName) {
	var objForm = document.forms[formName];

	noYouth = parseInt(objForm.nY.value);

	var contents = document.getElementById("youthAges");
	contents.innerHTML = "";

	var output = new Array();

	// get the ages value
	var tmp = new Array();
	tmp = youthAges.split("-");
	for (i = 0; i < noYouth; i++) {
		output.push(" <input name='youthAge" + i + "' ");
		if (tmp.length > 0 || tmp[i].length > 0) {
			if (tmp[i] != undefined) {
				output.push(" value='" + tmp[i] + "' ");
			}
		}
		output.push("type='hidden'>");
	}

	if (noYouth > 0) {
		contents.innerHTML = contents.innerHTML + output.join("");
	}
}

// Customized function for How To Book Page (CMS)

function howToPopulateYouthAge(youthAges, headerText, youthPaxAge) {
	var objForm = document.form1;

	noYouth = parseInt(objForm.nY.value);

	if (checkNoOfPax()) {
		var contents = document.getElementById("youthAge");
		contents.innerHTML = "";

		var output = new Array();

		output.push("<p class='youth-note'> " + headerText + " </p>");
		output.push("<div id='trip-passenger-field' class='trip-passenger-field'>");

		// get the ages value
		var tmp = new Array();
		tmp = youthAges.split("-");

		// alert(' tmp ' + tmp);
		for (i = 0; i < noYouth; i++) {
			output.push(" <div class='deals-form-field'> " + youthPaxAge + " #"
					+ (i + 1) + " <br/> <input name='youthAge" + i
					+ "' class='tiny' maxlength='2' ");
			if (tmp.length > 0 || tmp[i].length > 0) {
				if (tmp[i] != undefined) {
					output.push(" value='" + tmp[i] + "' ");
				}
			}
			output.push("type='text'>  </div>");
		}
		output.push(" </div>");

		if (noYouth > 0) {
			contents.innerHTML = contents.innerHTML + output.join("");
		}
	}
}

function validateRTDate() {
	rVal = $('input:radio[name=roundtrip]:checked').val();
	if (rVal == 1 && eval('document.form1.from1') == undefined) {
		roundTripCheck();
	}

}
//Changed by Rubesh for RENFE enhancement starts
function roundTripCheck() {
  rVal = 0;
  if (document.form1 != undefined) {
    rVal = $('input:radio[name=roundtrip]:checked').val();
    // check whether the current request is amtrak
    amtrakReq = $('input[name=isAmtrakRequest]').val();
    maxDeptDateDaysLimit = 365;
    if (amtrakReq == 1) {
      maxDeptDateDaysLimit = 335;
    }
    //var anotherTrip = document.getElementById("add-another-trip");	
    
    if (rVal == 0) {
      ddate = '';
      if ($("#deptDate0").val() != undefined) {
        ddate = $("#deptDate0").val();
      }
            
      for (j = 1; j < 12; j++) {      
        if ($('#trip-search-field' + j) != undefined) {
            $('#trip-search-field' + j ).remove();
        }
        if ($('#trip-table' + j) != undefined) {
            $('#trip-table' + j).remove();
        }  
        if ($('#breaktrip' + j) != undefined) {
            $('#breaktrip' + j).remove();
        }                                      
        if ($('#trip-alert' + j) != undefined) {
            $('#trip-alert' + j).remove();
        }         
      }     
              
			document.form1.rows.value = 1;
			//if (anotherTrip != undefined) {
			//	anotherTrip.innerHTML = "";
			//}
		}

		// if rVal is 1, populate the From1 and To1 in second trip
		if (rVal == 1) {       

      var ddate0 ='';
      if ( $('#deptDate0').val() != undefined) {
        ddate0 = $('#deptDate0').val();
      }
      
      var ddate1 ='';
      if ( $('#deptDate1').val() != undefined) {
        ddate1 = $('#deptDate1').val();
      }
      else{
          ddate1 = addNDaysToDate(ddate0, 5);
      }
      
      var time0 = '';
      if ( $('#time0').val() != undefined) {
        time0 = $('#time0').val();
      }
            
      var time1 = '';
      if ( $('#time1').val() != undefined) {
        time1 = $('#time1').val();
      }
      
      if ($('#trip-frame') != undefined) { 

        for (i = 1; i < 12; i++) {
          if ($('#trip-search-field' + i) != undefined) {
              $('#trip-search-field' + i).remove();
          }

          if ($('#trip-table' + i) != undefined) {
              $('#trip-table' + i).remove();
          }

          if ($('#breaktrip' + i) != undefined) {
              $('#breaktrip' + i).remove();
          }                                                

          if ($('#trip-alert' + i) != undefined) {
              $('#trip-alert' + i).remove();
          }        

        }

        if ($('#trip-search-field0') != undefined) {         
          var suffix = "1";      
          $('#trip-table0').clone(true).attr('id', 'trip-table' + suffix).insertAfter($('#trip-table0'));
          
          $('#trip-search-field0').clone(false).attr('id', 'trip-search-field' + suffix).find('*').each(function() {
              if (this.type != undefined ) {
                var idName = String(this.name);
                changed= idName.substring(0 ,idName.length-1) + suffix;
                if (changed == 'deptDate1') {                
                  $(this).removeAttr("onchange");
                }
                $(this).removeAttr("id");
                $(this).removeAttr("name");
                this.name += changed;
                this.id += changed;
              }
              else if(this.id != '') {
                var idName = String(this.id);
                changed= idName.substring(0 ,idName.length-1) + suffix;
                $(this).removeAttr("id");
                this.id += changed;            
              }
            }).end().insertBefore($('#trip-table' + suffix));
          
          if ($('#breaktrip0') != undefined) { 
          
          $('#breaktrip0').clone(false).attr('id', 'breaktrip' + suffix).find('*').each(function() {
              if (this.type != undefined ) {
                var idName = String(this.name);
                changed= idName.substring(0 ,idName.length-1) + suffix;
                $(this).removeAttr("id");
                $(this).removeAttr("name");
                this.name += changed;
                this.id += changed;
              }
              else if(this.id != '') {
                var idName = String(this.id);
                changed= idName.substring(0 ,idName.length-1) + suffix;
                $(this).removeAttr("id");
                this.id += changed;            
              }
            }).end().insertBefore($('#trip-table' + suffix));          
          }

          $('#trip-table0').clone(true).attr('id', 'trip-table').insertBefore($('#breaktrip1'));

          // to remove href for return date
          $('#' + suffix).remove();
//          //$('#trip' + suffix).html("Trip 2");
          $('#trip'+ suffix).html($('#trip'+ suffix).html().replace('1','2')); 

          $("#departure0").replaceWith( "<div class='departure' id='departure0'>"
            + $('#deptdate').text() 
            + "<br><input name='deptDate0' id='deptDate0' onChange='updateRoundTripDate();' class='departure-field dp-applied' value='' type='text'></div>");
        
          $("#departure1").replaceWith( "<div class='departure' id='departure1'>"
            + $('#returndate').text() 
            + "<br><input name='deptDate1' id='deptDate1' class='departure-field dp-applied' value='' type='text'></div>");

          if ($('#bpc1') != undefined && $('#bpc1').val() != undefined  
            && $('#error-bpc1') != undefined) {
            // remove the hidden fields
            $('#from1').remove();
            $('#to1').remove();
          }
          
          $('#from1').attr('name', 'fromCity1');
          $('#to1').attr('name', 'toCity1');        
          $('#from1').attr('id', 'fromCity1');
          $('#to1').attr('id', 'toCity1');

          $("#fromCity1").val($("#to0").val());
          $("#toCity1").val($("#from0").val());

          $("#fromCity1").attr("disabled", "disabled");
          $("#toCity1").attr("disabled", "disabled");

          if ($('#bpc1') != undefined && $('#bpc1').val() != undefined  
            && $('#error-bpc1') != undefined) {
            $('#error-bpc1').replaceWith("<input name='bpc1' id='bpc1' disabled='true' class='from-field' value='' type='text'>");
          }
          
          $('#trip-search-field1').append("<input id='from1' name='from1' type='hidden' value=''><input id='to1' name='to1' type='hidden' value=''>");
          $("#from1").val($("#to0").val());
          $("#to1").val($("#from0").val());

          $('#error-from1').replaceWith($('#error-from1').html());
          $('#error-to1').replaceWith($('#error-to1').html());
          $('#error-date1').replaceWith($('#error-date1').html());

          if ( time0 != '') {
            $("#time0").val(time0);
          }
          if ( time1 != '') {
            $("#time1").val(time1);
          }
            
          isAtocRequest = $("#isAtocRequest").val();
          if (isAtocRequest == '1' && 
             (document.form1.time1 != undefined
             && document.form1.time1.value == 'anytime')) {
            $('#time1').val('12');
          }

          $("#from0").attr("onBlur", "populateRoundTrip(), atoc_city_check()");
          $("#to0").attr("onBlur", "populateRoundTrip(), atoc_city_check()");          
          
          $("#deptDate0").val(ddate0);
          $('#deptDate0').dpSetEndDate(new Date().addDays(maxDeptDateDaysLimit).asString());            

          $("#deptDate1").val(ddate1);
          $('#deptDate1').datePicker().val($('#deptDate1').val()).trigger('change');
          $('#deptDate1').dpSetEndDate(new Date().addDays(maxDeptDateDaysLimit).asString());            

//          updateRoundTripDate();
          
          $('#deptDate0').datePicker().val($('#deptDate0').val()).trigger('change');

          document.form1.rows.value = 2;
         // if (anotherTrip != undefined) {
         //   anotherTrip.innerHTML = "";
        //  }        
        }
      }   
//alert("OUTPUT : " + $('#trip-search-field1').html());
		}

		if (rVal == 2) {

			rows = document.form1.rows.value;

			if (rows == undefined) {
				rows = 4;
			}
			if (rows < 4) {
				rows = 4;
			}
      
      var ddate ="";
      if ( document.form1.deptDate0 != undefined) {
        ddate = document.form1.deptDate0.value;
      }


      if ($('#trip-frame') != undefined) { 

        for (i = 1; i < 12; i++) {
          if ($('#trip-search-field' + i) != undefined) {
              $('#trip-search-field' + i).remove();
          }

          if ($('#trip-table' + i) != undefined) {
              $('#trip-table' + i).remove();
          }
        }

        if ($('#trip-search-field0') != undefined) { 
          l = 0;
          k = 0;
          
          for (j=1; j < rows; j++) {
            k = j+1;
            $('#trip-table' + l).clone(false).attr('id', 'trip-table' + j).insertAfter($('#trip-table' + l));
            $('#trip-search-field0').clone(false).attr('id', 'trip-search-field' + j).find('*').each(function() {
              if (this.type != undefined ) {
                var idName = String(this.name);
                changed= idName.substring(0 ,idName.length-1) + j;
                $(this).removeAttr("id");
                $(this).removeAttr("name");
                this.name += changed;
                this.id += changed;
              }
              else if(this.id != '') {
                var idName = String(this.id);
                changed= idName.substring(0 ,idName.length-1) + j;
                $(this).removeAttr("id");
                this.id += changed;            
              }
            }).end().insertBefore($('#trip-table' + j));

            // to remove href for return date
            $('#'+j).remove();
            
            $('#trip'+ j).html($('#trip'+ j).html().replace('1',k)); 
            l = l+1;
          }          
          
          $("#departure0").replaceWith( "<div class='departure' id='departure0'>"
            + $('#deptdate').text() 
            + "<br><input name='deptDate0' id='deptDate0' onChange='updateRoundTripDate();' class='departure-field dp-applied' value='' type='text'></div>");
          
          $('#deptDate0').val(ddate);          
          $('#deptDate0').attr( {onChange : 'updateRoundTripDate();' });
          $('#deptDate0').datePicker().val($('#deptDate0').val()).trigger('change');
          $('#deptDate0').dpSetEndDate(new Date().addDays(maxDeptDateDaysLimit).asString());
          for (k = 1; k < rows; k++) {  
          
            $('#error-from' + k).replaceWith($('#error-from' + k).html());
            $('#error-to' + k).replaceWith($('#error-to' + k).html());
            $('#error-date' + k).replaceWith($('#error-date' + k).html());
          
            $('#from' + k).val("");
            $('#to' + k).val("");
                        
          $('#departure' + k).replaceWith( "<div class='departure' id='departure" + k + "'>"
            + $('#deptdate').text() 
            + "<br><input name='deptDate" + k + "' id='deptDate" + k + "' onChange='updateRoundTripDate();' class='departure-field dp-applied' value='' type='text'></div>");
                                              
            $('#deptDate' + k).val(ddate);
//            $('#deptDate' + k).attr( {onChange : "updateRoundTripDate();" });
            $('#deptDate' + k).datePicker().val($('#deptDate' + k).val()).trigger('change');
            $('#deptDate' + k).dpSetEndDate(new Date().addDays(maxDeptDateDaysLimit).asString());            
          }       
        }

				//var output = new Array();
				//output.push("<a href='javascript:addAnotherTrip();'><img src='/redesign/images/img-plus.jpg' class='float-left' alt='Add Another Trip'/></a>");
				//output.push("<div><a href='javascript:addAnotherTrip();'>Add another trip</a></div>");

				//anotherTrip.innerHTML = output.join("");
			}
			document.form1.rows.value = rows;
		}
    break_point_check();
		reinitialize_cities(); // NK
		return false;
	}
}
//Changed by Rubesh for RENFE enhancement ends

//Changed by Rubesh for RENFE enhancement starts
function addAnotherTrip() {
	// get the current number of portions
	// index= parseInt(document.form1.rows.value);
	rows = 1;
	for (i = 0; i < 12; i++) {
		// alert(' date ' + $('#deptDate'+i).val());
		if ($('#deptDate' + i).val() != undefined) {
			rows++;
		}
	}
	index = rows - 1;

	if (index == 12) {
		alert('Maximum number of portions allowed is 12.');
	} 
  else {
    $('#trip-table0').clone(false).attr('id', 'trip-table' + index).insertAfter($('#trip-table' + (index-1)));
    $('#trip-search-field0').clone(false).attr('id', 'trip-search-field'+index).find('*').each(function() {
      if (this.type != undefined ) {
        var idName = String(this.name);
        changed= idName.substring(0 ,idName.length-1) + index;
        $(this).removeAttr("id");
        $(this).removeAttr("name");
        this.name += changed;
        this.id += changed;
      }
      else if(this.id != '') {
        var idName = String(this.id);
        changed= idName.substring(0 ,idName.length-1) + index;
        $(this).removeAttr("id");
        this.id += changed;            
      }
    }).end().insertBefore($('#trip-table'+index));

    // to remove href for return date
    $('#'+index).remove();
  
   
    $('#trip'+ index).html($('#trip'+ index).html().replace('1',(index+1))); 
              
    $('#trip-table'+(index-1)).clone(true).attr('id', 'trip-table'+ index).insertAfter($('#trip-search-field'+ index));

    $('#error-from' + index).replaceWith($('#error-from' + index).html());
    $('#error-to' + index).replaceWith($('#error-to' + index).html());
    $('#error-date' + index).replaceWith($('#error-date' + index).html());
            
    $('#from' + index).val("");
    $('#to' + index).val("");
    $('#departure' + index).replaceWith( "<div class='departure' id='departure" + index + "'>"
      + $('#deptdate').text() 
      + "<br><input name='deptDate" + index+ "' id='deptDate" + index+ "' onChange='updateRoundTripDate();' class='departure-field dp-applied' value='' type='text'></div>");

    
//    $('#deptDate' + index).attr( {onChange : "updateRoundTripDate();" });
    $('#deptDate' + index).datePicker().val($('#deptDate' + (index-1)).val()).trigger('change');
    $('#deptDate' + index).dpSetEndDate(new Date().addDays(365).asString());
    
		document.form1.rows.value = (index + 1);
		reinitialize_cities(); // NK
	}


}

//Changed by Rubesh for RENFE enhancement ends


function multioverviewSubmit(formName, aafFormName, strAction) {
	multiForm = document.forms[formName];
	vpFormName = document.forms[aafFormName];

	if (multiForm.fromFareType.length > 0) {
		for (i = 0; i < multiForm.fromFareType.length; i++) {
			if (multiForm.fromFareType[i].checked == true) {
				fareType = multiForm.fromFareType[i].value;
				break;
			}
		}
  }
  else {
		fareType = multiForm.fromFareType.value;
	}

	// if it is virtual pass, submit the form to shopping cart
	// AAF_PREMIER_FARE = "4";
	if (fareType == 4) {
		vpFormName.submit();
  }
  else {
		multiForm.action = getURLPathString(window.location.pathname)
				+ 'multioverview.htm?strAction=' + strAction + '&fromFareType='
				+ fareType;
		multiForm.submit();
	}
}

function portionSubmit(formName, strAction) {
	portionForm = document.forms[formName];
		portionForm.strAction.value = strAction;
		portionForm.action = getURLPathString(window.location.pathname) + 'portionresult.htm';
		portionForm.submit();

}

function getURLPathString(urlStr) {
	tmpStr = urlStr.substring(0, urlStr.lastIndexOf('/') + 1);
	return tmpStr;
}

function submitMandatoryRTFares(formName, portionId) {
	// alert('edit button ' + portionId);
	var objForm = document.forms[formName];
	objForm.action = getURLPathString(window.location.pathname)
			+ 'portionresult.htm?editPortionId=' + portionId
			+ '&strAction=edit&mandatoryRtSelected=true';
	objForm.submit();
}

function earlierTrain(criteriaForm, presultForm, strAction) {
	// 0 - 6
	// 6 - 12
	// 12 - 18
	startTime = getStartTimeHour(criteriaForm);
	// alert(' startTime ' + startTime);
	endTime = 0;
	/*
	if (startTime >= 0 && startTime < 11) {
		startTime = 0;
		endTime = 288;
	} else if (startTime >= 11 && startTime < 17) {
		startTime = 0;
		endTime = 288;
	} else if (startTime >= 17 && startTime < 24) {
		startTime = 288;
		endTime = 432;
	} */
	
	if (startTime >= 0 && startTime < 11) {
      startTime = 0;
      endTime = 144;
    } else if (startTime >= 11 && startTime < 17) {
      startTime = 144;
      endTime = 288;
    } else if (startTime >= 17 && startTime < 24) {
      startTime = 288;
      endTime = 432;
    }
          document.criteriaForm.minTime.value = startTime;
 
	  document.criteriaForm.maxTime.value = endTime;
 
	var params = '&' + getCriteriaParams(criteriaForm, presultForm);

  portionForm = document.forms[presultForm];
  portionForm.strAction.value = strAction;

	// return false;
	// portionForm.action = getURLPathString(window.location.pathname) +
	// 'portioncriteria.htm?'+'strAction='+strAction+params;
	portionForm.action = getURLPathString(window.location.pathname) + 'portioncriteria.htm';
	portionForm.submit();

}

function laterTrain(criteriaForm, presultForm, strAction) {
	// 0 - 6
	// 6 - 12
	// 12 - 18	
	startTime = getStartTimeHour(criteriaForm);
	endTime = 0;
	/*
	if (startTime >= 0 && startTime < 11) {
		startTime = 288;
		endTime = 432;
	} else if (startTime >= 11 && startTime < 17) {
		startTime = 432;
		endTime = 576;
	} else if (startTime >= 17 && startTime < 24) {
		startTime = 432;
		endTime = 576;
	}
	*/
	if (startTime >= 0 && startTime < 5) {
      startTime = 144;
      endTime = 288;    
    }else if (startTime >= 5 && startTime < 11) {
      startTime = 288;
      endTime = 432;
    } else if (startTime >= 11 && startTime < 24) {
      startTime = 432;
      endTime = 576;
    }
		

	document.criteriaForm.minTime.value = startTime;
	document.criteriaForm.maxTime.value = endTime;

	var params = '&' + getCriteriaParams(criteriaForm, presultForm);
	// alert(' later params ' + params);
	// return false;

  portionForm = document.forms[presultForm];
  portionForm.strAction.value = strAction;

	// portionForm.action = getURLPathString(window.location.pathname) +
	// 'portioncriteria.htm?'+'strAction='+strAction+params;
	portionForm.action = getURLPathString(window.location.pathname) + 'portioncriteria.htm';
	portionForm.submit();

}

function getStartTimeHour(criteriaForm) {
	portionForm = document.forms[criteriaForm];
	var slider_min = parseInt(portionForm.minTime.value);
	// alert(' slider min ' + slider_min );
	// if(slider_min > 0) {
	// slider_min += 34;
	// }

	var startTime = 0;
	if (slider_min > 0) {
		startTime = Math.floor((slider_min / 24));
		// startTime -= 1;
	}
	stTime = startTime + "";

	if (stTime.indexOf(".") > 0) {
		stTime = stTime.substring(0, stTime.indexOf("."));
	}
	// alert(' stTime ' + stTime );
	return stTime;
}

function getStartTimeMin(criteriaForm) {
	portionForm = document.forms[criteriaForm];
	var slider_min = parseInt(portionForm.minTime.value);
	
	var startTime = 0;
	if (slider_min > 0) {
		startTime = slider_min % 24;
	}
	stTime = startTime * 2.5;
	return stTime;
}

function getEndTimeHour(criteriaForm) {
	portionForm = document.forms[criteriaForm];
	var slider_max = parseInt(portionForm.maxTime.value);
	// alert(' slider_max ' + slider_max );
	// slider_max += 34;

	var endTime = Math.floor((slider_max / 24));
	// endTime -= 1;
	edTime = endTime + "";

	if (edTime.indexOf(".") > 0) {
		edTime = edTime.substring(0, edTime.indexOf("."));
	}
	// alert(' edTime ' + edTime );
	return edTime;
}

function getEndTimeMin(criteriaForm) {
	portionForm = document.forms[criteriaForm];
        var slider_max = parseInt(portionForm.maxTime.value);

	// alert(' slider_max ' + slider_max );
	// slider_max += 34;
	var endTime = slider_max % 24;
	// alert(' endTime ' + endTime);
	edTime = 0;

	edTime = endTime * 2.5;

	// alert(' edTime min ' + edTime );
	return edTime;
}

function getCriteriaParams(criteriaForm, presultForm) {
	// need to consider all the components
	// whichever component is clicked
	// get all the values and pass to the server

	// for(i=0; i<document.criteriaForm.elements.length; i++)
	// {
	// alert("The field name is: " + document.criteriaForm.elements[i].name + "
	// and it’s value is: " + document.criteriaForm.elements[i].value + ".<br
	// />");
	// }
	objResultForm = document.forms[presultForm];
	objCritForm = document.forms[criteriaForm];

	var portionId = objResultForm.portionId.value;
	var faresSelected = objResultForm.faresSelected.value;
	var resultId = objResultForm.resultId.value;
	var fareKey = "";
	if (document.portionHeaderForm != undefined) {
		fareKey = document.portionHeaderForm.portionFareSelected.value;
	}
	var connection0 = "";
	var connection1 = "";
	var connection2 = "";
	var fastest = "";
	var cheapest = "";
	var comfort = "";
	var firsttrainArriving = "";
	var lasttrainDeparting = "";

	isPassHolder = 0;
	if (objResultForm.p != undefined) {
		isPassHolder = objResultForm.p.value;
	}
	familyId = "";
	if (objResultForm.familyId != undefined) {
		familyId = objResultForm.familyId.value;
	}
	familyName = "";
	if (objResultForm.familyName != undefined) {
		familyName = objResultForm.familyName.value;
	}

	if (objCritForm.zero.checked) {
		connection0 = objCritForm.zero.value;
	}

	if (objCritForm.one.checked) {
		connection1 = objCritForm.one.value;
	}

	if (objCritForm.two.checked) {
		connection2 = objCritForm.two.value;
	}

	var startTime = objCritForm.minTime.value;
	var endTime = objCritForm.maxTime.value;

	if (objCritForm.fastest.checked) {
		fastest = objCritForm.fastest.value;
	}

	if (objCritForm.cheapest.checked) {
		cheapest = objCritForm.cheapest.value;
	}

	if (objCritForm.comfort.checked) {
		comfort = objCritForm.comfort.value;
	}

	if (objCritForm.firsttrain.checked) {
		firsttrainArriving = objCritForm.firsttrain.value;
	}

	if (objCritForm.lasttrain.checked) {
		lasttrainDeparting = objCritForm.lasttrain.value;
	}
	v = objResultForm.v.value;

	stTimeHour = getStartTimeHour(criteriaForm);
	stTimeMin = getStartTimeMin(criteriaForm);

	edTimeHour = getEndTimeHour(criteriaForm);
	edTimeMin = getEndTimeMin(criteriaForm);

	var output = new Array();

	if (objResultForm.zero == undefined) {
		output.push(" <input type='hidden' name='zero' value='" + connection0
				+ "' />");
	}

	if (objResultForm.one == undefined) {
		output.push(" <input type='hidden' name='one' value='" + connection1
				+ "' />");
	}

	if (objResultForm.two == undefined) {
		output.push(" <input type='hidden' name='two' value='" + connection2
				+ "' />");
	}

	if (objResultForm.fastest == undefined) {
		output.push(" <input type='hidden' name='fastest' value='" + fastest
				+ "' />");
	}

	if (objResultForm.cheapest == undefined) {
		output.push(" <input type='hidden' name='cheapest' value='" + cheapest
				+ "' />");
	}

	if (objResultForm.comfort == undefined) {
		output.push(" <input type='hidden' name='comfort' value='" + comfort
				+ "' />");
	}

	if (objResultForm.firsttrain == undefined) {
		output.push(" <input type='hidden' name='firsttrain' value='"
				+ firsttrainArriving + "' />");
	}

	if (objResultForm.lasttrain == undefined) {
		output.push(" <input type='hidden' name='lasttrain' value='"
				+ lasttrainDeparting + "' />");
	}

	if (objResultForm.familyId == undefined) {
		output.push(" <input type='hidden' name='familyId' value='"
				+ familyId + "' />");
	}
if (objResultForm.familyName == undefined) {
		output.push(" <input type='hidden' name='familyName' value='"
				+ familyName + "' />");
	}
	output.push(" <input type='hidden' name='minTimeHr' value='" + stTimeHour
			+ "' />");
	output.push(" <input type='hidden' name='maxTimeHr' value='" + edTimeHour
			+ "' />");

	output.push(" <input type='hidden' name='minTime' value='" + stTimeHour
			+ "' />");
	output.push(" <input type='hidden' name='maxTime' value='" + edTimeHour
			+ "' />");

	output.push(" <input type='hidden' name='minTimeMin' value='" + stTimeMin
			+ "' />");
	output.push(" <input type='hidden' name='maxTimeMin' value='" + edTimeMin
			+ "' />");

	// if(objResultForm.criteriaFields != undefined) {
	var contents = document.getElementById("criteriaFields");
	if (contents != undefined) {
		contents.innerHTML = "";
		contents.innerHTML = contents.innerHTML + output.join("");
	}
	// var elms = contents.getElementsByTagName("*");

	// alert(' contents ' + elms);
	// for(i=0; i<elms.length; i++) {
	// alert(' i ' + i + '' + elms[i].name);
	// }

	// }

	var params = "zero=" + connection0 + "&one=" + connection1 + "&two="
			+ connection2 + "&minTimeHr=" + stTimeHour + "&maxTimeHr="
			+ edTimeHour + "&minTime=" + stTimeHour + "&maxTime=" + edTimeHour
			+ "&minTimeMin=" + stTimeMin + "&maxTimeMin=" + edTimeMin
			+ "&fastest=" + fastest + "&cheapest=" + cheapest + "&comfort="
			+ comfort + "&firsttrain=" + firsttrainArriving + "&lasttrain="
			+ lasttrainDeparting + "&fareKey=" + fareKey + "&faresSelected="
			+ faresSelected + "&resultId=" + resultId + "&portionId="
			+ portionId + "&p=" + isPassHolder + "&v=" + v + "&familyId="
			+ familyId + "&familyName="+familyName;

	// alert('params ' + params);
	return params;
}

// on change whenever any component is clicked
// or changed

function submitCriteria(criteriaForm, presultForm) {

	objResultForm = document.forms[presultForm];
	objCritForm = document.forms[criteriaForm];

	var portionId = objResultForm.portionId.value;
	var faresSelected = objResultForm.faresSelected.value;
	var resultId = objResultForm.resultId.value;
	var viewType = objResultForm.v.value;
	// need to consider all the components
	// whichever component is clicked
	// get all the values and pass to the server
	var params = getCriteriaParams(criteriaForm, presultForm);
	// alert(' params ' + params);
	// get processFlag value
	prFlag = objCritForm.processFlag.value;
	// processFlag - used for basically not to submit the multiple request
	// continuously
	// if it is false, change to true and call ajax request

	// if it is true , dont call ajax request
	if (prFlag == 'true') {
		return false;
	}

	if (prFlag == 'false') {
		objCritForm.processFlag.value = 'true';
	}

	// return false;

	var action = getURLPathString(window.location.pathname)
			+ 'portioncriteria.htm';

	var output = new Array();

	output.push(" <form name='PtpResults'  method='post'> ");
	output.push(" <input type='hidden' name='action' />");
	output.push(" <input type='hidden' name='portionId' value='" + portionId
			+ "' />");
	output.push(" <input type='hidden' name='resultId' value='" + resultId
			+ "' />");
	output.push(" <input type='hidden' name='faresSelected' value='"
			+ faresSelected + "'/>");
	output.push(" <input type='hidden' name='v' value='" + viewType + "'/>");
	output.push(" <input type='hidden' name='p' value='" + isPassHolder
					+ "'/>");
	output.push(" <input type='hidden' name='familyId' value='" + familyId
			+ "'/>");
	// output.push(" There was a problem with the network in getting the
	// results. ");
	output.push(" </form> ");

	var resultTxt1 = "";

	var contents = document.getElementById("portioncontents");
	contents.innerHTML = "";
	// alert('ptpResultData ' + ptpResultData);
	document.getElementById("portioncontents").innerHTML = "<div align='center'><img src='/redesign/images/fs_waiting.gif' alt='' border='0' align='absmiddle' /></div>";

	$.ajax( {
		url : action,
		type : 'POST',
		cache : false,
		data : params,
		dataType : 'text/html',
		timeout : 4000,
		error : function() {

			var contents = document.getElementById("portioncontents");
			contents.innerHTML = "";
			// alert('ptpResultData ' + ptpResultData);
		document.getElementById("portioncontents").innerHTML = output.join("");

	},
	success : function(resultTxt) {
		var contents = document.getElementById("portioncontents");
		contents.innerHTML = "";
		// alert('resultTxt ' + resultTxt);
		document.getElementById("portioncontents").innerHTML = resultTxt;
		compareHideUnHide();
		// extract java script
		cssScript = getIndicatorCSSscript(resultTxt);
		// and eval		
		eval(cssScript);
		tb_init('a.thickbox, area.thickbox, input.thickbox');
	}
	});
	objCritForm.processFlag.value = 'false';

}

function getIndicatorCSSscript(respText) {
// TODO: replace with JSON
	scriptIndex1 = respText.indexOf("<script type=\"text/javascript\">");
	scriptIndex2 = respText.indexOf("}");
	// alert(' scriptIndex1 ' + scriptIndex1 );
	// alert(' scriptIndex2 ' + scriptIndex2 );
	strScript = respText.substring(scriptIndex1 + 8, scriptIndex2 + 3);
	// alert(' strScript ' + strScript);
	return strScript;
}

function updatePrice(portionId, priceSelected) {

	// get the fare amount selected
	var strPrice = priceSelected.value;
	strPrice = strPrice.substring(0, strPrice.indexOf('@@'));
	// get the portion index
	var index = portionId.substring(portionId.indexOf("_") + 1,
			portionId.length);

	// get current selected fare selection key
	var strFare = priceSelected.value;
	// alert(' strFare ' + strFare);

	eval('document.portionHeaderForm.portionFareSelected.value="' + strFare + '"');

	fareIndex = (strFare.substring(strFare.indexOf('@@') + 2, strFare.length));
	// alert(' fareIndex[0] ' + fareIndex[0]);
	// alert(' fareIndex[1] ' + fareIndex[1]);
	fareKeyType = strFare.substring(strFare.length - 1, strFare.length);
	// alert(' fareKeyType ' + fareKeyType);

	var strVar = portionId + '_PRICE';
	// set the price to hidden variable, which can be used for calculating total
	if (document.portionHeaderForm.PORTION_PRICE.length > 0) {
		eval('document.portionHeaderForm.PORTION_PRICE[' + index + '].value='
				+ strPrice);
  }
  else {
		eval('document.portionHeaderForm.PORTION_PRICE.value=' + strPrice);
	}

	// set selected portion fare to div
	document.getElementById(strVar + '_LABEL').innerHTML = "";
	document.getElementById(strVar + '_LABEL').innerHTML = strPrice;
	updateTotalPrice();
}

function updateFareCSS(fareId) {

	// var radios = document.forms.PtpResults.elements.fareKey;
	// for(var i=0; i<radios.length; i++){
	// fareValue =radios[i].value;
	$("input[type='radio']").parent().removeClass();
	$("input[type='radio']").parent().addClass('td-choice-options first');

	// }
	$("#" + fareId).removeClass();
	$("#" + fareId).addClass('td-choice-options first on');

	// change the css in compare classes also

}

function updateTotalPrice() {
	var total = 0;
	// calculate total
	if (document.portionHeaderForm.PORTION_PRICE.length > 0) {
		for (i = 0; i < document.portionHeaderForm.PORTION_PRICE.length; i++) {
			total += parseFloat(document.portionHeaderForm.PORTION_PRICE[i].value);
		}
  }
  else {
		total += parseFloat(document.portionHeaderForm.PORTION_PRICE.value);
	}
	// set total value
	var strAmount = total + "";
	if (strAmount.indexOf('.') == -1) {
		strAmount = total + '.00';
	}

	document.getElementById("PORTION_TOTAL_PRICE_LABEL").innerHTML = "";
	document.getElementById("PORTION_TOTAL_PRICE_LABEL").innerHTML = strAmount;

}

function aafSubmit(formName) {
	var objForm = document.forms[formName];
	objForm.submit();
}

function gotoPortion(formName, portionId) {
	// alert('edit button ' + portionId);
	var objForm = document.forms[formName];

	var faresSelected = objForm.faresSelected.value;
	// need to consider all the components
	// whichever component is clicked
	objForm.method = 'post';
	objForm.action = getURLPathString(window.location.pathname)
			+ 'portionresult.htm?editPortionId=' + portionId + '&strAction=goto';
	objForm.submit();
}

function modifyPortion(formName, portionId) {
	// alert('edit button ' + portionId);
	var objForm = document.forms[formName];
	objForm.action = getURLPathString(window.location.pathname)
			+ 'portionresult.htm?editPortionId=' + portionId + '&strAction=edit';
	objForm.submit();
}

function addToCart(formName, btn) {
  actionName 
    = '/' + getSaleCountry() + '/rail/point_to_point/' + 'add_to_cart.htm';

  // fix to accommodate optional lang
  var lang = getLang();
  if (lang != '') actionName = '/' + lang + actionName;

  var objForm = document.forms[formName];
  objForm.action = actionName;
  btn.disabled = true;
  objForm.submit();
}

function compareHideUnHide() {
	var faqtable = new switchicon("icongroup", "div") // Limit scanning of
														// switch contents to
														// just "div" elements	
	var close = ptpMessage.linkClose + ' <img src="/redesign/images/img-arrow-collapse.jpg" alt="" />';
	var viewFare = ptpMessage.linkViewFare + '<img src="/redesign/images/img-arrow-expand.jpg"  alt="" />'
	faqtable.setHeader(close, viewFare) // Set header HTML
	faqtable.collapsePrevious(false) // Allow more than 1 content to be open
										// simultanously
	faqtable.setPersist(true, 0) // Enable persistence to remember last
									// switch content states for 7 days
	faqtable.init()

}

String.prototype.trim = function() {
	return this.replace(/^\s*/, "").replace(/\s*$/, "");
}

// on change whenever any component is clicked
// or changed
/*
function checkRTCompatibility(presultForm) {

	objResultForm = document.forms[presultForm];

	var portionId = objResultForm.portionId.value;
	var faresSelected = objResultForm.faresSelected.value;
	var resultId = objResultForm.resultId.value;
	var fareKey = document.portionHeaderForm.portionFareSelected.value;
	// need to consider all the components
	// whichever component is clicked
	var params = "fareKey=" + fareKey + "&faresSelected=" + faresSelected
			+ "&resultId=" + resultId + "&portionId=" + portionId;

	var action = getURLPathString(window.location.pathname)
			+ 'rtcompatibility.htm?' + params;
	result = true;
	var resultTxt = "";
	contents = "";
	$.ajax( {
		url : action,
		type : 'GET',
		cache : false,
		async : false,
		dataType : 'text/html',
		error : function() {
			result = false;
		},
		success : function(resultTxt) {
			var contents = document.getElementById("rtcompatible");
			contents.innerHTML = "";
			// alert('resultTxt ' + resultTxt);
		document.getElementById("rtcompatible").innerHTML = resultTxt;

	}
	});

}
*/

function updateShoppingCartTotal(formName, currency) {
	shopForm = document.forms[formName];

	amount = 0;
	if (shopForm.itemFare != undefined) {

		if (shopForm.itemFare.length > 0) {
			for (i = 0; i < shopForm.itemFare.length; i++) {
				amount += parseFloat(shopForm.itemFare[i].value);
			}
    }
    else {
			amount += parseFloat(shopForm.itemFare.value);
		}
		var strAmount = amount + "";
		if (strAmount.indexOf('.') == -1) {
			strAmount = amount + '.00';
		}
		document.getElementById("total").innerHTML = "";
		document.getElementById("total").innerHTML = currency + '' + strAmount;
	}

}

function upgradePortionFare(presultForm, portionId, fareKey) {

	objResultForm = document.forms[presultForm];
	var resultId = objResultForm.resultId.value;
	var faresSelected = objResultForm.faresSelected.value;
	// need to consider all the components
	// whichever component is clicked
	var params = "fareKey=" + fareKey + "&faresSelected=" + faresSelected
			+ "&resultId=" + resultId + "&portionId=" + portionId;
	var action = getURLPathString(window.location.pathname)
			+ "fareupgrade.htm?" + params;
	objResultForm.action = action;
	objResultForm.submit();

}

function upgradeAllPortions(presultForm) {

	objResultForm = document.forms[presultForm];

	var action = getURLPathString(window.location.pathname)
			+ "fareupgrade.htm?strAction=upgradeall";
	objResultForm.action = action;
	objResultForm.submit();

}

function passSubmit(formName, strAction) {
	passForm = document.forms[formName];
	var portionId = passForm.portionId.value;
	var resultId = passForm.resultId.value;
	var faresSelected = passForm.faresSelected.value;
	var fromFare = passForm.fromFareType.value;

	var fareKey = '';
	if (passForm.fareKey != undefined) {

		if (passForm.fareKey.length > 0) {
			for (i = 0; i < passForm.fareKey.length; i++) {
				if (passForm.fareKey[i].checked == true) {
					fareKey = passForm.fareKey[i].value;
					break;
				}
			}
    }
    else {
			fareKey = passForm.fareKey.value;
		}
	}

	var params = "strAction=" + strAction + "&fareKey=" + fareKey
			+ "&faresSelected=" + faresSelected + "&resultId=" + resultId
			+ "&portionId=" + portionId + "&fromFareType=" + fromFare;
	alert('params ' + params);
	// return false;
	passForm.action = getURLPathString(window.location.pathname)
			+ 'passresult.htm?' + params;
	passForm.submit();
}

function modifyPass(formName, portionId) {
	// alert('edit button ' + portionId);
	var objForm = document.forms[formName];
	objForm.portionId.value = portionId;
	var fromFare = objForm.fromFareType.value;
	objForm.action = getURLPathString(window.location.pathname) + 'passresult.htm?strAction=edit&fromFareType='+fromFare;
	objForm.submit();
}
 
function passHolderAddToCartSubmit(formName, fareKey) {
	var passForm = document.forms[formName];
	passForm.fareKey.value = fareKey;
	actionName = getURLPathString(window.location.pathname) + 'add_to_cart.htm';
	passForm.action = actionName;
	passForm.submit();
}

function aafAddToCartSubmit(formName, fareKey) { 
  var passForm = document.forms[formName];  
  passForm.fareKey.value = fareKey;
  actionName = getURLPathString(window.location.pathname) + 'aaf_invoice.htm';
  passForm.action = actionName;
  passForm.submit();
}

function passFormSubmit(formName, fareKey) {
	var passForm = document.forms[formName];
	passForm.fareKey.value = fareKey;
	actionName = getURLPathString(window.location.pathname) + 'passresult.htm';
	passForm.action = actionName;
	passForm.submit();
}

function editPass(formName, portionId) {
	// alert('edit button ' + portionId);
	var passForm = document.forms[formName];
	// var fromFare = passForm.fromFareType.value;

	var faresSelected = passForm.faresSelected.value;
	var fareKey = '';
	// need to consider all the components
	// whichever component is clicked
	passForm.portionId.value = portionId;
	var fromFare = passForm.fromFareType.value;
	passForm.method = 'post';
	passForm.action = getURLPathString(window.location.pathname) + 'passresult.htm?strAction=edit&fromFareType='+fromFare;
	passForm.submit();
}

function minimiseAllPassFares(portionId) {
	var checkboxes = document.forms.PtpResults.elements.fareCheckBox;
	rlength = document.forms.PtpResults.fareKey.length;
	for ( var i = 0; i < rlength; i++) {
		$("#fareCheck" + i).css('display', 'none');
	}

	// update total price on top
	var index = portionId.substring(portionId.indexOf("_") + 1,
			portionId.length);
	index = parseInt(index) + 1;
	;
	strPrice = "0.00";
	var strVar = portionId + '_PRICE';
	// set the price to hidden variable, which can be used for calculating total
	if (document.passHeaderForm.PORTION_PRICE.length > 0) {
		eval('document.passHeaderForm.PORTION_PRICE[' + index + '].value='
				+ strPrice);
  }
  else {
		eval('document.passHeaderForm.PORTION_PRICE.value=' + strPrice);
	}
	// set selected portion fare to div
	document.getElementById(strVar + '_LABEL').innerHTML = "";
	document.getElementById(strVar + '_LABEL').innerHTML = strPrice;
	updatePassTotalPrice();

}

function updatePassPrice(portionId, priceSelected) {

	// get the fare amount selected
	var strPrice = priceSelected.value;

	strPrice = strPrice.substring(0, strPrice.indexOf('@@'));
	// get the portion index
	var index = portionId.substring(portionId.indexOf("_") + 1,
			portionId.length);
	index = parseInt(index) + 1;
	;
	// get current selected fare selection key
	var strFare = priceSelected.value;

	eval('document.passHeaderForm.portionFareSelected.value="' + strFare + '"');

	fareIndex = (strFare.substring(strFare.indexOf('@@') + 2, strFare.length));
	// alert(' fareIndex[0] ' + fareIndex[0]);
	// alert(' fareIndex[1] ' + fareIndex[1]);
	fareKeyType = strFare.substring(strFare.length - 1, strFare.length);
	// alert(' fareKeyType ' + fareKeyType);

	if (priceSelected.checked == false) {
		strPrice = "0";
	}

	var strVar = portionId + '_PRICE';
	// set the price to hidden variable, which can be used for calculating total
	if (document.passHeaderForm.PORTION_PRICE.length > 0) {
		eval('document.passHeaderForm.PORTION_PRICE[' + index + '].value='
				+ strPrice);
  }
  else {
		eval('document.passHeaderForm.PORTION_PRICE.value=' + strPrice);
	}

	// set selected portion fare to div
	document.getElementById(strVar + '_LABEL').innerHTML = "";
	document.getElementById(strVar + '_LABEL').innerHTML = strPrice;
	updatePassTotalPrice();
}

function updatePassTotalPrice() {
	var total = 0;
	// calculate total

	if (document.passHeaderForm.PORTION_PRICE.length > 0) {
		for (i = 0; i < document.passHeaderForm.PORTION_PRICE.length; i++) {
			total += parseFloat(document.passHeaderForm.PORTION_PRICE[i].value);
		}
  }
  else {
		total += parseFloat(document.passHeaderForm.PORTION_PRICE.value);
	}
	// set total value
	var strAmount = total + "";
	if (strAmount.indexOf('.') == -1) {
		strAmount = total + '.00';
	}
	document.getElementById("PORTION_TOTAL_PRICE_LABEL").innerHTML = "";
	document.getElementById("PORTION_TOTAL_PRICE_LABEL").innerHTML = strAmount;

}

function addPassToCart(formName) {
	actionName = '/' + getSaleCountry() + '/shopping/add_pass_selector_product.htm';
	var objForm = document.forms[formName];
	objForm.action = actionName;
	return false;
}

function getPassHolderEarlierTrain(presultForm, strAction) {
	var passForm = document.forms[presultForm];
	minTime = passForm.minTime.value;
	maxTime = passForm.maxTime.value;
	resultId = passForm.resultId.value;
	passForm.action = getURLPathString(window.location.pathname)
			+ 'passholdercriteria.htm?' + 'strAction=' + strAction
			+ '&minTime=' + minTime + '&maxTime=' + maxTime + '&resultId='
			+ resultId;
	passForm.submit();
}

function getPassReservationEarlierLaterTrain(presultForm, strAction) {
	var passForm = document.forms[presultForm];
	minTime = passForm.minTime.value;
	maxTime = passForm.maxTime.value;
	resultId = passForm.resultId.value;
	portionId = passForm.portionId.value;

	var fromFare = passForm.fromFareType.value;

	var faresSelected = passForm.faresSelected.value;
	var fareKey = '';
	if (passForm.fareKey != undefined) {

		if (passForm.fareKey.length > 0) {
			for (i = 0; i < passForm.fareKey.length; i++) {
				if (passForm.fareKey[i].checked == true) {
					fareKey = passForm.fareKey[i].value;
					break;
				}
			}
    }
    else {
			fareKey = passForm.fareKey.value;
		}
	}

	passForm.action = getURLPathString(window.location.pathname)
			+ 'passresult.htm?' + 'strAction=' + strAction + '&minTime='
			+ minTime + '&maxTime=' + maxTime + '&resultId=' + resultId
			+ '&portionId=' + portionId + "&fareKey=" + fareKey
			+ '&faresSelected=' + faresSelected + "&fromFareType=" + fromFare;
	passForm.submit();

}


function getAafTripReservationEarlierLaterTrain(presultForm, strAction) {
	var passForm = document.forms[presultForm];
	minTime = passForm.minTime.value;
	maxTime = passForm.maxTime.value;
	resultId = passForm.resultId.value;
	portionId = passForm.portionId.value;

	var fromFare = passForm.fromFareType.value;

	var faresSelected = passForm.faresSelected.value;
	var fareKey = '';
	if (passForm.fareKey != undefined) {

		if (passForm.fareKey.length > 0) {
			for (i = 0; i < passForm.fareKey.length; i++) {
				if (passForm.fareKey[i].checked == true) {
					fareKey = passForm.fareKey[i].value;
					break;
				}
			}
    }
    else {
			fareKey = passForm.fareKey.value;
		}
	}

	var fullUrl = window.location.href;
	var params = fullUrl.substring(fullUrl.indexOf('?') + 1);
	passForm.action = window.location.pathname + '?strAction=' + strAction
			+ '&minTime=' + minTime + '&maxTime=' + maxTime + '&resultId='
			+ resultId + '&portionId=' + portionId + "&fareKey=" + fareKey
			+ '&faresSelected=' + faresSelected + "&fromFareType=" + fromFare
			+ params;
	passForm.submit();

}


// For the Home page
function roundTripCheckHome(rVal) {

	if (rVal.value == 0) {
		fromCity = document.form1.from0.value;
		toCity = document.form1.to0.value;
		deptdate = document.form1.deptDate0.value;
		document.form1.from0.value = fromCity;
		document.form1.to0.value = toCity;
		document.form1.deptDate0.value = deptdate;
		document.form1.from1.value = '';
		document.form1.to1.value = '';
		document.form1.deptDate1.disabled = true;

		$('#deptDate0').datePicker().val($('#deptDate0').val()).trigger(
				'change');
		$('#deptDate1').addClass("dp-disabled");
		// $('#deptDate1').dpSetDisabled(true);
     $("#time1").attr('disabled', 'disabled');     
	}

	// if rVal is 1, populate the From1 and To1 in second trip
	if (rVal.value == 1) {
		var output = new Array();
		// get trip 1 details
		fromCity = document.form1.from0.value;
		toCity = document.form1.to0.value;
		deptdate = document.form1.deptDate0.value;
		time = document.form1.time0.value;

		deptdate1 = '';
		if (document.form1.deptDate1 != undefined) {
			deptdate1 = document.form1.deptDate1.value;
		}

		// assign trip 1 values
		document.form1.from0.value = fromCity;
		document.form1.to0.value = toCity;
		document.form1.deptDate0.value = deptdate;
		document.form1.time0.value = time;

		// assign trip 2 values
		document.form1.from1.value = toCity;
		document.form1.to1.value = fromCity;
		document.form1.deptDate1.disabled = false;

		if (deptdate1 != '') {
			document.form1.deptDate1.value = deptdate1;
		} else {
			document.form1.deptDate1.value = deptdate;
		}

		$('#deptDate0').datePicker().val($('#deptDate0').val()).trigger(
				'change');
		$('#deptDate1').dpSetDisabled(false);
		$('#deptDate1').datePicker().val($('#deptDate1').val()).trigger(
				'change');
    $("#time1").removeAttr('disabled');

		updateRoundTripDate();

		$('#deptDate0').attr( {			
			onChange : "updateRoundTripDate();"
		});
	}
}

function populateRoundTripHome() {
	var objForm = document.form1;
	indexVal = 0;
	for (i = 0; i < objForm.roundtrip.length; i++) {

		if (objForm.roundtrip[i].checked == true) {
			indexVal = objForm.roundtrip[i].value;
			break;
		}
	}
	if (indexVal == 1) {

		fromCity = document.form1.from0.value;
		toCity = document.form1.to0.value;

		// get trip 1 details
		document.form1.from1.value = toCity;
		document.form1.to1.value = fromCity;

	}

	nA = document.form1.nA.value;
	if (nA.trim().length == 0) {
		document.form1.nA.value = '0';
	}

	nC = document.form1.nC.value;
	if (nC.trim().length == 0) {
		document.form1.nC.value = '0';
	}

	nY = document.form1.nY.value;
	if (nY.trim().length == 0) {
		document.form1.nY.value = '0';
	}

	nS = document.form1.nS.value;
	if (nS.trim().length == 0) {
		document.form1.nS.value = '0';
	}
}

$(document).ready(function() {
	var objForm = document.form1;
	if (objForm && objForm.roundtrip) {
		indexVal = 0;
		for (i = 0; i < objForm.roundtrip.length; i++) {
			if (objForm.roundtrip[i].checked == true) {
				indexVal = objForm.roundtrip[i].value;
				break;
			}
		}
		if (indexVal == 0 && objForm.roundtrip.length > 1) {
			if (objForm.from1) {
				objForm.from1.value = '';
				objForm.to1.value = '';
				objForm.deptDate1.disabled = true;
				$('#deptDate1').addClass("dp-disabled");
			}
    }
    else if (indexVal == 1) {
			if (objForm.from1) {
				objForm.from1.value = objForm.to0.value;
				objForm.to1.value = objForm.from0.value;
				objForm.deptDate1.disabled = false;
				$('#deptDate1').removeClass("dp-disabled");
			}
		}
	}
});

// Code to setup initialization of trip summary carousel.
$(document).ready(function() {
	var CAROUSEL_DISPLAY_SIZE = 3;
	var $carouselItems = $('ul#ptp_carousel > li');
	var size = $carouselItems.size();
	if (size > CAROUSEL_DISPLAY_SIZE) {
		var selectedItem = $('li#current-trip').get(0);
		var index = $carouselItems.index(selectedItem);
		var start = index - Math.floor(CAROUSEL_DISPLAY_SIZE / 2);
		if (start < 0)
			start = 0;
		if (start > size - CAROUSEL_DISPLAY_SIZE) {
			start = size - CAROUSEL_DISPLAY_SIZE;
		}
		jQuery('#ptp_carousel').jcarousel( {
			vertical : true,
			scroll : 1,
			visible : CAROUSEL_DISPLAY_SIZE,
			start : start + 1
		// jcarousel uses 1-based indexes
				});
	}
});

// This function is being replicated to make the # of rows for Multi City to be
// 3
function howToRoundTripCheck() {
	rVal = $('input:radio[name=roundtrip]:checked').val();
	amtrakReq = 0;
	if (document.form1.isAmtrakRequest != undefined) {
		amtrakReq = document.form1.isAmtrakRequest.value;
	}

	//var anotherTrip = document.getElementById("add-another-trip");
	if (rVal == 0) {
		fromCity = document.form1.from0.value;
		toCity = document.form1.to0.value;
		deptdate = document.form1.deptDate0.value;
		time = document.form1.time0.value;
		var contents = document.getElementById("trip-frame");
		contents.innerHTML = "";
		document.getElementById("trip-frame").innerHTML = addPortionTrip(0, 0,
				amtrakReq);
		document.form1.from0.value = fromCity;
		document.form1.to0.value = toCity;
		document.form1.deptDate0.value = deptdate;
		document.form1.time0.value = time;
		document.form1.rows.value = 1;
		//anotherTrip.innerHTML = "";
		$('#deptDate0').datePicker().val($('#deptDate0').val()).trigger(
				'change');
		$('#deptDate0').dpSetEndDate(new Date().addDays(365).asString());
		// atoc_event();
	}

	// if rVal is 1, populate the From1 and To1 in second trip
	if (rVal == 1) {

		var output = new Array();

		// NEW
		output.push("<div class='trip-search-field-cars' id='trip-search-field-cars'></div>");

		// get trip 1 details
		fromCity = document.form1.from0.value;
		toCity = document.form1.to0.value;
		deptdate = document.form1.deptDate0.value;
		time = document.form1.time0.value;

		deptdate1 = '';
		if (document.form1.deptDate1 != undefined) {
			deptdate1 = document.form1.deptDate1.value;
		}

		var contents = document.getElementById("trip-frame");
		// clear the trips
		contents.innerHTML = "";

		// add trip 1
		contents.innerHTML = contents.innerHTML
				+ addPortionTrip(0, 1, amtrakReq);
		// add trip 2 - round trip
		contents.innerHTML = contents.innerHTML + addRoundTrip(1, amtrakReq)
				+ output.join("");

		// assign trip 1 values
		document.form1.from0.value = fromCity;
		document.form1.to0.value = toCity;
		document.form1.deptDate0.value = deptdate;
		document.form1.time0.value = time;

		// assign trip 2 values
		document.form1.from1.value = toCity;
		document.form1.fromCity1.value = toCity;
		document.form1.to1.value = fromCity;
		document.form1.toCity1.value = fromCity;

		if (deptdate1 != '') {
			document.form1.deptDate1.value = deptdate1;
    }
    else {
			document.form1.deptDate1.value = deptdate;
		}
		document.form1.fromCity1.disabled = true;
		document.form1.toCity1.disabled = true;

		//anotherTrip.innerHTML = "";
		document.form1.rows.value = 2;
		$('#deptDate0').datePicker().val($('#deptDate0').val()).trigger(
				'change');
		$('#deptDate1').datePicker().val($('#deptDate1').val()).trigger(
				'change');
		$('#deptDate0').dpSetEndDate(new Date().addDays(365).asString());
		$('#deptDate1').dpSetEndDate(new Date().addDays(365).asString());
		validateRTDate();
		updateRoundTripDate();

		$('#deptDate0').attr( {
			onChange : "updateRoundTripDate();"
		});
		 atoc_city_check();
	}

	if (rVal == 2) {

		rows = document.form1.rows.value;

		if (rows == undefined) {
			rows = 4;
		}
		if (rows < 4) {
			rows = 4;
		}
		fromCityArray = new Array(rows);
		toCityArray = new Array(rows);
		deptDateArray = new Array(rows);
		deptTimeArray = new Array(rows);
		for (i = 0; i < rows; i++) {
			if (eval('document.form1.from' + i) != undefined) {
				from = eval('document.form1.from' + i + '.value');
				// alert(' from ' + from);
				if (from != undefined) {
					fromCityArray[i] = from;
				}
      }
      else {
				fromCityArray[i] = '';
			}

			if (eval('document.form1.to' + i) != undefined) {
				to = eval('document.form1.to' + i + '.value');
				// alert(' to ' + to);
				if (to != undefined) {
					toCityArray[i] = to;
				}
      }
      else {
				toCityArray[i] = '';
			}

			if (eval('document.form1.deptDate' + i) != undefined) {
				ddate = eval('document.form1.deptDate' + i + '.value');
				// alert(' ddate ' + ddate);
				if (ddate != undefined) {
					deptDateArray[i] = ddate;
				}
      }
      else {
				deptDateArray[i] = '';
			}

			if (eval('document.form1.time' + i) != undefined) {
				dtime = eval('document.form1.time' + i + '.value');
				// alert(' dtime ' + dtime);
				if (dtime != undefined) {
					deptTimeArray[i] = dtime;
				}
      }
      else {
				deptTimeArray[i] = '';
			}

		}

		// fromCity = document.form1.from0.value;
		// toCity = document.form1.to0.value;
		// deptdate = document.form1.deptDate0.value;
		// time = document.form1.time0.value;

		var contents = document.getElementById("trip-frame");
		contents.innerHTML = "";
		document.getElementById("trip-frame").innerHTML = addPortionTrip(0, 2,
				0);
		for (k = 1; k < rows; k++) {
			contents.innerHTML = contents.innerHTML + addPortionTrip(k, 2, 0);
		}

		for (i = 0; i < rows; i++) {
			// eval('document.form1.from'+i+'.value='+fromCityArray[i]);
			$('#from' + i).val(fromCityArray[i]);
			$('#to' + i).val(toCityArray[i]);
			// if(deptDateArray[i] != '') {
			// $('#deptDate'+i).datePicker().val(deptDateArray[i]).trigger('change');
      // }
      // else {
			if (deptDateArray[i] != '') {
				$('#deptDate' + i).datePicker().val(deptDateArray[i]).trigger(
						'change');
      }
      else {
				// $('#deptDate' + i).datePicker().val($('#deptDate' + (i - 1)).val());
				$('#deptDate' + i).datePicker().val(new Date().addDays(7).asString()).trigger('change');			 
			}
			// }
			if (deptTimeArray[i] != '') {
				$('#time' + i).val(deptTimeArray[i]);
			}
			$('#deptDate' + i).dpSetEndDate(new Date().addDays(335).asString());
		}

		//var output = new Array();
		//output.push("<a href='javascript:addAnotherTrip();'><img src='/redesign/images/img-plus.jpg' class='float-left' alt='Add Another Trip'/></a>");
		//output.push("<div><a href='javascript:addAnotherTrip();'>Add another trip</a></div>");

		//anotherTrip.innerHTML = output.join("");
		
		document.form1.rows.value = rows;
		// for(i=0; i<rows; i++){
		// $('#deptDate'+i).datePicker().val(getNextMonthDate()).trigger('change');
		// $('#deptDate'+i).dpSetEndDate(new Date().addDays(365).asString());
		// }
	}
	reinitialize_cities(); // NK	
	return false;
}

 
function atoc_city_check() {
	var objForm = document.form1;	 
	if (objForm == undefined) {
		return;
	}
	fromCity = objForm.from0.value;
	toCity = objForm.to0.value;
	indexVal = 0;
	if (objForm != undefined) {
		for (i = 0; i < objForm.roundtrip.length; i++) {
			if (objForm.roundtrip[i].checked == true) {
				indexVal = objForm.roundtrip[i].value;
				break;
			}
		}
	}
	if (indexVal == 2) {
		return 0;
	}
	
	if(objForm.p != undefined) {
	  if(objForm.p.value == '1')
	   return 0;
	}
	
	isAtocFromCity = "0";
	isAtocToCity = "0";
	isAtocRequest = $("#isAtocRequest").val();

	// check whether the fromcity and tocity is changed
	// from last value
	// if changed then call ajax to check atoc city
	// otherwise do nothing
	oldFromCity = "";
	oldToCity = "";
	if (document.form1.oldFromCity != undefined) {
		oldFromCity = document.form1.oldFromCity.value;
	}
	if (document.form1.oldToCity != undefined) {
		oldToCity = document.form1.oldToCity.value;
	}

	if (oldFromCity != fromCity || oldToCity != toCity) {
		isAtocRequest="0";
	//	if (oldFromCity != fromCity) {
		  if (fromCity.length > 0) {
			isAtocFromCity = checkAtocCity(fromCity);
		  }
	//	}
	//	if(oldToCity != toCity) {
		  if (toCity.length > 0) {
			isAtocToCity = checkAtocCity(toCity);
	//	  }
		}
	}

//	if(isAtocRequest == 1) {
	//	isAtocFromCity= "1";
	//	isAtocToCity = "1";
//	}
//alert('isAtocRequest' + isAtocRequest);
	if ((oldFromCity == fromCity && oldToCity == toCity) && isAtocRequest == 1) {
		isAtocFromCity= "1";
		isAtocToCity = "1";
	}
	if (isAtocFromCity == '0' && isAtocToCity == '0') {
		$("#multicity").show();
		$("#browseschedule").show();
		// objForm.isAtocRequest.value = '0';
		$('#isAtocRequest').val('0');
		$('#time0').val('anytime');
		if(document.form1.time1 != undefined) {
			$('#time1').val('anytime');
		}

	}
	if (isAtocFromCity == '1' || isAtocToCity == '1') {
		$("#multicity").hide();
		$("#browseschedule").hide();
		// objForm.isAtocRequest.value = '1';
		$('#isAtocRequest').val('1');
		if(document.form1.time0.value == 'anytime') {
			$('#time0').val('12');
		}
		if(document.form1.time1 != undefined && document.form1.time1.value == 'anytime') {
			$('#time1').val('12');
		}

	}
	if (document.form1.oldFromCity != undefined) {
		document.form1.oldFromCity.value = fromCity;
	}
	if (document.form1.oldToCity != undefined) {
		document.form1.oldToCity.value = toCity;
	}
}

function checkAtocCity(cityName) {
	var action = "/biz/atoc_city_check.jsp?cityName=" + cityName;

	result = "0";
	$.ajax( {
		url : action,
		type : 'GET',
		cache : false,
		async : false,
		dataType : 'text/html',
		error : function() {
			resultTxt = "0";
		},
		success : function(resultTxt) {

			if (resultTxt == '1') {
				result = "1";
      }
      else {
				result = "0";
			}

		}
	});
	return result;
}

function getAtocEarlierTrain(presultForm, strAction) {
	var portionForm = document.forms[presultForm];
	resultId = portionForm.resultId.value;
	portionForm.action = getURLPathString(window.location.pathname)
			+ 'portioncriteria.htm?' + 'strAction=' + strAction
			+ '&resultId='+ resultId;
	portionForm.submit();
}

//Added by Rubesh for ATOC / RENFE enhancement starts
function break_point_check() {
  if ( $('#bpc0') != undefined && $('#bpc0').val() != undefined) {
    $("#fromBreakCity0").val($("#bpc0").val());
    if ($("#fromBreakCity1") != undefined){
      $("#fromBreakCity1").val($("#bpc0").val());
    }
    if ($("#bpc1") != undefined && $('#bpc1').val() != undefined ){
      $("#bpc1").val($("#bpc0").val());
      
    }  
  }
  else{
    $("#fromCity1").val($("#to0").val());
    $("#toCity1").val($("#from0").val());
  }
}
//Added by Rubesh for ATOC / RENFE enhancement ends

// PassHolder/Ptp request page redirection from cms pages .

function ptpPassRequestPageRedirection(requestType,selection,urlPrefix){			
	var from = document.getElementById('from0').value;
	var to = document.getElementById('to0').value;
	var date=document.getElementById('deptDate0').value;	
	var selObj = document.getElementById('time0');
	var selIndex = selObj.selectedIndex;
	var time = selObj.options[selIndex].value;	
		
	if(selection == "round"){
		url = urlPrefix + "/rail/point_to_point/"+requestType+".htm?roundtrip=1&from0="+from+"&to0="+to+"&deptDate0="+date+"&time0="+time;		
	}else{
		url = urlPrefix + "/rail/point_to_point/"+requestType+".htm?roundtrip=2&from0="+from+"&to0="+to+"&deptDate0="+date+"&time0="+time;		
	}	
	this.location.href=url;
}
 
