//***************** DO NOT EDIT *****************
//This file was automatically generated by 
//./gen.pl cms-content.dat cms-content.js 
//on Thu Nov 12 10:49:50 2009.

//From : ../reg/photo-video.js ____________
$(document).ready(function() {

  //Define identifiers used for class/id selectors.			     
  //var PREVIEW = 'preview';
  var LOADER = 'loader';
  var LOADING = 'loading';
  var LOADERAFTER = 'loaderafter';
  var CAPTION = 'caption';
  var HIDDEN_CAPTION = 'hiddencaption';
 
  var PHOTO_TAB = 'photo-tab';

  var PHOTO_SEL = 'photoselector';
  var BUTTON_HOME_ON = 'btn-home-on';
  var BUTTON_HOME_OFF = 'btn-home-off';
  var BUTTON_PHOTOS = 'btn-photos';
  var IMAGE_CAPTION = 'imagecaption';
  var IMAGE_LOAD = 'imageload';
  var PREVIOUS_PHOTO = 'previous-image';
  var NEXT_PHOTO = 'next-image';
  var SELECTED_PHOTO = 'selected-photo';

  //Delay between photos for photo animation.
  var PHOTO_DELAY_MILLIS = 60*1000;

  var ALINK = 'alink';
  var IMAGELINK = 'imagelink';
  var CAPLINK   = 'caplink';

 

  //PHOTO DISPLAY

  var photoIndex; //index of current photo being displayed.
  var N_PHOTOS = $('.' + IMAGE_LOAD).size(); //total # of photos.

   //load photos[photoIndex] into #LOADER.
  function loadImage() {
    var $anchor = $('.' + IMAGE_LOAD).slice(photoIndex, photoIndex + 1);
    var href = $anchor.attr('href');
    var caption = $anchor.attr('alt');
    var reclink = $anchor.attr('bref');
    $('#' + LOADER).addClass(LOADING);
    $('#' + LOADER + ' img:first').remove();
   
    var img = new Image();
    $(img).attr('src', href);
    $(img).css('display', 'none').hide();
        
    if(reclink != "null"){
        $('#' + LOADER).removeClass(LOADING);
        $('#' + ALINK ).attr('href',reclink);
        $('#' + ALINK ).append(img);
    } else {
        $('#' + LOADER).removeClass(LOADING).append(img);
        $('#' + ALINK ).html("<div></div>");
    }


    if(reclink != "null"){    	
    $('#' + IMAGE_CAPTION).html("<a href='" + reclink + "'>" + caption + "</a>");
    } else {    
    $('#' + IMAGE_CAPTION).html(caption);
    }     
    
    $(img).fadeIn();
  };

  //Set photoIndex to i, update the number to indicate it selected,
  //and display the corresponding photo.
  function setPhotoIndex(i) {
    photoIndex = i;
    $('.' + IMAGE_LOAD).removeClass(SELECTED_PHOTO);
    $('.' + IMAGE_LOAD).slice(i, i + 1).addClass(SELECTED_PHOTO);
    loadImage();
    reanimate();
  } 

  //load default image.
  setPhotoIndex(Math.floor(Math.random()*N_PHOTOS));

  //Display clicked on photo.
  $('.' + IMAGE_LOAD).click(function(event) {
    event.preventDefault();
    setPhotoIndex($(this).html() - 1);
  });

  //Display next photo in sequence.
  function nextPhoto() {
    var i = (photoIndex + 1) % N_PHOTOS;
    setPhotoIndex(i);
  }

  //Handler for clicking previous arrow.
  $('.' + PREVIOUS_PHOTO).click(function(event) {
    event.preventDefault();
    var i = photoIndex - 1;
    if (i < 0) i = N_PHOTOS - 1;
    setPhotoIndex(i); 
  });

  //Handler for clicking next arrow.
  $('.' + NEXT_PHOTO).click(function(event) {
    event.preventDefault();
    nextPhoto();
  });

  var animateId;
  function animate() {
    if (!animateId){
     animateId = window.setInterval(nextPhoto, PHOTO_DELAY_MILLIS);
    }
  }

  function unanimate() {
    window.clearInterval(animateId);
    animateId = null;
  }

  function reanimate() {
    unanimate(); animate();
  }

  animate();

  $('#' + LOADER).hover(unanimate, animate);

});


//From : ../reg/quote.js ____________

// jsvascript to support eurogroups quotes setup

var errorSectionPage1 = "";
var errorSectionPage2 = "";

function onPage1Load()
{
  errorSectionPage1 = document.getElementById("errorSectionPage1").innerHTML;
  document.getElementById("errorSectionPage1").innerHTML = "";
}

function onPage2Load()
{
  errorSectionPage2 = document.getElementById("errorSectionPage2").innerHTML;
  document.getElementById("errorSectionPage2").innerHTML = "";
}

function testErrors()
{
}

function isAgent()
{
  return document.QuotesForm.isAgent[0].checked;
}

function switchFields()
{
  if (isAgent()) {
    setVisibility(getElement("agent"), 1);
    setVisibility(getElement("nonAgent"), 0);
  }
  else {
    setVisibility(getElement("agent"), 0);
    setVisibility(getElement("nonAgent"), 1);
  }

}

function displayErrorsPage1(errorMessagesPage1)
{
  document.getElementById("errorSectionPage1").innerHTML = errorSectionPage1;
  document.getElementById("errorMessagesPage1").innerHTML = errorMessagesPage1;
}

function submitVerifyPage1()
{
  var errorHTML = 
    '<div id="genericErrorContainer" style="display: block;" >' +
    '<div class="error-box-top"></div>' +
    '<div class="error-box-mid">' +
    '<div class="error-sign"></div>' +
    '<div class="error-box-message">' +
    '<p id="contact_us_error_message">Please correct the following errors and then continue:' +
    '<br />' +
    '</p>' +
    '<p id="errorMessages">' +
    '</p>' +
    '</div>' +
    '<div class="clear"></div>' +
    '</div>' +
    '<div class="error-box-btm"></div>' +
    '</div';

  var errorMessagesPage1 = "";
  if (isAgent()) {
    if (document.getElementById("agencyContactPerson").value == "") {
      errorMessagesPage1 += "Agency contact person field cannot be empty<br>";
    }
    if (document.getElementById("agencyIata").value == "") {
      errorMessagesPage1 += "Agency IATA field cannot be empty<br>";
    }
    if (document.getElementById("agencyEmailAddress").value == "") {
      errorMessagesPage1 += "Email address field cannot be empty<br>";
    }
    if (!isValidEmailId($('#agencyEmailAddress').val())) {
      errorMessagesPage1 += "Please enter a valid email address<br>";
    }
    if (document.getElementById("agencyPhoneNumber").value == "") {
      errorMessagesPage1 += "Agency phone number field cannot be empty<br>";
    }
  }
  else {
    if (document.getElementById("contactPerson").value == "") {
      errorMessagesPage1 += "Contact person field cannot be empty<br>";
    }
    if (document.getElementById("address").value == "") {
      errorMessagesPage1 += "Address field cannot be empty<br>";
    }
    if (document.getElementById("city").value == "") {
      errorMessagesPage1 += "City field cannot be empty<br>";
    }
    if (document.getElementById("state").value == "") {
      errorMessagesPage1 += "State field cannot be empty<br>";
    }
    if (document.getElementById("zipCode").value == "") {
      errorMessagesPage1 += "Zipcode field cannot be empty<br>";
    }
    if (document.getElementById("emailAddress").value == "") {
      errorMessagesPage1 += "Email address field cannot be empty<br>";
    }
    if (!isValidEmailId($('#emailAddress').val())) {
      errorMessagesPage1 += "Please enter a valid email address<br>";
    }
    if (document.getElementById("phoneNumber").value == "") {
      errorMessagesPage1 += "Phone number field cannot be empty<br>";
    }
  }

  if (errorMessagesPage1 != "") {
    //return errorMessagesPage1;
    $('#genericErrorContainer').replaceWith(errorHTML);
    $('#errorMessages').after(errorMessagesPage1);
    return $('#genericErrorContainer').html();
  }
  return "";

}

function submitVerifyPage2()
{
  return "";
}

function formSubmitPage1()
{
  if (submitVerifyPage1()) document.QuotesForm.submit();
}

function quote_form_1_validate(){
  return submitVerifyPage1();
}

function quote_form_2_validate(){
  return submitVerifyPage2();
}



var MAX_TRIPS = 8;
var tripCount = 2;
  
function addTrip()
{
  tripCount++;
  
  var tripTitle = "Trip " + tripCount;
  var tripFrom = "trip" + tripCount + "From";
  var tripTo = "trip" + tripCount + "To";
  var tripDepartureDate = "trip" + tripCount + "DepartureDate";
  var tripTime = "trip" + tripCount + "Time";
  var tripClass = "trip" + tripCount + "Class";

  var s = 
    '<div class="group-trip-search-field">' + 
    '<div class="trip2">' + tripTitle + '<br />' +
    '</div>' +
    '<div class="from">From:<br />' +
    '<input type="text" name="' + tripFrom + '" value="" class="from-field" />' +
    '</div>' +
    '<div class="to">To:<br />' +
    '<input type="text" name="' + tripTo + '" value="" class="to-field" />' +
    '</div>' +

    '<div class="departure">Departure Date:<br />' +
    '<input type="text" name="' + tripDepartureDate + '" id="' + tripDepartureDate + '" ' +
    'value="" class="departure-field" />' +

    '</div>' +
    '<script type="text/javascript" charset="utf-8">' +  
    'Date.format = "mm/dd/yyyy";' + 
	"$(function() {$('#" + tripDepartureDate + "').datePicker();});" +
    '</script>' +

    '<div class="trip-time">Time:<br/>' +
    '<span class="departure">' +
    '<input type="text" name="' + tripTime + '" value="" class="time-field" />' +
    '</span></div>' +
      
    '<div>Class:<br/>' +
    '<span class="field-float-left">' +
    '<select id="class1" class="select-box-small" name="' + tripClass + '">' +
    '<option value="First" selected="selected">1st</option>' +
    '<option value="Second">2nd</option>' +
    '</select>' +
    '</span> </div>' +
    '</div>' +
    '<div class="clear"></div>' ;

    if (tripCount <= MAX_TRIPS) {      
      $('#appendTrip').append(s);
	  $('#totalTickets').val(tripCount);
	}
    else {
      tripCount--;
    }

}

var MAX_PASSES = 8;
var passCount = 1;

function addPass()
{
  passCount++;
  var railPassName = "railPassName" + passCount;
  var duration = "duration" + passCount;
  var passClass = "passClass" + passCount;

  var s = 
    '<div class="group-trip-search-field">' +
    '<div class="from">Rail Pass Name:<br />' +

    '<input type="text" name="' + railPassName + '" value="" class="from-field" />' +
    '</div>' +
    '<div class="from">Duration:<br />' +
    '<input type="text" name="' + duration  + '" value="" class="from-field" />' +
    '</div>' +
    '<div>Class:<br/>' +
    '<span class="field-float-left">' +
    '<select id="time" class="select-box-small" name="' + passClass + '" >' +
    '<option value="First" selected="selected">1st</option>' +
    '<option value="Second">2nd</option>' +
    '</select>' +
    '</span> </div>' +
    '</div>' ;

    if (passCount <= MAX_PASSES) {
      $('#appendPass').append(s);
	  $('#totalPasses').val(passCount);
    }
    else {
      passCount--;
    }

}

//From : ../reg/contact_us.js ____________
function isValidEmailId(str)
{
  var len = str.length;
  if (len < 5) return false;

  var atIndex = str.indexOf('@');
  if (atIndex == -1 || atIndex == 0) return false;

  var atLastIndex = str.lastIndexOf('@');
  if (atIndex != atLastIndex) return false;

  var dotIndex = str.indexOf('.', atIndex);
  if (dotIndex == -1) return false;
  if ((atIndex+1) == dotIndex) return false;
  if ((dotIndex+1) == len) return false;
  return true;
}

function contactUsSubmitVerify()
{
  var errorHTML = 
    '<div id="genericErrorContainer" style="display: block;" >' +
    '<div class="error-box-top"></div>' +
    '<div class="error-box-mid">' +
    '<div class="error-sign"></div>' +
    '<div class="error-box-message">' +
    '<p id="contact_us_error_message">Please correct the following errors and then continue:' +
    '<br />' +
    '</p>' +
    '<p id="errorMessages">' +
    '</p>' +
    '</div>' +
    '<div class="clear"></div>' +
    '</div>' +
    '<div class="error-box-btm"></div>' +
    '</div';

  var fullName = $('#full-name').val();
  var email = $('#email').val();
  var confirmEmail = $('#confirm-email').val();
  var errorMessages = "";

  if (fullName == "")
    errorMessages += "The name field needs to be filled in<br>";

  if (email == "") {
    errorMessages += "The email address field needs to be filled in<br>";
  }
  else
    if (!isValidEmailId(email))
      errorMessages += "Email address has invalid format<br>";

  if (email != confirmEmail)
    errorMessages += "The two email address fields should be identical<br>";

  if (errorMessages != "") {
    $('#genericErrorContainer').replaceWith(errorHTML);
    $('#errorMessages').after(errorMessages);
    return $('#genericErrorContainer').html();
  }
  return "";

}

function contact_us_validate()
{
  return contactUsSubmitVerify();
}

//From : ../reg/fs.js ____________
var displayTextBoxes = false;

function FsData() {
  this.urls = new Array();
  this.urls["fsRequest"] = "/rail/point_to_point/results.htm";
  this.urls["fsLater"] = "/rail/point_to_point/later.htm";
  this.urls["fsVpRequest"] = "/rail/point_to_point/vp_trip_result.htm";
  this.urls["fsVpLater"] = "/rail/point_to_point/vp_trip_later.htm";
  this.urls["fsPhRequest"] = "/rail/point_to_point/passholderresults.htm";
  this.urls["fsAmtrakRequest"] = "/rail/point_to_point/amtrakptpresults.htm";
}
  
function getBrowserType()
{
  var browserName = navigator.appName.toLowerCase();
  var browserUserAgent = navigator.userAgent.toLowerCase();

  var browserType = "X";  // some unknown browser

  if (browserName.indexOf("microsoft") >= 0) {
    browserType = "I";
  }
  else if (browserName.indexOf("netscape") >= 0) {
    browserType = "N";
  }
  else if (browserUserAgent.indexOf("aol") >= 0) {
    browserType = "A";
  }
  else if (browserUserAgent.indexOf("opera") >= 0) {
    browserType = "O";
  }
  return browserType;
}

function getBrowserVersion()
{
  var browserVersion = navigator.appVersion;
  for (var v = 3; v <= 6; v++) {
    if (browserVersion.indexOf(v + ".") >= 0) return v;
  }
  return 0;
}

function doTextBoxes() {
  var browserType = getBrowserType();
  var ver = getBrowserVersion();
  return ((browserType == "N" && ver >= 5) || 
          (browserType == "I" && ver >= 4) ||
           browserType == "A");
}

function binSearch(toFind, array, low, high)
{
  var mid = Math.floor( (low+high)/2 );
  if (low > high) {
    return -1;
  }
  var matchResult = match(toFind, array[mid].text);
  if (low == high) {
    return (matchResult == 0 ) ? mid : -1;
  }
  else if (matchResult == 0) {
    return mid;
  }
  else if (matchResult < 0) {
    return binSearch(toFind, array, low, mid-1);
  }
  else {
    return binSearch(toFind, array, mid+1, high);
  }
}

function match(toFind, subject)
{
  var toFindLC = toFind.toLowerCase();
  var subjectLC = subject.toLowerCase();
  var toFindLCLen = toFindLC.length;
  if (toFindLCLen > 0 && toFindLC == subjectLC.substr(0, toFindLCLen)) {
    return 0;
  }
  else {
    return (toFindLC < subjectLC) ? -1 : +1;
  }
}

function selectFirstMatch(city, index, fromTo)
{
  var array = document.fspage[fromTo].options;
  for (var i = index; i > 0; i--) {
    if (match(city, array[i - 1].text) != 0) break;
  }	    
  return i;
}

function hOnKeyUp(fromTo)
{
  var selectBox = document.fspage[fromTo];
  var array = selectBox.options;
  var city = document.fspage["TXT_" + fromTo].value;

  var index = binSearch(city, array, 0, array.length-1);

  if ( index == -1 ) {
    selectBox.selectedIndex = -1;
  }
  else  {
    var newIndex = selectFirstMatch(city, index, fromTo);
    array[newIndex].selected = true;
  }
}

function hOnBlur(fromTo)
{
  var selectWidget = document.fspage[fromTo];
  var array = selectWidget.options;
  var index = selectWidget.selectedIndex;
  if (index >= 0) {
    document.fspage['TXT_' + fromTo].value = array[index].text;
  }
}

function request_text_box(fromTo, heading) {
  if (displayTextBoxes) {
    document.write(heading);
    var tabIndex = (fromTo == 'F') ? 1 : 2;
    document.write('<input autocomplete="off" type="text" ' +
      'name="TXT_' + fromTo + '" ' +
      'size="20" onKeyUp="hOnKeyUp(\'' + fromTo + '\')" ' +
      'onBlur="hOnBlur(\'' + fromTo + '\')" ' +
      'TABINDEX="' + tabIndex + '"><p>');
  }
}

displayTextBoxes = doTextBoxes();



// New FS
function showPopup(pURL) {
  var cWidth= 420;
  var cHeight= 625;
  var cParams= "status=1,toolbar=1,scrollbars=1,location=0,menu=1,resizable=1";

  var width = (showPopup.arguments[1] > 0) ? showPopup.arguments[1] : cWidth;
  var height = (showPopup.arguments[2] > 0) ? showPopup.arguments[2] : cHeight;
  var params = (showPopup.arguments[3]) ? showPopup.arguments[3] : cParams;
  popupWindow = window.open(pURL,
                            "popupWindow",
                            "width=" + width + "," +
                            "height=" + height + "," +
                            params);
  if (popupWindow.focus) popupWindow.focus();
}
function fareDebug(countrySite, stateId, solutionIndex, klass, step) {
  showPopup("/fs/" + countrySite + "/FSServe?fn=fareDebug&stateId=" + 
            stateId + "&solutionIndex=" + solutionIndex +
     "&klass=" + klass + "&step=" + step);
}
function fareRules(countrySite, stateId, solutionIndex, klass, step) {
  showPopup("/fs/" + countrySite + "/FSServe?fn=fareRules&stateId=" + 
            stateId + "&solutionIndex=" + solutionIndex +
     "&klass=" + klass + "&step=" + step);
}
function showAccomodations(countrySite, stateId) {
  showPopup("/fs/" + countrySite + "/FSServe?fn=showAccomodations&stateId=" +
            stateId, 420, 400);
}
function book(widget, value) {
  document.PtpResults.fareSelect.value = value;
  //alert(document.PtpResults);
  //document.PtpResults.submit();
  return true;
}
function selectFare(widget, value) {
  document.PtpResults.fareSelect.value = value;
  document.PtpResults.submit();
  return false;
}
function selectFare1(form, value) {
  form.fareSelect.value = value;
  form.submit();
  return false;
}

function mask(f) {if(isNaN(parseInt(f.value))) f.value= "";}

function enableRT(f) {
    f.d1.disabled=false;
    f.m1.disabled=false;
    f.t1.disabled=false;
}
function disableRT(f) {
    f.d1.disabled=true;
    f.m1.disabled=true;
    f.t1.disabled=true;
}
function initializeRT(f) {
  var rtContr = f.r[0];
  if (rtContr == null) return; 
  if (f.r[0].checked) {
    enableRT(f);
  }
  else {
    disableRT(f);
  }
}

//var dots;
//var count=0;
function wait_page_on_load(mainDiv, dotsDiv, img, width, height, countrySite){
  //dots = dotsDiv;
  var key = getFunctionKey();
  var fsData = new FsData();
  var finurl = "/" + countrySite + fsData.urls[key] + window.location.search;
  window.location.replace(finurl);

  if(document.getElementById&&!(navigator.userAgent.indexOf("5.2")>-1)){
    mainDiv.style.backgroundImage = img;
    mainDiv.style.position = "relative";
    mainDiv.style.width = width;
    mainDiv.style.height = height;
    mainDiv.style.backgroundRepeat = "no-repeat";

//    if(!document.all) {
//      animate();
//    }
  }
}
//function animate(){
//  wait = "We are searching for your ticket(s) ";
//  
//  switch (count){
//    case 0:dots.firstChild.nodeValue = wait+"";count++;break;
//    case 1:dots.firstChild.nodeValue = wait+".";count++;break;
//    case 2:dots.firstChild.nodeValue = wait+"..";count++;break;
//    case 3:dots.firstChild.nodeValue = wait+"...";count++;break;
//    case 4:dots.firstChild.nodeValue = wait+"....";count++;break;
//    case 5:dots.firstChild.nodeValue = wait+".....";count++;break;
//    default:dots.firstChild.nodeValue = wait+"......";count=0;
//  }
//  setTimeout("animate()",500);
//}

// Second argument is an optional country code
// Only the cities that belongs to such country will be returned

function setupPTP(countrySite) {
/*
  var countryIndex = 1;
  var filterCountryCode = setupPTP.arguments[countryIndex];
  if ((typeof(document.form1)!="undefined")&&(typeof(document.form1.from0)!="undefined")){
  // setTimeout("initialize(document.form1.F0,document.form1.T0, 
  //  document.form1.d0, true, countrySite)",900);
    initialize(document.form1.from0,document.form1.to0, document.form1.deptDate0, true,
      countrySite, filterCountryCode);
//    initializeRT(document.form1);
   document.form1.from0.onfocus= function() {
     handleFocus(0);
   }
   document.form1.to0.onfocus= function() {
     handleFocus(1);
   }
  }
*/  
}


function showPtpPopunder(url) {
  ptpPopunder=window.open(url, "ptpPopunder", "status=yes,toolbar=yes,location=yes,menubar=yes,directories=yes,resizable=yes,scrollbars=yes,width=800,height=600");
  ptpPopunder.blur();
  window.focus();
}
  
function getFunctionKey() {
  var fnName = "fn";
  var query = window.location.search;
  var mainEls = query.split("&");
  var result = null;
  
  for( var index in mainEls) {
    var element = mainEls[index];
    if( element.indexOf("fn=") > -1) {
      //this is the one
      var subEls = element.split("=");
      if( subEls.length == 2) {
        result = subEls[1];
        break;
      }
    }
  }
  return ( result!=null )? result : "fsRequest";
}

///////  new wait page function

function g3_wait_page_on_load(countrySite)
{
  var key = getFunctionKey();
  var fsData = new FsData();
  var finurl = "/" + countrySite + fsData.urls[key] + window.location.search;
  window.location.replace(finurl);
}

//From : ../reg/city_suggest.js ____________

selectItem=function(event){
  event.preventDefault();
  var fields = 
    $(this).parents('form:eq(0),body').find('button,input,textarea,select');
  var index = fields.index( this );
  if ( index > -1 && ( index + 1 ) < fields.length ) {
    fields.eq( index + 1 ).focus();
  }
  return false;
}


reinitialize_cities=function() {

  var urlStr = '';
  amtrakReq=0;
  if(document.form1 != undefined && document.form1.isAmtrakRequest != undefined) {
	  amtrakReq=document.form1.isAmtrakRequest.value;
  }
  if(amtrakReq == 0) {
     urlStr = "../../../biz/city_dropdown.jsp";
  } else {
    urlStr = "../../../biz/amtrak_city_dropdown.jsp";
   }

  $(".city-input").autocomplete(urlStr,
    {
      delay:10,
      minChars:1,
      matchSubset:1,
      matchContains:1,
      cacheLength:100,
      autoFill:true,
      scroll:false
     }
   );

   $(".city-input").result(selectItem);
}

$(document).ready(function(){
  reinitialize_cities();
});

//From : ../reg/portion-script.js ____________
function getSaleCountry()
{
  var saleCountry = $('#saleCountry').val();
  if (saleCountry == undefined) saleCountry = 'us';
  return saleCountry;
}

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();' ");
  } 
  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();' ");
  } 
  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>");   
  output.push("<div class='trip-time'>Time:<br> <span class='field-float-left'> <select name='time"+index+"' id='time"+index+"' class='time-field'> <option value='morning' >12am to 12pm</option> <option value='afternoon'>12pm to 6pm</option> <option value='evening'>6pm to 12am</option> ")
  if(isAmtrakReq == 0) {
    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 name='fromCity"+index+"' class='from-field' value='' type='text'/> <input name='from"+index+"' type='hidden'> </div>");
  output.push("<div class='to'>To:<br> <input name='toCity"+index+"' class='to-field' value='' type='text'/> <input 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>");  
  output.push("<div class='trip-time'>Time:<br> <span class='field-float-left'> <select name='time"+index+"' id='time"+index+"' class='time-field'> <option value='morning' >12am to 12pm</option> <option value='afternoon'>12pm to 6pm</option> <option value='evening'>6pm to 12am</option>  ");
  if(isAmtrakReq == 0) {
    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-->");
  $(function()
  {
    $('#deptDate'+index).datePicker().val(new Date().asString()).trigger('change');
    if(isAmtrakReq == 0) {
      $('#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;
  for(i=0; i<objForm.roundtrip.length; i++) {
    if(objForm.roundtrip[i].checked == true) {     
      indexVal = objForm.roundtrip[i].value;
      break;
    }
  }
  if(indexVal == 1) {      
    // get trip 1 details  
    if(eval('document.form1.from1') == undefined) { 
      howToRoundTripCheck();
    } 
    document.form1.from1.value = document.form1.to0.value;
    document.form1.to1.value = document.form1.from0.value;
    document.form1.fromCity1.value = document.form1.to0.value;
    document.form1.toCity1.value = document.form1.from0.value;    
  } 
  
  amtrakReq=0;
  if(document.form1 != undefined && document.form1.isAmtrakRequest != undefined) {
    amtrakReq=document.form1.isAmtrakRequest.value;
  }
  if(amtrakReq == 1) {
    if((document.form1.to0.value !=undefined && document.form1.from0.value != undefined)){
      var contents = document.getElementById("trip-search-field-cars");
      contents.innerHTML = "";
      var output = new Array();
      fromCity = document.form1.from0.value.toLowerCase();
      toCity = document.form1.to0.value.toLowerCase();
      if((fromCity.indexOf('sanford') >= 0 && toCity.indexOf('lorton') >= 0) || 
        (toCity.indexOf('sanford') >= 0 && fromCity.indexOf('lorton') >= 0))  {  
          output.push("<p>");
          output.push("This route allows travelers to ride with their cars. Let us know if you would like to take your car.");
          output.push("</p>");
          
          output.push("<div class='car-count'># of Cars:<br/>");
          output.push("<span class='field-float-left'>");  
          output.push("<select class='bike-field' name='nCars' id='nCars'>");          
          output.push("<option value='1' selected='selected'>1</option>");            
          output.push("<option value='1'>2</option>");
          output.push("<option value='2'>3</option>");
          output.push("</select>");
          output.push("</span>");
          output.push("</div>");
          
          output.push("<div class='car-type'>Type of car #1:<br/>");
          output.push("<span class='field-float-left'>");
          output.push("<select class='car-type-field' id='carType0' name='carType0'>");
          output.push("<option value='REGVEH' selected='selected'>Regular</option>");
          output.push("<option value='MOTOVWH'>Motor Cycle</option>");          
          output.push("<option value='OVSVEH'>Oversize Vehicle</option>");
          output.push("</select>");
          output.push("</span>");
          output.push("</div>");
          output.push("<div class='clear'></div>");   
        }
      contents.innerHTML  = contents.innerHTML +output.join("");
    }
  }
  
}


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() {
  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) {      
    // get trip 1 details
    document.form1.fromCity1.value = document.form1.to0.value;
    document.form1.toCity1.value = document.form1.from0.value;
    document.form1.from1.value = document.form1.to0.value;
    document.form1.to1.value = document.form1.from0.value;
    document.form1.fromCity1.disabled=true;
    document.form1.toCity1.disabled=true;
  }
  amtrakReq=0;
  if(document.form1 != undefined && document.form1.isAmtrakRequest != undefined) {
    amtrakReq=document.form1.isAmtrakRequest.value;
  }
  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 updateRoundTripDate() {
  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) {      
    // get trip 1 details
    deptDate = document.form1.deptDate0.value;
    if(deptDate != '') {
      str1 = deptDate.split("/");
      
      month = parseInt(str1[0],10)-1;
      day = parseInt(str1[1],10);
      year = str1[2];
      
      var myDate=new Date();
      // alert(' my date 1 : ' + myDate);
      myDate.setFullYear(year,month, day);
      // alert(' my date : ' + myDate);
      myDate.setDate(myDate.getDate()+5);
      
      //     alert(' after 5 , my date : ' + myDate);
      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;
      
      document.form1.deptDate1.value = newDate;
      $(function()
      {
        $('#deptDate1').datePicker().val(newDate).trigger('change');
        $('#deptDate1').dpSetStartDate(deptDate);
        $('#deptDate1').dpSetEndDate(new Date().addDays(365).asString());
      });
    }
    
  }
  
}

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 populateYouthAge(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 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+"' size='2' class='tiny' ");
      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 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() {
  for(j=0; j<document.form1.roundtrip.length; j++) {
    if(document.form1.roundtrip[j].checked == true) {
      rVal = j;   
    }
  }
  if(rVal == 1) {
    if(eval('document.form1.deptDate1') != undefined) {
      $('#deptDate0').bind('dpClosed', 
        function(e, selectedDates)    {
          var d = selectedDates[0];
          if (d) {
            d = new Date(d);
            $('#deptDate1').dpSetStartDate(d.addDays(0).asString());
          }
        }
      );
    }
  }
  
  if(rVal == 1 && eval('document.form1.from1') == undefined) { 
    roundTripCheck();
  }
  
}

function roundTripCheck() {
  
  for(j=0; j<document.form1.roundtrip.length; j++) {
    if(document.form1.roundtrip[j].checked == true) {
      rVal = j;   
    }
  }
  // check whether the current request is amtrak
  amtrakReq=0;
  if(document.form1.isAmtrakRequest != undefined) {
    amtrakReq = document.form1.isAmtrakRequest.value;
  }
  maxDeptDateDaysLimit = 365;
  if(amtrakReq != 0) {
    maxDeptDateDaysLimit = 335;
  }
  
  
  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;
    if(anotherTrip != undefined) {
      anotherTrip.innerHTML="";
    }
    $('#deptDate0').datePicker().val($('#deptDate0').val()).trigger('change');
    $('#deptDate0').dpSetEndDate(new Date().addDays(maxDeptDateDaysLimit).asString());  
    document.form1.deptDate0.value=deptdate;
  }
  
  // if rVal is 1, populate the From1 and To1 in second trip
  if(rVal  == 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;;
    
    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);
    
    // 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;
    document.form1.deptDate1.value=deptdate;
    
    document.form1.fromCity1.disabled=true;
    document.form1.toCity1.disabled=true;
    if(anotherTrip != undefined) {
      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(maxDeptDateDaysLimit).asString());
    $('#deptDate1').dpSetEndDate(new Date().addDays(maxDeptDateDaysLimit).asString());
    
    if(eval('document.form1.deptDate1') != undefined) {
      $('#deptDate0').bind('dpClosed', 
        function(e, selectedDates)    {
          var d = selectedDates[0];
          if (d) {
            d = new Date(d);
            $('#deptDate1').dpSetStartDate(d.addDays(0).asString());
          }
        }
      );
    }
    
    updateRoundTripDate();
    
    $('#deptDate0').attr({ 
      onChange: "updateRoundTripDate();"
      });
    
  }
  
  if(rVal  == 2) {
    
    rows = document.form1.rows.value;
    
    if(rows == undefined) {
      rows = 6;
    }
    if(rows < 6) {
      rows = 6;
    }
    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,amtrakReq);
    for(i=1; i<rows; i++){
      contents.innerHTML  = contents.innerHTML + addPortionTrip(i,2, amtrakReq);
    }
    
    for(i=0; i<rows; i++){
      $('#from'+i).val(fromCityArray[i]);
      $('#to'+i).val(toCityArray[i]);
      
      if(deptDateArray[i] != '') {
        $('#deptDate'+i).datePicker().val(deptDateArray[i]).trigger('change');
      } else {
        $('#deptDate'+i).datePicker().val($('#deptDate'+(i-1)).val()).trigger('change');
      }

      if(deptTimeArray[i] != '') {
        $('#time'+i).val(deptTimeArray[i]);
      }
      //eval('document.form1.to'+i+'.value='+toCityArray[i]);
      //eval('document.form1.deptDate'+i+'.value='+deptDateArray[i]);
      //eval('document.form1.time'+i+'.value='+deptTimeArray[i]);
      
      $('#deptDate'+i).dpSetEndDate(new Date().addDays(365).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 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 {
    //var contents = document.getElementById("trip-frame");
    // contents.innerHTML  = contents.innerHTML + addPortionTrip(parseInt(index));
    //alert(' contents ' + contents);
    // document.getElementById("trip-frame").innerHTML += addPortionTrip(parseInt(index));
    $('#trip-frame').append(addPortionTrip(parseInt(index),2, 0));
    document.form1.rows.value=(index+1);
    $('#deptDate'+index).datePicker().val(getNextMonthDate()).trigger('change');
    $('#deptDate'+index).dpSetEndDate(new Date().addDays(365).asString());
    
    reinitialize_cities();  //NK
  }
  
}



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 = '/' + getSaleCountry() + '/rail/point_to_point/multioverview.htm?strAction='+strAction+'&fromFareType='+fareType;      
    multiForm.submit();
  }
}

function portionSubmit(formName, strAction) {
  checkRTCompatibility(formName);
  portionForm = document.forms[formName];
  // get value of isFareCompatible
  result = portionForm.isFareCompatible.value;
  message = portionForm.rtMessage.value;
  editPortionId = portionForm.editPortionId.value;
  //  alert(' isfarect ' + result);
  //  alert("editPortionId : " + editPortionId);
  
  if(result == 'true') {
    portionForm.strAction.value=strAction;
    portionForm.action = '/' + getSaleCountry() + '/rail/point_to_point/portionresult.htm';
    portionForm.submit();
  } else {
    res = confirm(message);
    if(res == true){
      submitMandatoryRTFares(formName, editPortionId);
      //      modifyPortion(formName, editPortionId);
    } else {
      return false;
    }
  }
}


function submitMandatoryRTFares(formName, portionId) {
  // alert('edit button ' + portionId);
  var objForm = document.forms[formName];   
  objForm.action = '/' + getSaleCountry() + '/rail/point_to_point/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;
  } 
  
  document.criteriaForm.minTime.value = startTime;
  document.criteriaForm.maxTime.value = endTime;
  
  var params='&'+ getCriteriaParams(criteriaForm, presultForm);
  //alert(' earlier params ' + params);
  //return false;
  
  
  
  portionForm = document.forms[presultForm]; 
  portionForm.action = '/' + getSaleCountry() + '/rail/point_to_point/portioncriteria.htm?'+'strAction='+strAction+params;      
  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;
  } 
  
  
  
  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.action = '/' + getSaleCountry() + '/rail/point_to_point/portioncriteria.htm?'+'strAction='+strAction+params;      
  portionForm.submit();
  
}


function getStartTimeHour(criteriaForm) {
  var slider_min  = parseInt(document.criteriaForm.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) {
  var slider_min  = parseInt(document.criteriaForm.minTime.value);
  var startTime = 0;
  if(slider_min > 0) {
    startTime = slider_min%24;
  }
  stTime = startTime * 2.5;
  return stTime;
}


function getEndTimeHour(criteriaForm) {
  var slider_max  =  parseInt(document.criteriaForm.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) {
  var slider_max  =  parseInt(document.criteriaForm.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 = document.portionHeaderForm.portionFareSelected.value;
  var connection0 = "";
  var connection1 = "";
  var connection2 = "";
  var fastest = "";
  var cheapest = "";
  var comfort = "";
  var firsttrainArriving = "";
  var lasttrainDeparting = "";
  
  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;
  }
  
  stTimeHour = getStartTimeHour(criteriaForm);
  stTimeMin = getStartTimeMin(criteriaForm);
  
  edTimeHour =  getEndTimeHour(criteriaForm);
  edTimeMin =  getEndTimeMin(criteriaForm);
  
  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;
  
  // 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;
  
  // 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 = '/' + getSaleCountry() + "/rail/point_to_point/portioncriteria.htm?"+params;
  
  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(" 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,
      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);
    }
  });
  objCritForm.processFlag.value = 'false';
  
  
}


function getIndicatorCSSscript(respText) {
  scriptIndex1 = respText.indexOf("<script>");
  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 editPortion(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 = '/' + getSaleCountry() + '/rail/point_to_point/portionresult.htm?portionId='+portionId+'&faresSelected='+faresSelected+'&strAction=edit';
  objForm.submit();
}

function modifyPortion(formName, portionId) {
  // alert('edit button ' + portionId);
  var objForm = document.forms[formName];   
  objForm.action = '/' + getSaleCountry() + '/rail/point_to_point/portionresult.htm?portionId='+portionId+'&strAction=edit';
  objForm.submit();
}


function addToCart(formName, btn) {
  actionName = '/' + getSaleCountry() + '/rail/point_to_point/add_to_cart.htm';
  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
    faqtable.setHeader('Close <img src="/redesign/images/img-arrow-collapse.jpg" alt="" />', 'View Fare & Accommodation Detail <img src="/redesign/images/img-arrow-expand.jpg"  alt="" />') //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 = '/' + getSaleCountry() + "/rail/point_to_point/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 = '/' + getSaleCountry() + "/rail/point_to_point/fareupgrade.htm?"+params;
  objResultForm.action = action;
  objResultForm.submit();
  
}



function upgradeAllPortions(presultForm) {
  
  objResultForm = document.forms[presultForm]; 
  
  var action = '/' + getSaleCountry() + "/rail/point_to_point/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 = '/' + getSaleCountry() + '/rail/point_to_point/passresult.htm?'+params;
  passForm.submit();
}


function modifyPass(formName, portionId) {
  // alert('edit button ' + portionId);
  var objForm = document.forms[formName];   
  objForm.action = '/' + getSaleCountry() + '/rail/point_to_point/passresult.htm?editPortionId='+portionId+'&strAction=edit';
  objForm.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 = '';
  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;
    }
  }
  
  // need to consider all the components
  // whichever component is clicked
  passForm.method='post';
  passForm.action = '/' + getSaleCountry() + '/rail/point_to_point/passresult.htm?portionId='+portionId+"&fareKey="+fareKey+'&faresSelected='+faresSelected+"&fromFareType="+fromFare+'&strAction=edit';
  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 = '/' + getSaleCountry() + '/rail/point_to_point/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 = '/' + getSaleCountry() + '/rail/point_to_point/passresult.htm?'+'strAction='+strAction+'&minTime='+minTime+'&maxTime='+maxTime+'&resultId='+resultId+'&portionId='+portionId+"&fareKey="+fareKey+'&faresSelected='+faresSelected+"&fromFareType="+fromFare;     
  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);
  }
  
  // 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;
    
    // 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;
    document.form1.deptDate1.value=deptdate;
    
    $('#deptDate0').datePicker().val($('#deptDate0').val()).trigger('change');
    $('#deptDate1').dpSetDisabled(false);
    $('#deptDate1').datePicker().val($('#deptDate1').val()).trigger('change');
    
    updateRoundTripDate();
    
    $('#deptDate0').attr({ 
      onBlur: "updateRoundTripDate();"
      });
  } 
}

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 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) { 
      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() {
  
  for(j=0; j<3; j++) {
    if(document.form1.roundtrip[j] != undefined && document.form1.roundtrip[j].checked == true  ) {
      rVal = j;   
    }
  }
  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()); 
  }
  
  // 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;;
    
    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;
    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();"
      });
    
  }
  
  if(rVal  == 2) {
    
    rows = document.form1.rows.value;
    
    if(rows == undefined) {
      rows = 3;
    }
    if(rows < 3) {
      rows = 3;
    }
    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(i=1; i<rows; i++){
      contents.innerHTML  = contents.innerHTML + addPortionTrip(i,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()).trigger('change');
	      }
      // }
      if(deptTimeArray[i] != '') {
        $('#time'+i).val(deptTimeArray[i]);
      }
      
      //eval('document.form1.to'+i+'.value='+toCityArray[i]);
      //eval('document.form1.deptDate'+i+'.value='+deptDateArray[i]);
      //eval('document.form1.time'+i+'.value='+deptTimeArray[i]);
      
      $('#deptDate'+i).dpSetEndDate(new Date().addDays(365).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;
}



//From : ../reg/utilities.js ____________
function truncateString(str, maxLength) {
  if (str.length <= maxLength)
    return str;
  return str.substring(0, maxLength-1);
}

function URLDecode(encodeStr) {
  return unescape(String(encodeStr).replace(/\+/g, " "));
}

function URLEncode(str) {
  return escape(str.replace(/\ /g, "+"));
}

// Removes the leading zeros (eg. 08 become 8 for a month value)
function trimLeftZeros(s) {
  return s.replace(/^0+/, '');
}

// Retrives the element from the document by its id 
function getElement(id) {
  return (document.all)? document.all[id] : document.getElementById(id);
}
  
// Retrives the "single value control" value
function getValue( ctr ) {
  var result = null;
  if( ctr!=null ) { // sanity check
    var form = (getValue.arguments[1]!=null)? getValue.arguments[1]: null;
    if( form!=null ) {
      // radio can be evaluated only within a form with widget name(no id in IE)
      // alert("Inside getValue with ctr.len="+form[ctr].length)
      for( var i=0; i<form[ctr].length; i++ ) {
        if( form[ctr][i].checked == true ) {
          result = form[ctr][i].value;
        }
      }
    }
    else {
      // Test if ctr is a "select-one" or a text input
      var index=ctr.selectedIndex;
      result = (index==null)? ctr.value: ctr.options[index].value;
    }
  }
  return result;
}

// Sets the "single value control" value
function setValue( ctr, value ) {
  if(ctr==null) return; // sanity check
  var form = (setValue.arguments[2]!=null)? setValue.arguments[2]: null;
  if( form!=null) {
    // radio can be evaluated only within a form with widget name (no id for IE)
    for( var i=0; i<form[ctr].length; i++ ) {
      if( form[ctr][i].value == value ) {
        form[ctr][i].checked = true;
        break;
      }
    }
  }
  else if( ctr.type=="text" || ctr.type=="hidden") {
    ctr.value = value;
  }
  else if(ctr.type == "select-one") {
    // find the right index for the value
    var indexFound = false;
    for( var i=0; i< ctr.options.length; i++) {
      if( ctr.options[i].value==value) {
        ctr.options[i].selected = true;
        indexFound = true;
      }
    }
    // if no index found select the option at index zero
    if(!indexFound && ctr.options.length>0) {
      ctr.options[0].selected = true;
    }
  }
}

// Disables-enables the control based on the flag value
function disable(ctr, flag) {
  ctr.disabled = flag;
}

// Make page element visible or not based on the passed flag (true/false)
function setVisibility(element, flag) {
  if (document.layers) {
    element.visibility= flag? 'show' : 'hide';
  }
  else {
    element.style.visibility = flag? 'visible' : 'hidden';
  }
}

// Display or remove a given page element based on the passed flag (true/false)
function setDisplay(element, flag) {
  if (document.layers) 
    element.display = (flag)? 'block' : 'none';
  else
    element.style.display = (flag)? 'block' : 'none';
}
  
// Disables-enables the widget specified by id based on the flag value
function disableWidget(id, flag) {
  disable(getElement(id), flag);
}

// Helper for the getValue by a widget id
function getWidgetValue(id) {
  var result = null;
  var ctr = getElement(id);
  var formName = ( getWidgetValue.arguments[1]!=null )?
      getWidgetValue.arguments[1] : null;
  if( formName!=null) {
    result = getValue(id, document.forms[formName]);
  }
  else if( ctr!=null ) {
    result = getValue(ctr);
  }
  return result;
}
  
  

// Helper for the setValue by a widget id 
function setWidgetValue(id, val) {
  var ctr = getElement(id);
  var formName = (setWidgetValue.arguments[2]!=null)? 
    setWidgetValue.arguments[2]: null;
  if(formName!=null) {
    setValue(id, val, document.forms[formName]);
  }
  else if (ctr!=null) {
    setValue(ctr, val);
  }
}

function fillForm(theForm, queryString){
  var pairs= queryString.substring(1).split("&");
  var map = new Object();
  for (var i = 0; i < pairs.length; i++) {
    var pair= pairs[i].split("=");
    var key = pair[0];
    map[key] = pair[1];;
  }

  var els = theForm.elements; 
  for(var i=0; i<els.length; i++){
    var value = map[els[i].name]; 
    if (typeof(value) != "undefined") {
      switch(els[i].type){
        case "text":
        case "hidden":
    els[i].value = URLDecode(value);
      break;
        case "radio":
        case "checkbox":
          if (URLEncode(els[i].value) == value)
            els[i].checked = true;
    else
            els[i].checked = false;
        break;
      }
    }
  }
}


if ( isSite("studentuniverse") || isSite("travelocity") )
  loadStylesheets();

function isSite(site)
{
  var url = document.URL;
  if (url.indexOf(site) != -1)
    return 1;
  return 0;
}

function submitVerify()
{
  var dialog = 
    "Before purchasing this product, please understand that the " +
    "condition of this product is that travel must be begin within " +
    "2 months of the date of purchase and once travel has started it " + 
    "must be completed within 2 months.";

  document.ProductForm.onsubmit=function() {
  if (confirm(dialog))
    return true;
  else
    return false;
  }
}
  
function commissionVerify()
{
  var f1 = document.ShipInfo.commission;
  var f2 = document.ShipInfo.agencyServiceFee;
  if (f1 == undefined || f2 == undefined) return true;
  var commission = f1.value;
  var agencyServiceFee = f2.value;
  var dialog = 
    "The current commission on this booking is $" + commission + "\n" + 
    "Press Ok to continue the checkout process, or Cancel to go back and " +
    "add an agency fee.";
  
  if (agencyServiceFee == "0.00" || agencyServiceFee == "") {
    if (confirm(dialog)) return true; else return false;
  }
  else {
    return true;
  }
}
  
function showPopup(pURL) {
  var cWidth= 420;
  var cHeight= 625;
  var cParams= "status=1,toolbar=1,scrollbars=1,location=0,menu=1,resizable=1";
 
  var width = (showPopup.arguments[1] > 0) ? showPopup.arguments[1] : cWidth; 
  var height = (showPopup.arguments[2] > 0) ? showPopup.arguments[2] : cHeight; 
  var params = (showPopup.arguments[3]) ? showPopup.arguments[3] : cParams; 
  popupWindow = window.open(pURL,
                            "popupWindow",
                            "width=" + width + "," +
                            "height=" + height + "," +
                            params); 
  if (popupWindow!=null) popupWindow.focus();
}

function switchPage(pURL) {
  var cWidth= 420;
  var cHeight= 625;

  var width = (switchPage.arguments[1] > 0) ? switchPage.arguments[1] : cWidth; 
  var height = (switchPage.arguments[2] > 0) ? switchPage.arguments[2] : cHeight; 
  window.resizeTo(width, height);
  window.location.href= pURL;
}

function switchSite(pURL) {
  if (this.opener) {  
    opener.location= pURL;
    close();
  }
  else {
    this.location= pURL;
  }
}

function deletePopupClose(status) {
  if (status == 1) opener.location= "$yesURL";
  window.close();
}                                                                            

function fsCategory(categoryName) {
  showPopup("/us/rail/fares_schedules/fare_categories/" + categoryName + ".htm",
            380, 350, 
            "status=1,toolbar=0,location=0,menu=1,resizable=1,scrollbars=1");
}

function getStylesheet() {
  return '<link rel=stylesheet type="text/css" href="' 
         + ((navigator.appName == 'Microsoft Internet Explorer') 
            ? '/css/swiss_en.css' 
            : '/css/swiss_en_ns.css')
         + '">';
}
                                
function processGoTo() {
  var value= document.goToForm.GoTo.options[
                            document.goToForm.GoTo.selectedIndex].value;
  if (value != '../travel_agent.htm') {
    window.open(value, '_top');
  }
  else {
    showPopup(value, 424, 280, 
              "status=0,toolbar=0,location=0,menu=0,resizable=1,scrollbars=0");
  }
}

function displayCityPopunder(url){
  win2=window.open(url, "city_promo", "status=no,toolbar=no,location=no,menu=no,resizable=yes,scrollbars=no,width=510,height=310");
  win2.blur();

  window.focus();
}

function loadStylesheets()
{
  //Load style sheets
  browser_version= parseInt(navigator.appVersion);
  browser_type = navigator.appName;
  platform = navigator.platform;
  platform_slice=platform.slice(0, 3);

  if (browser_type == "Microsoft Internet Explorer" && (browser_version >= 4))
  {
    document.write("<link REL='stylesheet' href='/iestyle.css' TYPE='text/css'>");
  }
  else 
    if (browser_type == "Netscape" && (platform_slice == "Mac") && 
      (browser_version != 5)) {
      document.write("<link REL='stylesheet' href='/macstyle.css' TYPE='text/css'>");
  }

  else 
    if (browser_type == "Netscape" && (browser_version >= 4)) {
      document.write("<link REL='stylesheet' href='/nsstyle.css' TYPE='text/css'>");
  }
} // end loadStylesheets()

// ------------------ travelcuts rollover functions ------------------ //

function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}

function preload()
{
  MM_preloadImages(
    '/images/travelcuts/bookflight1.gif',
    '/images/travelcuts/onlinetravelshop1.gif',
    '/images/travelcuts/hotdeals1.gif',
    '/images/travelcuts/ebulletin1.gif',
    '/images/buttons/submit1.gif',
    '/images/buttons/close1.gif',
    '/images/buttons/buy_now1.gif',
    '/images/buttons/get_fares_schedules1.gif',
    '/images/buttons/add_to_shopping_cart_bgd1.gif',
    '/images/buttons/add_to_shopping_cart1.gif',
    '/images/buttons/yes1.gif'
  );
}

function processing_init() {
  MM_preloadImages(
    '/images/buttons/processing_order.gif',
    '/img/misc/processing_train.gif'
  );
}

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

function showProcessing() {    
  if (document.layers) {
    document.submit_order.visibility= "hidden";
    document.processing_order.visibility= "visible";
  }

  if (document.all) {
    submit_order.style.visibility= "hidden";
    processing_order.style.visibility= "visible";
  }
    
  if (!document.all && document.getElementById) { 
    document.getElementById("submit_order").style.visibility= "hidden";
    document.getElementById("processing_order").style.visibility= "visible";
  }
}

function textCounter(field, cntfield, maxlimit) 
{
  if (field.value.length > maxlimit)
  { // text too long...trim it!
    field.value = field.value.substring(0, maxlimit);
  }
  else if( cntfield != null )
  { // otherwise, update 'characters left' counter if exists
    cntfield.value = maxlimit - field.value.length;
  }
}


function MM_showHideLayers() { //v6.0
  var i,p,v,obj,args=MM_showHideLayers.arguments;
  
  for (i=0; i<(args.length-2); i+=3) {
    if ((obj=MM_findObj(args[i]))!=null) { 
      v=args[i+2];
      if (obj.style){ 
        obj=obj.style; 
        v=(v=='show')?'visible':(v=='hide')?'hidden':v; 
      }
      obj.visibility=v; 
    }
  }
}

function getQueryValue(key)
{
  var vars = parseQuery();
  return  vars[key];
}

function parseQuery()
{
  var queryVars = new Array();
  var query = window.location.search.substring(1);
  var pairs = query.split("&");
  
  for (var i=0;i<pairs.length;i++) {
    var pos = pairs[i].indexOf('=');
    if (pos >= 0) {
      var name = pairs[i].substring(0,pos);
      var value = pairs[i].substring(pos+1);
      queryVars[name] = value;
    }
  }
  return queryVars;
}
  
var RE_answers = new Array(20);
function flip(nr)
{
  var queCtr = document.getElementById("que"+nr);
  var ansCtr = document.getElementById("ans"+nr);
  if( queCtr==null || ansCtr==null) { 
    alert("Cotrol(s) null");
    return;
  }
  if( RE_answers[nr]==null ) {
    RE_answers[nr] = queCtr.innerHTML;
    queCtr.innerHTML = RE_answers[nr]+"<br/>"+ansCtr.innerHTML;
  }
  else {
    queCtr.innerHTML = RE_answers[nr];
    RE_answers[nr]=null;
  }
}
  
/** ======================================================================
 * Adds a given function to the onload event handler
 * It does not overwritte the page onload method but append to it
 * ======================================================================*/
function addOnloadEvent(func) { 
  var oldonload = window.onload; 
  if (typeof window.onload != 'function') { 
    window.onload = func; 
  }
  else { 
    window.onload = function() { 
      if (oldonload) { 
        oldonload(); 
      }
      func(); 
    }
  }
}

/** ======================================================================
 * Adds a given function to the onunload event handler
 * It does not overwritte the page onunload method but append to it
 * ======================================================================*/
function addOnunloadEvent(func) { 
  var oldonunload = window.onunload; 
  if (typeof window.onunload != 'function') { 
    window.onunload = func; 
  }
  else { 
    window.onunload = function() { 
      if (oldonunload) { 
        oldonunload(); 
      }
      func(); 
    }
  }
}

/** ======================================================================
 * Class StringBuffer used to efficiently append a lot of string
 * ======================================================================*/
function StringBuffer() { this.buffer = []; }

StringBuffer.prototype.append = function append(string) {
  this.buffer.push(string);
  return this;
};

StringBuffer.prototype.toString = function toString() {
  return this.buffer.join("");
};
  
// This function adds SIFR look to the text of all tags with dyn-header class
function fixHeader() {
  if(typeof(sIFR)=='object' && sIFR!=null) {
    //alert('sIFR valid object')
    sIFR.replace(tradegothic, {
      selector: '.dyn-header'
      ,css: [
        '.sIFR-root { text-align: left; font-weight: bold; color: #862c72; }'
        ,'a { text-decoration: none; }'
        ,'a:link { color: #862c72; }'
        ,'a:hover { color: #862c72; }'
      ],
      wmode: 'transparent'
    });
  }
  // else alert('sIFR NOT valid object')
}
  
/*
 * Date Format 1.2.3
 * (c) 2007-2009 Steven Levithan <stevenlevithan.com>
 * MIT license
 *
 * Includes enhancements by Scott Trenda <scott.trenda.net>
 * and Kris Kowal <cixar.com/~kris.kowal/>
 *
 * Accepts a date, a mask, or a date and a mask.
 * Returns a formatted version of the given date.
 * The date defaults to the current date/time.
 * The mask defaults to dateFormat.masks.default.
 */

var dateFormat = function () {
  var token = /d{1,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|[LloSZ]|"[^"]*"|'[^']*'/g,
    timezone = /\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g,
    timezoneClip = /[^-+\dA-Z]/g,
    pad = function (val, len) {
      val = String(val);
      len = len || 2;
      while (val.length < len) val = "0" + val;
      return val;
    };

  // Regexes and supporting functions are cached through closure
  return function (date, mask, utc) {
    var dF = dateFormat;

    // You can't provide utc if you skip other args (use the "UTC:" mask prefix)
    if (arguments.length == 1 && Object.prototype.toString.call(date) == "[object String]" && !/\d/.test(date)) {
      mask = date;
      date = undefined;
    }

    // Passing date through Date applies Date.parse, if necessary
    date = date ? new Date(date) : new Date;
    if (isNaN(date)) throw SyntaxError("invalid date");

    mask = String(dF.masks[mask] || mask || dF.masks["default"]);

    // Allow setting the utc argument via the mask
    if (mask.slice(0, 4) == "UTC:") {
      mask = mask.slice(4);
      utc = true;
    }

    var _ = utc ? "getUTC" : "get",
      d = date[_ + "Date"](),
      D = date[_ + "Day"](),
      m = date[_ + "Month"](),
      y = date[_ + "FullYear"](),
      H = date[_ + "Hours"](),
      M = date[_ + "Minutes"](),
      s = date[_ + "Seconds"](),
      L = date[_ + "Milliseconds"](),
      o = utc ? 0 : date.getTimezoneOffset(),
      flags = {
        d:    d,
        dd:   pad(d),
        ddd:  dF.i18n.dayNames[D],
        dddd: dF.i18n.dayNames[D + 7],
        m:    m + 1,
        mm:   pad(m + 1),
        mmm:  dF.i18n.monthNames[m],
        mmmm: dF.i18n.monthNames[m + 12],
        yy:   String(y).slice(2),
        yyyy: y,
        h:    H % 12 || 12,
        hh:   pad(H % 12 || 12),
        H:    H,
        HH:   pad(H),
        M:    M,
        MM:   pad(M),
        s:    s,
        ss:   pad(s),
        l:    pad(L, 3),
        L:    pad(L > 99 ? Math.round(L / 10) : L),
        t:    H < 12 ? "a"  : "p",
        tt:   H < 12 ? "am" : "pm",
        T:    H < 12 ? "A"  : "P",
        TT:   H < 12 ? "AM" : "PM",
        Z:    utc ? "UTC" : (String(date).match(timezone) || [""]).pop().replace(timezoneClip, ""),
        o:    (o > 0 ? "-" : "+") + pad(Math.floor(Math.abs(o) / 60) * 100 + Math.abs(o) % 60, 4),
        S:    ["th", "st", "nd", "rd"][d % 10 > 3 ? 0 : (d % 100 - d % 10 != 10) * d % 10]
      };

    return mask.replace(token, function ($0) {
      return $0 in flags ? flags[$0] : $0.slice(1, $0.length - 1);
    });
  };
}();

// Some common format strings
dateFormat.masks = {
  "default":      "ddd mmm dd yyyy HH:MM:ss",
  shortDate:      "m/d/yy",
  mediumDate:     "mmm d, yyyy",
  longDate:       "mmmm d, yyyy",
  fullDate:       "dddd, mmmm d, yyyy",
  shortTime:      "h:MM TT",
  mediumTime:     "h:MM:ss TT",
  longTime:       "h:MM:ss TT Z",
  isoDate:        "yyyy-mm-dd",
  isoTime:        "HH:MM:ss",
  isoDateTime:    "yyyy-mm-dd'T'HH:MM:ss",
  isoUtcDateTime: "UTC:yyyy-mm-dd'T'HH:MM:ss'Z'"
};

// Internationalization strings
dateFormat.i18n = {
  dayNames: [
    "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat",
    "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"
  ],
  monthNames: [
    "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
    "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"
  ]
};

// For convenience...
Date.prototype.format = function (mask, utc) {
  return dateFormat(this, mask, utc);
};
  
// This is the String object extension to remove all spaces or expression define
String.prototype.strip = function(exp) { 
  return this.replace(exp? exp : /\s/g,'');
}

//From : ../vendor/swfobject.js ____________
/**
 * SWFObject v1.5: Flash Player detection and embed - http://blog.deconcept.com/swfobject/
 *
 * SWFObject is (c) 2007 Geoff Stearns and is released under the MIT License:
 * http://www.opensource.org/licenses/mit-license.php
 *
 */
if(typeof deconcept=="undefined"){var deconcept=new Object();}if(typeof deconcept.util=="undefined"){deconcept.util=new Object();}if(typeof deconcept.SWFObjectUtil=="undefined"){deconcept.SWFObjectUtil=new Object();}deconcept.SWFObject=function(_1,id,w,h,_5,c,_7,_8,_9,_a){if(!document.getElementById){return;}this.DETECT_KEY=_a?_a:"detectflash";this.skipDetect=deconcept.util.getRequestParameter(this.DETECT_KEY);this.params=new Object();this.variables=new Object();this.attributes=new Array();if(_1){this.setAttribute("swf",_1);}if(id){this.setAttribute("id",id);}if(w){this.setAttribute("width",w);}if(h){this.setAttribute("height",h);}if(_5){this.setAttribute("version",new deconcept.PlayerVersion(_5.toString().split(".")));}this.installedVer=deconcept.SWFObjectUtil.getPlayerVersion();if(!window.opera&&document.all&&this.installedVer.major>7){deconcept.SWFObject.doPrepUnload=true;}if(c){this.addParam("bgcolor",c);}var q=_7?_7:"high";this.addParam("quality",q);this.setAttribute("useExpressInstall",false);this.setAttribute("doExpressInstall",false);var _c=(_8)?_8:window.location;this.setAttribute("xiRedirectUrl",_c);this.setAttribute("redirectUrl","");if(_9){this.setAttribute("redirectUrl",_9);}};deconcept.SWFObject.prototype={useExpressInstall:function(_d){this.xiSWFPath=!_d?"expressinstall.swf":_d;this.setAttribute("useExpressInstall",true);},setAttribute:function(_e,_f){this.attributes[_e]=_f;},getAttribute:function(_10){return this.attributes[_10];},addParam:function(_11,_12){this.params[_11]=_12;},getParams:function(){return this.params;},addVariable:function(_13,_14){this.variables[_13]=_14;},getVariable:function(_15){return this.variables[_15];},getVariables:function(){return this.variables;},getVariablePairs:function(){var _16=new Array();var key;var _18=this.getVariables();for(key in _18){_16[_16.length]=key+"="+_18[key];}return _16;},getSWFHTML:function(){var _19="";if(navigator.plugins&&navigator.mimeTypes&&navigator.mimeTypes.length){if(this.getAttribute("doExpressInstall")){this.addVariable("MMplayerType","PlugIn");this.setAttribute("swf",this.xiSWFPath);}_19="<embed type=\"application/x-shockwave-flash\" src=\""+this.getAttribute("swf")+"\" width=\""+this.getAttribute("width")+"\" height=\""+this.getAttribute("height")+"\" style=\""+this.getAttribute("style")+"\"";_19+=" id=\""+this.getAttribute("id")+"\" name=\""+this.getAttribute("id")+"\" ";var _1a=this.getParams();for(var key in _1a){_19+=[key]+"=\""+_1a[key]+"\" ";}var _1c=this.getVariablePairs().join("&");if(_1c.length>0){_19+="flashvars=\""+_1c+"\"";}_19+="/>";}else{if(this.getAttribute("doExpressInstall")){this.addVariable("MMplayerType","ActiveX");this.setAttribute("swf",this.xiSWFPath);}_19="<object id=\""+this.getAttribute("id")+"\" classid=\"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000\" width=\""+this.getAttribute("width")+"\" height=\""+this.getAttribute("height")+"\" style=\""+this.getAttribute("style")+"\">";_19+="<param name=\"movie\" value=\""+this.getAttribute("swf")+"\" />";var _1d=this.getParams();for(var key in _1d){_19+="<param name=\""+key+"\" value=\""+_1d[key]+"\" />";}var _1f=this.getVariablePairs().join("&");if(_1f.length>0){_19+="<param name=\"flashvars\" value=\""+_1f+"\" />";}_19+="</object>";}return _19;},write:function(_20){if(this.getAttribute("useExpressInstall")){var _21=new deconcept.PlayerVersion([6,0,65]);if(this.installedVer.versionIsValid(_21)&&!this.installedVer.versionIsValid(this.getAttribute("version"))){this.setAttribute("doExpressInstall",true);this.addVariable("MMredirectURL",escape(this.getAttribute("xiRedirectUrl")));document.title=document.title.slice(0,47)+" - Flash Player Installation";this.addVariable("MMdoctitle",document.title);}}if(this.skipDetect||this.getAttribute("doExpressInstall")||this.installedVer.versionIsValid(this.getAttribute("version"))){var n=(typeof _20=="string")?document.getElementById(_20):_20;n.innerHTML=this.getSWFHTML();return true;}else{if(this.getAttribute("redirectUrl")!=""){document.location.replace(this.getAttribute("redirectUrl"));}}return false;}};deconcept.SWFObjectUtil.getPlayerVersion=function(){var _23=new deconcept.PlayerVersion([0,0,0]);if(navigator.plugins&&navigator.mimeTypes.length){var x=navigator.plugins["Shockwave Flash"];if(x&&x.description){_23=new deconcept.PlayerVersion(x.description.replace(/([a-zA-Z]|\s)+/,"").replace(/(\s+r|\s+b[0-9]+)/,".").split("."));}}else{if(navigator.userAgent&&navigator.userAgent.indexOf("Windows CE")>=0){var axo=1;var _26=3;while(axo){try{_26++;axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash."+_26);_23=new deconcept.PlayerVersion([_26,0,0]);}catch(e){axo=null;}}}else{try{var axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7");}catch(e){try{var axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash.6");_23=new deconcept.PlayerVersion([6,0,21]);axo.AllowScriptAccess="always";}catch(e){if(_23.major==6){return _23;}}try{axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash");}catch(e){}}if(axo!=null){_23=new deconcept.PlayerVersion(axo.GetVariable("$version").split(" ")[1].split(","));}}}return _23;};deconcept.PlayerVersion=function(_29){this.major=_29[0]!=null?parseInt(_29[0]):0;this.minor=_29[1]!=null?parseInt(_29[1]):0;this.rev=_29[2]!=null?parseInt(_29[2]):0;};deconcept.PlayerVersion.prototype.versionIsValid=function(fv){if(this.major<fv.major){return false;}if(this.major>fv.major){return true;}if(this.minor<fv.minor){return false;}if(this.minor>fv.minor){return true;}if(this.rev<fv.rev){return false;}return true;};deconcept.util={getRequestParameter:function(_2b){var q=document.location.search||document.location.hash;if(_2b==null){return q;}if(q){var _2d=q.substring(1).split("&");for(var i=0;i<_2d.length;i++){if(_2d[i].substring(0,_2d[i].indexOf("="))==_2b){return _2d[i].substring((_2d[i].indexOf("=")+1));}}}return "";}};deconcept.SWFObjectUtil.cleanupSWFs=function(){var _2f=document.getElementsByTagName("OBJECT");for(var i=_2f.length-1;i>=0;i--){_2f[i].style.display="none";for(var x in _2f[i]){if(typeof _2f[i][x]=="function"){_2f[i][x]=function(){};}}}};if(deconcept.SWFObject.doPrepUnload){if(!deconcept.unloadSet){deconcept.SWFObjectUtil.prepUnload=function(){__flash_unloadHandler=function(){};__flash_savedUnloadHandler=function(){};window.attachEvent("onunload",deconcept.SWFObjectUtil.cleanupSWFs);};window.attachEvent("onbeforeunload",deconcept.SWFObjectUtil.prepUnload);deconcept.unloadSet=true;}}if(!document.getElementById&&document.all){document.getElementById=function(id){return document.all[id];};}var getQueryParamValue=deconcept.util.getRequestParameter;var FlashObject=deconcept.SWFObject;var SWFObject=deconcept.SWFObject;
//From : ../reg/calendar/date.js ____________
/*
 * Date prototype extensions. Doesn't depend on any
 * other code. Doens't overwrite existing methods.
 *
 * Adds dayNames, abbrDayNames, monthNames and abbrMonthNames static properties and isLeapYear,
 * isWeekend, isWeekDay, getDaysInMonth, getDayName, getMonthName, getDayOfYear, getWeekOfYear,
 * setDayOfYear, addYears, addMonths, addDays, addHours, addMinutes, addSeconds methods
 *
 * Copyright (c) 2006 JÃ¶rn Zaefferer and Brandon Aaron (brandon.aaron@gmail.com || http://brandonaaron.net)
 *
 * Additional methods and properties added by Kelvin Luck: firstDayOfWeek, dateFormat, zeroTime, asString, fromString -
 * I've added my name to these methods so you know who to blame if they are broken!
 * 
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 *
 */

/**
 * An Array of day names starting with Sunday.
 * 
 * @example dayNames[0]
 * @result 'Sunday'
 *
 * @name dayNames
 * @type Array
 * @cat Plugins/Methods/Date
 */
Date.dayNames = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];

/**
 * An Array of abbreviated day names starting with Sun.
 * 
 * @example abbrDayNames[0]
 * @result 'Sun'
 *
 * @name abbrDayNames
 * @type Array
 * @cat Plugins/Methods/Date
 */
Date.abbrDayNames = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];

/**
 * An Array of month names starting with Janurary.
 * 
 * @example monthNames[0]
 * @result 'January'
 *
 * @name monthNames
 * @type Array
 * @cat Plugins/Methods/Date
 */
Date.monthNames = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];

/**
 * An Array of abbreviated month names starting with Jan.
 * 
 * @example abbrMonthNames[0]
 * @result 'Jan'
 *
 * @name monthNames
 * @type Array
 * @cat Plugins/Methods/Date
 */
Date.abbrMonthNames = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];

/**
 * The first day of the week for this locale.
 *
 * @name firstDayOfWeek
 * @type Number
 * @cat Plugins/Methods/Date
 * @author Kelvin Luck
 */
Date.firstDayOfWeek = 1;

/**
 * The format that string dates should be represented as (e.g. 'dd/mm/yyyy' for UK, 'mm/dd/yyyy' for US, 'yyyy-mm-dd' for Unicode etc).
 *
 * @name format
 * @type String
 * @cat Plugins/Methods/Date
 * @author Kelvin Luck
 */
Date.format = 'dd/mm/yyyy';
//Date.format = 'mm/dd/yyyy';
//Date.format = 'yyyy-mm-dd';
//Date.format = 'dd mmm yy';

/**
 * The first two numbers in the century to be used when decoding a two digit year. Since a two digit year is ambiguous (and date.setYear
 * only works with numbers < 99 and so doesn't allow you to set years after 2000) we need to use this to disambiguate the two digit year codes.
 *
 * @name format
 * @type String
 * @cat Plugins/Methods/Date
 * @author Kelvin Luck
 */
Date.fullYearStart = '20';

(function() {

	/**
	 * Adds a given method under the given name 
	 * to the Date prototype if it doesn't
	 * currently exist.
	 *
	 * @private
	 */
	function add(name, method) {
		if( !Date.prototype[name] ) {
			Date.prototype[name] = method;
		}
	};
	
	/**
	 * Checks if the year is a leap year.
	 *
	 * @example var dtm = new Date("01/12/2008");
	 * dtm.isLeapYear();
	 * @result true
	 *
	 * @name isLeapYear
	 * @type Boolean
	 * @cat Plugins/Methods/Date
	 */
	add("isLeapYear", function() {
		var y = this.getFullYear();
		return (y%4==0 && y%100!=0) || y%400==0;
	});
	
	/**
	 * Checks if the day is a weekend day (Sat or Sun).
	 *
	 * @example var dtm = new Date("01/12/2008");
	 * dtm.isWeekend();
	 * @result false
	 *
	 * @name isWeekend
	 * @type Boolean
	 * @cat Plugins/Methods/Date
	 */
	add("isWeekend", function() {
		return this.getDay()==0 || this.getDay()==6;
	});
	
	/**
	 * Check if the day is a day of the week (Mon-Fri)
	 * 
	 * @example var dtm = new Date("01/12/2008");
	 * dtm.isWeekDay();
	 * @result false
	 * 
	 * @name isWeekDay
	 * @type Boolean
	 * @cat Plugins/Methods/Date
	 */
	add("isWeekDay", function() {
		return !this.isWeekend();
	});
	
	/**
	 * Gets the number of days in the month.
	 * 
	 * @example var dtm = new Date("01/12/2008");
	 * dtm.getDaysInMonth();
	 * @result 31
	 * 
	 * @name getDaysInMonth
	 * @type Number
	 * @cat Plugins/Methods/Date
	 */
	add("getDaysInMonth", function() {
		return [31,(this.isLeapYear() ? 29:28),31,30,31,30,31,31,30,31,30,31][this.getMonth()];
	});
	
	/**
	 * Gets the name of the day.
	 * 
	 * @example var dtm = new Date("01/12/2008");
	 * dtm.getDayName();
	 * @result 'Saturday'
	 * 
	 * @example var dtm = new Date("01/12/2008");
	 * dtm.getDayName(true);
	 * @result 'Sat'
	 * 
	 * @param abbreviated Boolean When set to true the name will be abbreviated.
	 * @name getDayName
	 * @type String
	 * @cat Plugins/Methods/Date
	 */
	add("getDayName", function(abbreviated) {
		return abbreviated ? Date.abbrDayNames[this.getDay()] : Date.dayNames[this.getDay()];
	});

	/**
	 * Gets the name of the month.
	 * 
	 * @example var dtm = new Date("01/12/2008");
	 * dtm.getMonthName();
	 * @result 'Janurary'
	 *
	 * @example var dtm = new Date("01/12/2008");
	 * dtm.getMonthName(true);
	 * @result 'Jan'
	 * 
	 * @param abbreviated Boolean When set to true the name will be abbreviated.
	 * @name getDayName
	 * @type String
	 * @cat Plugins/Methods/Date
	 */
	add("getMonthName", function(abbreviated) {
		return abbreviated ? Date.abbrMonthNames[this.getMonth()] : Date.monthNames[this.getMonth()];
	});

	/**
	 * Get the number of the day of the year.
	 * 
	 * @example var dtm = new Date("01/12/2008");
	 * dtm.getDayOfYear();
	 * @result 11
	 * 
	 * @name getDayOfYear
	 * @type Number
	 * @cat Plugins/Methods/Date
	 */
	add("getDayOfYear", function() {
		var tmpdtm = new Date("1/1/" + this.getFullYear());
		return Math.floor((this.getTime() - tmpdtm.getTime()) / 86400000);
	});
	
	/**
	 * Get the number of the week of the year.
	 * 
	 * @example var dtm = new Date("01/12/2008");
	 * dtm.getWeekOfYear();
	 * @result 2
	 * 
	 * @name getWeekOfYear
	 * @type Number
	 * @cat Plugins/Methods/Date
	 */
	add("getWeekOfYear", function() {
		return Math.ceil(this.getDayOfYear() / 7);
	});

	/**
	 * Set the day of the year.
	 * 
	 * @example var dtm = new Date("01/12/2008");
	 * dtm.setDayOfYear(1);
	 * dtm.toString();
	 * @result 'Tue Jan 01 2008 00:00:00'
	 * 
	 * @name setDayOfYear
	 * @type Date
	 * @cat Plugins/Methods/Date
	 */
	add("setDayOfYear", function(day) {
		this.setMonth(0);
		this.setDate(day);
		return this;
	});
	
	/**
	 * Add a number of years to the date object.
	 * 
	 * @example var dtm = new Date("01/12/2008");
	 * dtm.addYears(1);
	 * dtm.toString();
	 * @result 'Mon Jan 12 2009 00:00:00'
	 * 
	 * @name addYears
	 * @type Date
	 * @cat Plugins/Methods/Date
	 */
	add("addYears", function(num) {
		this.setFullYear(this.getFullYear() + num);
		return this;
	});
	
	/**
	 * Add a number of months to the date object.
	 * 
	 * @example var dtm = new Date("01/12/2008");
	 * dtm.addMonths(1);
	 * dtm.toString();
	 * @result 'Tue Feb 12 2008 00:00:00'
	 * 
	 * @name addMonths
	 * @type Date
	 * @cat Plugins/Methods/Date
	 */
	add("addMonths", function(num) {
		var tmpdtm = this.getDate();
		
		this.setMonth(this.getMonth() + num);
		
		if (tmpdtm > this.getDate())
			this.addDays(-this.getDate());
		
		return this;
	});
	
	/**
	 * Add a number of days to the date object.
	 * 
	 * @example var dtm = new Date("01/12/2008");
	 * dtm.addDays(1);
	 * dtm.toString();
	 * @result 'Sun Jan 13 2008 00:00:00'
	 * 
	 * @name addDays
	 * @type Date
	 * @cat Plugins/Methods/Date
	 */
	add("addDays", function(num) {
		this.setDate(this.getDate() + num);
		return this;
	});
	
	/**
	 * Add a number of hours to the date object.
	 * 
	 * @example var dtm = new Date("01/12/2008");
	 * dtm.addHours(24);
	 * dtm.toString();
	 * @result 'Sun Jan 13 2008 00:00:00'
	 * 
	 * @name addHours
	 * @type Date
	 * @cat Plugins/Methods/Date
	 */
	add("addHours", function(num) {
		this.setHours(this.getHours() + num);
		return this;
	});

	/**
	 * Add a number of minutes to the date object.
	 * 
	 * @example var dtm = new Date("01/12/2008");
	 * dtm.addMinutes(60);
	 * dtm.toString();
	 * @result 'Sat Jan 12 2008 01:00:00'
	 * 
	 * @name addMinutes
	 * @type Date
	 * @cat Plugins/Methods/Date
	 */
	add("addMinutes", function(num) {
		this.setMinutes(this.getMinutes() + num);
		return this;
	});
	
	/**
	 * Add a number of seconds to the date object.
	 * 
	 * @example var dtm = new Date("01/12/2008");
	 * dtm.addSeconds(60);
	 * dtm.toString();
	 * @result 'Sat Jan 12 2008 00:01:00'
	 * 
	 * @name addSeconds
	 * @type Date
	 * @cat Plugins/Methods/Date
	 */
	add("addSeconds", function(num) {
		this.setSeconds(this.getSeconds() + num);
		return this;
	});
	
	/**
	 * Sets the time component of this Date to zero for cleaner, easier comparison of dates where time is not relevant.
	 * 
	 * @example var dtm = new Date();
	 * dtm.zeroTime();
	 * dtm.toString();
	 * @result 'Sat Jan 12 2008 00:01:00'
	 * 
	 * @name zeroTime
	 * @type Date
	 * @cat Plugins/Methods/Date
	 * @author Kelvin Luck
	 */
	add("zeroTime", function() {
		this.setMilliseconds(0);
		this.setSeconds(0);
		this.setMinutes(0);
		this.setHours(0);
		return this;
	});
	
	/**
	 * Returns a string representation of the date object according to Date.format.
	 * (Date.toString may be used in other places so I purposefully didn't overwrite it)
	 * 
	 * @example var dtm = new Date("01/12/2008");
	 * dtm.asString();
	 * @result '12/01/2008' // (where Date.format == 'dd/mm/yyyy'
	 * 
	 * @name asString
	 * @type Date
	 * @cat Plugins/Methods/Date
	 * @author Kelvin Luck
	 */
	add("asString", function() {
		var r = Date.format;
		return r
			.split('yyyy').join(this.getFullYear())
			.split('yy').join((this.getFullYear() + '').substring(2))
			.split('mmm').join(this.getMonthName(true))
			.split('mm').join(_zeroPad(this.getMonth()+1))
			.split('dd').join(_zeroPad(this.getDate()));
	});
	
	/**
	 * Returns a new date object created from the passed String according to Date.format or false if the attempt to do this results in an invalid date object
	 * (We can't simple use Date.parse as it's not aware of locale and I chose not to overwrite it incase it's functionality is being relied on elsewhere)
	 *
	 * @example var dtm = Date.fromString("12/01/2008");
	 * dtm.toString();
	 * @result 'Sat Jan 12 2008 00:00:00' // (where Date.format == 'dd/mm/yyyy'
	 * 
	 * @name fromString
	 * @type Date
	 * @cat Plugins/Methods/Date
	 * @author Kelvin Luck
	 */
	Date.fromString = function(s)
	{
		var f = Date.format;
		var d = new Date('01/01/1977');
		var iY = f.indexOf('yyyy');
		if (iY > -1) {
			d.setFullYear(Number(s.substr(iY, 4)));
		} else {
			// TODO - this doesn't work very well - are there any rules for what is meant by a two digit year?
			d.setFullYear(Number(Date.fullYearStart + s.substr(f.indexOf('yy'), 2)));
		}
		var iM = f.indexOf('mmm');
		if (iM > -1) {
			var mStr = s.substr(iM, 3);
			for (var i=0; i<Date.abbrMonthNames.length; i++) {
				if (Date.abbrMonthNames[i] == mStr) break;
			}
			d.setMonth(i);
		} else {
			d.setMonth(Number(s.substr(f.indexOf('mm'), 2)) - 1);
		}
		d.setDate(Number(s.substr(f.indexOf('dd'), 2)));
		if (isNaN(d.getTime())) {
			return false;
		}
		return d;
	};
	
	// utility method
	var _zeroPad = function(num) {
		var s = '0'+num;
		return s.substring(s.length-2)
		//return ('0'+num).substring(-2); // doesn't work on IE :(
	};
	
})();
//From : ../reg/calendar/jquery.js ____________
/**
 * Copyright (c) 2007 Kelvin Luck (http://www.kelvinluck.com/)
 * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php) 
 * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
 *
 * $Id: jquery.js,v 1.3 2009/11/12 15:20:42 dpramesh Exp $
 **/

(function($){
    
	$.fn.extend({
/**
 * Render a calendar table into any matched elements.
 * 
 * @param Object s (optional) Customize your calendars.
 * @option Number month The month to render (NOTE that months are zero based). Default is today's month.
 * @option Number year The year to render. Default is today's year.
 * @option Function renderCallback A reference to a function that is called as each cell is rendered and which can add classes and event listeners to the created nodes. Default is no callback.
 * @option Number showHeader Whether or not to show the header row, possible values are: $.dpConst.SHOW_HEADER_NONE (no header), $.dpConst.SHOW_HEADER_SHORT (first letter of each day) and $.dpConst.SHOW_HEADER_LONG (full name of each day). Default is $.dpConst.SHOW_HEADER_SHORT.
 * @option String hoverClass The class to attach to each cell when you hover over it (to allow you to use hover effects in IE6 which doesn't support the :hover pseudo-class on elements other than links). Default is dp-hover. Pass false if you don't want a hover class.
 * @type jQuery
 * @name renderCalendar
 * @cat plugins/datePicker
 * @author Kelvin Luck (http://www.kelvinluck.com/)
 *
 * @example $('#calendar-me').renderCalendar({month:0, year:2007});
 * @desc Renders a calendar displaying January 2007 into the element with an id of calendar-me.
 *
 * @example
 * var testCallback = function($td, thisDate, month, year)
 * {
 * if ($td.is('.current-month') && thisDate.getDay() == 4) {
 *		var d = thisDate.getDate();
 *		$td.bind(
 *			'click',
 *			function()
 *			{
 *				alert('You clicked on ' + d + '/' + (Number(month)+1) + '/' + year);
 *			}
 *		).addClass('thursday');
 *	} else if (thisDate.getDay() == 5) {
 *		$td.html('Friday the ' + $td.html() + 'th');
 *	}
 * }
 * $('#calendar-me').renderCalendar({month:0, year:2007, renderCallback:testCallback});
 * 
 * @desc Renders a calendar displaying January 2007 into the element with an id of calendar-me. Every Thursday in the current month has a class of "thursday" applied to it, is clickable and shows an alert when clicked. Every Friday on the calendar has the number inside replaced with text.
 **/
		renderCalendar  :   function(s)
		{
			var dc = function(a)
			{
				return document.createElement(a);
			};
			
			s = $.extend(
				{
					month			: null,
					year			: null,
					renderCallback	: null,
					showHeader		: $.dpConst.SHOW_HEADER_SHORT,
					dpController	: null,
					hoverClass		: 'dp-hover'
				}
				, s
			);
			
			if (s.showHeader != $.dpConst.SHOW_HEADER_NONE) {
				var headRow = $(dc('tr'));
				for (var i=Date.firstDayOfWeek; i<Date.firstDayOfWeek+7; i++) {
					var weekday = i%7;
					var day = Date.dayNames[weekday];
					headRow.append(
						jQuery(dc('th')).attr({'scope':'col', 'abbr':day, 'title':day, 'class':(weekday == 0 || weekday == 6 ? 'weekend' : 'weekday')}).html(s.showHeader == $.dpConst.SHOW_HEADER_SHORT ? day.substr(0, 1) : day)
					);
				}
			};
			
			var calendarTable = $(dc('table'))
									.attr(
										{
											'cellspacing':2,
											'className':'jCalendar'
										}
									)
									.append(
										(s.showHeader != $.dpConst.SHOW_HEADER_NONE ? 
											$(dc('thead'))
												.append(headRow)
											:
											dc('thead')
										)
									);
			var tbody = $(dc('tbody'));
			
			var today = (new Date()).zeroTime();
			
			var month = s.month == undefined ? today.getMonth() : s.month;
			var year = s.year || today.getFullYear();
			
			var currentDate = new Date(year, month, 1);
			
			
			var firstDayOffset = Date.firstDayOfWeek - currentDate.getDay() + 1;
			if (firstDayOffset > 1) firstDayOffset -= 7;
			var weeksToDraw = Math.ceil(( (-1*firstDayOffset+1) + currentDate.getDaysInMonth() ) /7);
			currentDate.addDays(firstDayOffset-1);
			
			var doHover = function()
			{
				if (s.hoverClass) {
					$(this).addClass(s.hoverClass);
				}
			};
			var unHover = function()
			{
				if (s.hoverClass) {
					$(this).removeClass(s.hoverClass);
				}
			};
			
			var w = 0;
			while (w++<weeksToDraw) {
				var r = jQuery(dc('tr'));
				for (var i=0; i<7; i++) {
					var thisMonth = currentDate.getMonth() == month;
					var d = $(dc('td'))
								.text(currentDate.getDate() + '')
								.attr('className', (thisMonth ? 'current-month ' : 'other-month ') +
													(currentDate.isWeekend() ? 'weekend ' : 'weekday ') +
													(thisMonth && currentDate.getTime() == today.getTime() ? 'today ' : '')
								)
								.hover(doHover, unHover)
							;
					if (s.renderCallback) {
						s.renderCallback(d, currentDate, month, year);
					}
					r.append(d);
					currentDate.addDays(1);
				}
				tbody.append(r);
			}
			calendarTable.append(tbody);
			
			return this.each(
				function()
				{
					$(this).empty().append(calendarTable);
				}
			);
		},
/**
 * Create a datePicker associated with each of the matched elements.
 *
 * The matched element will receive a few custom events with the following signatures:
 *
 * dateSelected(event, date, $td, status)
 * Triggered when a date is selected. event is a reference to the event, date is the Date selected, $td is a jquery object wrapped around the TD that was clicked on and status is whether the date was selected (true) or deselected (false)
 * 
 * dpClosed(event, selected)
 * Triggered when the date picker is closed. event is a reference to the event and selected is an Array containing Date objects.
 *
 * dpMonthChanged(event, displayedMonth, displayedYear)
 * Triggered when the month of the popped up calendar is changed. event is a reference to the event, displayedMonth is the number of the month now displayed (zero based) and displayedYear is the year of the month.
 *
 * dpDisplayed(event, $datePickerDiv)
 * Triggered when the date picker is created. $datePickerDiv is the div containing the date picker. Use this event to add custom content/ listeners to the popped up date picker.
 *
 * @param Object s (optional) Customize your date pickers.
 * @option Number month The month to render when the date picker is opened (NOTE that months are zero based). Default is today's month.
 * @option Number year The year to render when the date picker is opened. Default is today's year.
 * @option String startDate The first date date can be selected.
 * @option String endDate The last date that can be selected.
 * @option Boolean inline Whether to create the datePicker as inline (e.g. always on the page) or as a model popup. Default is false (== modal popup)
 * @option Boolean createButton Whether to create a .dp-choose-date anchor directly after the matched element which when clicked will trigger the showing of the date picker. Default is true.
 * @option Boolean showYearNavigation Whether to display buttons which allow the user to navigate through the months a year at a time. Default is true.
 * @option Boolean closeOnSelect Whether to close the date picker when a date is selected. Default is true.
 * @option Boolean displayClose Whether to create a "Close" button within the date picker popup. Default is false.
 * @option Boolean selectMultiple Whether a user should be able to select multiple dates with this date picker. Default is false.
 * @option Boolean clickInput If the matched element is an input type="text" and this option is true then clicking on the input will cause the date picker to appear.
 * @option Number verticalPosition The vertical alignment of the popped up date picker to the matched element. One of $.dpConst.POS_TOP and $.dpConst.POS_BOTTOM. Default is $.dpConst.POS_TOP.
 * @option Number horizontalPosition The horizontal alignment of the popped up date picker to the matched element. One of $.dpConst.POS_LEFT and $.dpConst.POS_RIGHT.
 * @option Number verticalOffset The number of pixels offset from the defined verticalPosition of this date picker that it should pop up in. Default in 0.
 * @option Number horizontalOffset The number of pixels offset from the defined horizontalPosition of this date picker that it should pop up in. Default in 0.
 * @option (Function|Array) renderCallback A reference to a function (or an array of seperate functions) that is called as each cell is rendered and which can add classes and event listeners to the created nodes. Each callback function will receive four arguments; a jquery object wrapping the created TD, a Date object containing the date this TD represents, a number giving the currently rendered month and a number giving the currently rendered year. Default is no callback.
 * @option String hoverClass The class to attach to each cell when you hover over it (to allow you to use hover effects in IE6 which doesn't support the :hover pseudo-class on elements other than links). Default is dp-hover. Pass false if you don't want a hover class.
 * @type jQuery
 * @name datePicker
 * @cat plugins/datePicker
 * @author Kelvin Luck (http://www.kelvinluck.com/)
 *
 * @example $('input.date-picker').datePicker();
 * @desc Creates a date picker button next to all matched input elements. When the button is clicked on the value of the selected date will be placed in the corresponding input (formatted according to Date.format).
 *
 * @example demo/index.html
 * @desc See the projects homepage for many more complex examples...
 **/
		datePicker : function(s)
		{			
			if (!$.event._dpCache) $.event._dpCache = [];
			
			// initialise the date picker controller with the relevant settings...
			s = $.extend(
				{
					month				: undefined,
					year				: undefined,
					startDate			: undefined,
					endDate				: undefined,
					inline				: false,
					renderCallback		: [],
					createButton		: true,
					showYearNavigation	: true,
					closeOnSelect		: true,
					displayClose		: false,
					selectMultiple		: false,
					clickInput			: false,
					verticalPosition	: $.dpConst.POS_TOP,
					horizontalPosition	: $.dpConst.POS_LEFT,
					verticalOffset		: 0,
					horizontalOffset	: 0,
					hoverClass			: 'dp-hover'
				}
				, s
			);
			
			return this.each(
				function()
				{
					var $this = $(this);
					var alreadyExists = true;
					
					if (!this._dpId) {
						this._dpId = $.event.guid++;
						$.event._dpCache[this._dpId] = new DatePicker(this);
						alreadyExists = false;
					}
					
					if (s.inline) {
						s.createButton = false;
						s.displayClose = false;
						s.closeOnSelect = false;
						$this.empty();
					}
					
					var controller = $.event._dpCache[this._dpId];
					
					controller.init(s);
					
					if (!alreadyExists && s.createButton) {
						// create it!
						controller.button = $('<a href="#" class="dp-choose-date" title="' + $.dpText.TEXT_CHOOSE_DATE + '">' + $.dpText.TEXT_CHOOSE_DATE + '</a>')
								.bind(
									'click',
									function()
									{
										$this.dpDisplay(this);
										this.blur();
										return false;
									}
								);
						$this.after(controller.button);
					}
					
					if (!alreadyExists && $this.is(':text')) {
						$this
							.bind(
								'dateSelected',
								function(e, selectedDate, $td)
								{
									this.value = selectedDate.asString();
								}
							).bind(
								'change',
								function()
								{
									var d = Date.fromString(this.value);
									if (d) {
										controller.setSelected(d, true, true);
									}
								}
							).bind(
									'click',
									function()
									{
										$this.dpDisplay(this);
										this.blur();
										return false;
									}
							);
						if (s.clickInput) {
							$this.bind(
								'click',
								function()
								{
									$this.dpDisplay();
								}
							);
						}
						var d = Date.fromString(this.value);
						if (this.value != '' && d) {
							controller.setSelected(d, true, true);
						}
					}
					
					$this.addClass('dp-applied');
					
				}
			)
		},
/**
 * Disables or enables this date picker
 *
 * @param Boolean s Whether to disable (true) or enable (false) this datePicker
 * @type jQuery
 * @name dpSetDisabled
 * @cat plugins/datePicker
 * @author Kelvin Luck (http://www.kelvinluck.com/)
 *
 * @example $('.date-picker').datePicker();
 * $('.date-picker').dpSetDisabled(true);
 * @desc Prevents this date picker from displaying and adds a class of dp-disabled to it (and it's associated button if it has one) for styling purposes. If the matched element is an input field then it will also set the disabled attribute to stop people directly editing the field.
 **/
		dpSetDisabled : function(s)
		{
			return _w.call(this, 'setDisabled', s);
		},
/**
 * Updates the first selectable date for any date pickers on any matched elements.
 *
 * @param String d A string representing the first selectable date (formatted according to Date.format).
 * @type jQuery
 * @name dpSetStartDate
 * @cat plugins/datePicker
 * @author Kelvin Luck (http://www.kelvinluck.com/)
 *
 * @example $('.date-picker').datePicker();
 * $('.date-picker').dpSetStartDate('01/01/2000');
 * @desc Creates a date picker associated with all elements with a class of "date-picker" then sets the first selectable date for each of these to the first day of the millenium.
 **/
		dpSetStartDate : function(d)
		{
			return _w.call(this, 'setStartDate', d);
		},
/**
 * Updates the last selectable date for any date pickers on any matched elements.
 *
 * @param String d A string representing the last selectable date (formatted according to Date.format).
 * @type jQuery
 * @name dpSetEndDate
 * @cat plugins/datePicker
 * @author Kelvin Luck (http://www.kelvinluck.com/)
 *
 * @example $('.date-picker').datePicker();
 * $('.date-picker').dpSetEndDate('01/01/2010');
 * @desc Creates a date picker associated with all elements with a class of "date-picker" then sets the last selectable date for each of these to the first Janurary 2010.
 **/
		dpSetEndDate : function(d)
		{
			return _w.call(this, 'setEndDate', d);
		},
/**
 * Gets a list of Dates currently selected by this datePicker. This will be an empty array if no dates are currently selected or NULL if there is no datePicker associated with the matched element.
 *
 * @type Array
 * @name dpGetSelected
 * @cat plugins/datePicker
 * @author Kelvin Luck (http://www.kelvinluck.com/)
 *
 * @example $('.date-picker').datePicker();
 * alert($('.date-picker').dpGetSelected());
 * @desc Will alert an empty array (as nothing is selected yet)
 **/
		dpGetSelected : function()
		{
			var c = _getController(this[0]);
			if (c) {
				return c.getSelected();
			}
			return null;
		},
/**
 * Selects or deselects a date on any matched element's date pickers. Deselcting is only useful on date pickers where selectMultiple==true. Selecting will only work if the passed date is within the startDate and endDate boundries for a given date picker.
 *
 * @param String d A string representing the date you want to select (formatted according to Date.format).
 * @param Boolean v Whether you want to select (true) or deselect (false) this date. Optional - default = true.
 * @param Boolean m Whether you want the date picker to open up on the month of this date when it is next opened. Optional - default = true.
 * @type jQuery
 * @name dpSetSelected
 * @cat plugins/datePicker
 * @author Kelvin Luck (http://www.kelvinluck.com/)
 *
 * @example $('.date-picker').datePicker();
 * $('.date-picker').dpSetSelected('01/01/2010');
 * @desc Creates a date picker associated with all elements with a class of "date-picker" then sets the selected date on these date pickers to the first Janurary 2010. When the date picker is next opened it will display Janurary 2010.
 **/
		dpSetSelected : function(d, v, m)
		{
			if (v == undefined) v=true;
			if (m == undefined) m=true;
			return _w.call(this, 'setSelected', Date.fromString(d), v, m);
		},
/**
 * Sets the month that will be displayed when the date picker is next opened. If the passed month is before startDate then the month containing startDate will be displayed instead. If the passed month is after endDate then the month containing the endDate will be displayed instead.
 *
 * @param Number m The month you want the date picker to display. Optional - defaults to the currently displayed month.
 * @param Number y The year you want the date picker to display. Optional - defaults to the currently displayed year.
 * @type jQuery
 * @name dpSetDisplayedMonth
 * @cat plugins/datePicker
 * @author Kelvin Luck (http://www.kelvinluck.com/)
 *
 * @example $('.date-picker').datePicker();
 * $('.date-picker').dpSetDisplayedMonth(10, 2008);
 * @desc Creates a date picker associated with all elements with a class of "date-picker" then sets the selected date on these date pickers to the first Janurary 2010. When the date picker is next opened it will display Janurary 2010.
 **/
		dpSetDisplayedMonth : function(m, y)
		{
			return _w.call(this, 'setDisplayedMonth', Number(m), Number(y));
		},
/**
 * Displays the date picker associated with the matched elements. Since only one date picker can be displayed at once then the date picker associated with the last matched element will be the one that is displayed.
 *
 * @param HTMLElement e An element that you want the date picker to pop up relative in position to. Optional - default behaviour is to pop up next to the element associated with this date picker.
 * @type jQuery
 * @name dpDisplay
 * @cat plugins/datePicker
 * @author Kelvin Luck (http://www.kelvinluck.com/)
 *
 * @example $('#date-picker').datePicker();
 * $('#date-picker').dpDisplay();
 * @desc Creates a date picker associated with the element with an id of date-picker and then causes it to pop up.
 **/
		dpDisplay : function(e)
		{
			return _w.call(this, 'display', e);
		},
/**
 * Sets a function or array of functions that is called when each TD of the date picker popup is rendered to the page
 *
 * @param (Function|Array) a A function or an array of functions that are called when each td is rendered. Each function will receive four arguments; a jquery object wrapping the created TD, a Date object containing the date this TD represents, a number giving the currently rendered month and a number giving the currently rendered year.
 * @type jQuery
 * @name dpSetRenderCallback
 * @cat plugins/datePicker
 * @author Kelvin Luck (http://www.kelvinluck.com/)
 *
 * @example $('#date-picker').datePicker();
 * $('#date-picker').dpSetRenderCallback(function($td, thisDate, month, year)
 * {
 * 	// do stuff as each td is rendered dependant on the date in the td and the displayed month and year
 * });
 * @desc Creates a date picker associated with the element with an id of date-picker and then creates a function which is called as each td is rendered when this date picker is displayed.
 **/
		dpSetRenderCallback : function(a)
		{
			return _w.call(this, 'setRenderCallback', a);
		},
/**
 * Sets the position that the datePicker will pop up (relative to it's associated element)
 *
 * @param Number v The vertical alignment of the created date picker to it's associated element. Possible values are $.dpConst.POS_TOP and $.dpConst.POS_BOTTOM
 * @param Number h The horizontal alignment of the created date picker to it's associated element. Possible values are $.dpConst.POS_LEFT and $.dpConst.POS_RIGHT
 * @type jQuery
 * @name dpSetPosition
 * @cat plugins/datePicker
 * @author Kelvin Luck (http://www.kelvinluck.com/)
 *
 * @example $('#date-picker').datePicker();
 * $('#date-picker').dpSetPosition($.dpConst.POS_BOTTOM, $.dpConst.POS_RIGHT);
 * @desc Creates a date picker associated with the element with an id of date-picker and makes it so that when this date picker pops up it will be bottom and right aligned to the #date-picker element.
 **/
		dpSetPosition : function(v, h)
		{
			return _w.call(this, 'setPosition', v, h);
		},
/**
 * Sets the offset that the popped up date picker will have from it's default position relative to it's associated element (as set by dpSetPosition)
 *
 * @param Number v The vertical offset of the created date picker.
 * @param Number h The horizontal offset of the created date picker.
 * @type jQuery
 * @name dpSetOffset
 * @cat plugins/datePicker
 * @author Kelvin Luck (http://www.kelvinluck.com/)
 *
 * @example $('#date-picker').datePicker();
 * $('#date-picker').dpSetOffset(-20, 200);
 * @desc Creates a date picker associated with the element with an id of date-picker and makes it so that when this date picker pops up it will be 20 pixels above and 200 pixels to the right of it's default position.
 **/
		dpSetOffset : function(v, h)
		{
			return _w.call(this, 'setOffset', v, h);
		},
/**
 * Closes the open date picker associated with this element.
 *
 * @type jQuery
 * @name dpClose
 * @cat plugins/datePicker
 * @author Kelvin Luck (http://www.kelvinluck.com/)
 *
 * @example $('.date-pick')
 *		.datePicker()
 *		.bind(
 *			'focus',
 *			function()
 *			{
 *				$(this).dpDisplay();
 *			}
 *		).bind(
 *			'blur',
 *			function()
 *			{
 *				$(this).dpClose();
 *			}
 *		);
 * @desc Creates a date picker and makes it appear when the relevant element is focused and disappear when it is blurred.
 **/
		dpClose : function()
		{
			return _w.call(this, '_closeCalendar', false, this[0]);
		},
		// private function called on unload to clean up any expandos etc and prevent memory links...
		_dpDestroy : function()
		{
			// TODO - implement this?
		}
	});
	
	// private internal function to cut down on the amount of code needed where we forward
	// dp* methods on the jQuery object on to the relevant DatePicker controllers...
	var _w = function(f, a1, a2, a3)
	{
		return this.each(
			function()
			{
				var c = _getController(this);
				if (c) {
					c[f](a1, a2, a3);
				}
			}
		);
	};
	
	function DatePicker(ele)
	{
		this.ele = ele;
		
		// initial values...
		this.displayedMonth		=	null;
		this.displayedYear		=	null;
		this.startDate			=	null;
		this.endDate			=	null;
		this.showYearNavigation	=	null;
		this.closeOnSelect		=	null;
		this.displayClose		=	null;
		this.selectMultiple		=	null;
		this.verticalPosition	=	null;
		this.horizontalPosition	=	null;
		this.verticalOffset		=	null;
		this.horizontalOffset	=	null;
		this.button				=	null;
		this.renderCallback		=	[];
		this.selectedDates		=	{};
		this.inline				=	null;
		this.context			=	'#dp-popup';
	};
	$.extend(
		DatePicker.prototype,
		{	
			init : function(s)
			{
				this.setStartDate(s.startDate);
				this.setEndDate(s.endDate);
				this.setDisplayedMonth(Number(s.month), Number(s.year));
				this.setRenderCallback(s.renderCallback);
				this.showYearNavigation = s.showYearNavigation;
				this.closeOnSelect = s.closeOnSelect;
				this.displayClose = s.displayClose;
				this.selectMultiple = s.selectMultiple;
				this.verticalPosition = s.verticalPosition;
				this.horizontalPosition = s.horizontalPosition;
				this.hoverClass = s.hoverClass;
				this.setOffset(s.verticalOffset, s.horizontalOffset);
				this.inline = s.inline;
				if (this.inline) {
					this.context = this.ele;
					this.display();
				}
			},
			setStartDate : function(d)
			{
				if (d) {
					this.startDate = Date.fromString(d);
				}
				if (!this.startDate) {
					this.startDate = (new Date()).zeroTime();
				}
				this.setDisplayedMonth(this.displayedMonth, this.displayedYear);
			},
			setEndDate : function(d)
			{
				if (d) {
					this.endDate = Date.fromString(d);
				}
				if (!this.endDate) {
					this.endDate = (new Date('12/31/2999')); // using the JS Date.parse function which expects mm/dd/yyyy
				}
				if (this.endDate.getTime() < this.startDate.getTime()) {
					this.endDate = this.startDate;
				}
				this.setDisplayedMonth(this.displayedMonth, this.displayedYear);
			},
			setPosition : function(v, h)
			{
				this.verticalPosition = v;
				this.horizontalPosition = h;
			},
			setOffset : function(v, h)
			{
				this.verticalOffset = parseInt(v) || 0;
				this.horizontalOffset = parseInt(h) || 0;
			},
			setDisabled : function(s)
			{
				$e = $(this.ele);
				$e[s ? 'addClass' : 'removeClass']('dp-disabled');
				if (this.button) {
					$but = $(this.button);
					$but[s ? 'addClass' : 'removeClass']('dp-disabled');
					$but.attr('title', s ? '' : $.dpText.TEXT_CHOOSE_DATE);
				}
				if ($e.is(':text')) {
					$e.attr('disabled', s ? 'disabled' : '');
				}
			},
			setDisplayedMonth : function(m, y)
			{
				if (this.startDate == undefined || this.endDate == undefined) {
					return;
				}
				var s = new Date(this.startDate.getTime());
				s.setDate(1);
				var e = new Date(this.endDate.getTime());
				e.setDate(1);
				
				var t;
				if ((!m && !y) || (isNaN(m) && isNaN(y))) {
					// no month or year passed - default to current month
					t = new Date().zeroTime();
					t.setDate(1);
				} else if (isNaN(m)) {
					// just year passed in - presume we want the displayedMonth
					t = new Date(y, this.displayedMonth, 1);
				} else if (isNaN(y)) {
					// just month passed in - presume we want the displayedYear
					t = new Date(this.displayedYear, m, 1);
				} else {
					// year and month passed in - that's the date we want!
					t = new Date(y, m, 1)
				}
				
				// check if the desired date is within the range of our defined startDate and endDate
				if (t.getTime() < s.getTime()) {
					t = s;
				} else if (t.getTime() > e.getTime()) {
					t = e;
				}
				this.displayedMonth = t.getMonth();
				this.displayedYear = t.getFullYear();
			},
			setSelected : function(d, v, moveToMonth)
			{
				if (this.selectMultiple == false) {
					this.selectedDates = {};
					$('td.selected', this.context).removeClass('selected');
				}
				if (moveToMonth) {
					this.setDisplayedMonth(d.getMonth(), d.getFullYear());
				}
				this.selectedDates[d.toString()] = v;
			},
			isSelected : function(d)
			{
				return this.selectedDates[d.toString()];
			},
			getSelected : function()
			{
				var r = [];
				for(s in this.selectedDates) {
					if (this.selectedDates[s] == true) {
						r.push(Date.parse(s));
					}
				}
				return r;
			},
			display : function(eleAlignTo)
			{
				if ($(this.ele).is('.dp-disabled')) return;
				
				eleAlignTo = eleAlignTo || this.ele;
				var c = this;
				var $ele = $(eleAlignTo);
				var eleOffset = $ele.offset();
				
				var $createIn;
				var attrs;
				var attrsCalendarHolder;
				var cssRules;
				
				if (c.inline) {
					$createIn = $(this.ele);
					attrs = {
						'id'		:	'calendar-' + this.ele._dpId,
						'className'	:	'dp-popup dp-popup-inline'
					};
					cssRules = {
					};
				} else {
					$createIn = $('body');
					attrs = {
						'id'		:	'dp-popup',
						'className'	:	'dp-popup'
					};
					cssRules = {
						'top'	:	eleOffset.top + c.verticalOffset + 18,
						'left'	:	eleOffset.left + c.horizontalOffset - 35
					};
					
					var _checkMouse = function(e)
					{
						var el = e.target;
						var cal = $('#dp-popup')[0];
						
						while (true){
							if (el == cal) {
								return true;
							} else if (el == document) {
								c._closeCalendar();
								return false;
							} else {
								el = $(el).parent()[0];
							}
						}
					};
					this._checkMouse = _checkMouse;
				
					this._closeCalendar(true);
				}
				
				
				$createIn
					.append(
						$('<div></div>')
							.attr(attrs)
							.css(cssRules)
							.append(
								$('<h5></h5>'),
								$('<div class="dp-nav-prev"></div>')
									.append(
										$('<a class="dp-nav-prev-month" href="#" title="' + $.dpText.TEXT_PREV_MONTH + '">&lt;</a>')
											.bind(
												'click',
												function()
												{
													return c._displayNewMonth.call(c, this, -1, 0);
												}
											)
									),
								$('<div class="dp-nav-next"></div>')
									.append(
										$('<a class="dp-nav-next-month" href="#" title="' + $.dpText.TEXT_NEXT_MONTH + '">&gt;</a>')
											.bind(
												'click',
												function()
												{
													return c._displayNewMonth.call(c, this, 1, 0);
												}
											)
									),
								$('<div></div>')
									.attr('className', 'dp-calendar')
							)
							.bgIframe()
						);
					
				var $pop = this.inline ? $('.dp-popup', this.context) : $('#dp-popup');
				
				if (this.showYearNavigation == false) {
					$('.dp-nav-prev-year, .dp-nav-next-year', c.context).css('display', 'none');
				}
				if (this.displayClose) {
					$pop.append(
						$('<a href="#" id="dp-close">' + $.dpText.TEXT_CLOSE + '</a>')
							.bind(
								'click',
								function()
								{
									c._closeCalendar();
									return false;
								}
							)
					);
				}
				c._renderCalendar();
				
				$(this.ele).trigger('dpDisplayed', $pop);
				
				if (!c.inline) {
					if (this.verticalPosition == $.dpConst.POS_BOTTOM) {
						$pop.css('top', eleOffset.top + $ele.height() - $pop.height() + c.verticalOffset);
					}
					if (this.horizontalPosition == $.dpConst.POS_RIGHT) {
						$pop.css('left', eleOffset.left + $ele.width() - $pop.width() + c.horizontalOffset);
					}
					$(document).bind('mousedown', this._checkMouse);
				}
			},
			setRenderCallback : function(a)
			{
				if (a && typeof(a) == 'function') {
					a = [a];
				}
				this.renderCallback = this.renderCallback.concat(a);
			},
			cellRender : function ($td, thisDate, month, year) {
				var c = this.dpController;
				var d = new Date(thisDate.getTime());
				
				// add our click handlers to deal with it when the days are clicked...
				
				$td.bind(
					'click',
					function()
					{
						var $this = $(this);
						if (!$this.is('.disabled')) {
							c.setSelected(d, !$this.is('.selected') || !c.selectMultiple);
							var s = c.isSelected(d);
							$(c.ele).trigger('dateSelected', [d, $td, s]);
							$(c.ele).trigger('change');
							if (c.closeOnSelect) {
								c._closeCalendar();
							} else {
								$this[s ? 'addClass' : 'removeClass']('selected');
							}
						}
					}
				);
				
				if (c.isSelected(d)) {
					$td.addClass('selected');
				}
				
				// call any extra renderCallbacks that were passed in
				for (var i=0; i<c.renderCallback.length; i++) {
					c.renderCallback[i].apply(this, arguments);
				}
				
				
			},
			// ele is the clicked button - only proceed if it doesn't have the class disabled...
			// m and y are -1, 0 or 1 depending which direction we want to go in...
			_displayNewMonth : function(ele, m, y) 
			{
				if (!$(ele).is('.disabled')) {
					this.setDisplayedMonth(this.displayedMonth + m, this.displayedYear + y);
					this._clearCalendar();
					this._renderCalendar();
					$(this.ele).trigger('dpMonthChanged', [this.displayedMonth, this.displayedYear]);
				}
				ele.blur();
				return false;
			},
			_renderCalendar : function()
			{
				// set the title...
				$('h5', this.context).html(Date.monthNames[this.displayedMonth] + ' ' + this.displayedYear);
				
				// render the calendar...
				$('.dp-calendar', this.context).renderCalendar(
					{
						month			: this.displayedMonth,
						year			: this.displayedYear,
						renderCallback	: this.cellRender,
						dpController	: this,
						hoverClass		: this.hoverClass
					}
				);
				
				// update the status of the control buttons and disable dates before startDate or after endDate...
				// TODO: When should the year buttons be disabled? When you can't go forward a whole year from where you are or is that annoying?
				if (this.displayedYear == this.startDate.getFullYear() && this.displayedMonth == this.startDate.getMonth()) {
					$('.dp-nav-prev-year', this.context).addClass('disabled');
					$('.dp-nav-prev-month', this.context).addClass('disabled');
					$('.dp-calendar td.other-month', this.context).each(
						function()
						{
							var $this = $(this);
							if (Number($this.text()) > 20) {
								$this.addClass('disabled');
							}
						}
					);
					var d = this.startDate.getDate();
					$('.dp-calendar td.current-month', this.context).each(
						function()
						{
							var $this = $(this);
							if (Number($this.text()) < d) {
								$this.addClass('disabled');
							}
						}
					);
				} else {
					$('.dp-nav-prev-year', this.context).removeClass('disabled');
					$('.dp-nav-prev-month', this.context).removeClass('disabled');
					var d = this.startDate.getDate();
					if (d > 20) {
						// check if the startDate is last month as we might need to add some disabled classes...
						var sd = new Date(this.startDate.getTime());
						sd.addMonths(1);
						if (this.displayedYear == sd.getFullYear() && this.displayedMonth == sd.getMonth()) {
							$('dp-calendar td.other-month', this.context).each(
								function()
								{
									var $this = $(this);
									if (Number($this.text()) < d) {
										$this.addClass('disabled');
									}
								}
							);
						}
					}
				}
				if (this.displayedYear == this.endDate.getFullYear() && this.displayedMonth == this.endDate.getMonth()) {
					$('.dp-nav-next-year', this.context).addClass('disabled');
					$('.dp-nav-next-month', this.context).addClass('disabled');
					$('.dp-calendar td.other-month', this.context).each(
						function()
						{
							var $this = $(this);
							if (Number($this.text()) < 14) {
								$this.addClass('disabled');
							}
						}
					);
					var d = this.endDate.getDate();
					$('.dp-calendar td.current-month', this.context).each(
						function()
						{
							var $this = $(this);
							if (Number($this.text()) > d) {
								$this.addClass('disabled');
							}
						}
					);
				} else {
					$('.dp-nav-next-year', this.context).removeClass('disabled');
					$('.dp-nav-next-month', this.context).removeClass('disabled');
					var d = this.endDate.getDate();
					if (d < 13) {
						// check if the endDate is next month as we might need to add some disabled classes...
						var ed = new Date(this.endDate.getTime());
						ed.addMonths(-1);
						if (this.displayedYear == ed.getFullYear() && this.displayedMonth == ed.getMonth()) {
							$('.dp-calendar td.other-month', this.context).each(
								function()
								{
									var $this = $(this);
									if (Number($this.text()) > d) {
										$this.addClass('disabled');
									}
								}
							);
						}
					}
				}
			},
			_closeCalendar : function(programatic, ele)
			{
				if (!ele || ele == this.ele)
				{
					$(document).unbind('mousedown', this._checkMouse);
					this._clearCalendar();
					$('#dp-popup a').unbind();
					$('#dp-popup').empty().remove();
					if (!programatic) {
						$(this.ele).trigger('dpClosed', [this.getSelected()]);
					}
				}
			},
			// empties the current dp-calendar div and makes sure that all events are unbound
			// and expandos removed to avoid memory leaks...
			_clearCalendar : function()
			{
				// TODO.
				$('.dp-calendar td', this.context).unbind();
				$('.dp-calendar', this.context).empty();
			}
		}
	);
	
	// static constants
	$.dpConst = {
		SHOW_HEADER_NONE	:	0,
		SHOW_HEADER_SHORT	:	1,
		SHOW_HEADER_LONG	:	2,
		POS_TOP				:	0,
		POS_BOTTOM			:	1,
		POS_LEFT			:	0,
		POS_RIGHT			:	1
	};
	// localisable text
	$.dpText = {
		TEXT_PREV_YEAR		:	'Previous year',
		TEXT_PREV_MONTH		:	'Previous month',
		TEXT_NEXT_YEAR		:	'Next year',
		TEXT_NEXT_MONTH		:	'Next month',
		TEXT_CLOSE			:	'Close',
		TEXT_CHOOSE_DATE	:	'Choose date'
	};
	// version
	$.dpVersion = '$Id: jquery.js,v 1.3 2009/11/12 15:20:42 dpramesh Exp $';

	function _getController(ele)
	{
		if (ele._dpId) return $.event._dpCache[ele._dpId];
		return false;
	};
	
	// make it so that no error is thrown if bgIframe plugin isn't included (allows you to use conditional
	// comments to only include bgIframe where it is needed in IE without breaking this plugin).
	if ($.fn.bgIframe == undefined) {
		$.fn.bgIframe = function() {return this; };
	};


	// clean-up
	$(window)
		.bind('unload', function() {
			var els = $.event._dpCache || [];
			for (var i in els) {
				$(els[i].ele)._dpDestroy();
			}
		});
		
	
})(jQuery);

//From : ../reg/agent_resources.js  ____________
  
$(document).ready(function() {
    
  $('#agent-tools-link').bind('click', function(event) {
    var id = '#'+event.target.id+'-all';
    $(id).toggle();
  });
  $('#agent-deals-link').bind('click', function(event) {
    var id = '#'+event.target.id+'-all';
    $(id).toggle();
  });
  $('#agent-support-link').bind('click', function(event) {
    var id = '#'+event.target.id+'-all';
    $(id).toggle();
  });
});


//From : ../reg/track.js ____________
function isUpper(c) {
  return ('A' <= c && c <= 'Z');
}

function isDigit(c) {
  return ('0' <= c && c <= '9');
}

function popupError(urlBase) {
/*
  var popupURL= urlBase + "/common/track/error.htm";
  var windowOptions= "width=300,height=300,top=100,left=100";
  var errorWindow= window.open(popupURL, "ErrorWindow", windowOptions);
  errorWindow.focus();
*/
  var url = urlBase + 
    '/misc/track/error.htm?height=155&width=350&modal=true';

  tb_show("",url,""); 
}


var SUFFIX_LENGTH= 4;

function isValidOrderID(orderID, prefix) {
  var len= orderID.length;
  var prefixLen= prefix.length;
  if (len < prefixLen + 1 + 1 + SUFFIX_LENGTH) return false;
  if (orderID.indexOf(prefix) != 0) return false;
  var i= prefixLen;
  if (!isDigit(orderID.charAt(i++))) return false;
  while (isDigit(orderID.charAt(i))) i++;
  if (orderID.charAt(i++) != '-') return false;
  var suffixLength= 0;
  //relaxed suffix check since after reds suffix can be all letters
  //var wantDigit= (isDigit(orderID.charAt(i)));
  while (i < len) {
    //var c= orderID.charAt(i++);
    //if (wantDigit ? !isDigit(c) : !isUpper(c)) return false;
    //wantDigit= !wantDigit;
    suffixLength++; i++;
  }
  return suffixLength == SUFFIX_LENGTH;
}

function stripOrderID(orderID) {
  var firstIndex = orderID.indexOf("-");
  var lastIndex = orderID.lastIndexOf("-");
  return orderID.substring(firstIndex+1, lastIndex);
}

function upCaseAndValidate(widget, prefix) {
  widget.value= widget.value.toUpperCase();
  var isOk= isValidOrderID(widget.value, prefix);
  if (!isOk) {
    var url= document.URL;
    var urlBase= url;
    var firstDot= url.indexOf('.');
    if (firstDot >= 0) {
      var urlBaseEnd= url.indexOf('/', firstDot);
      if (urlBaseEnd >= 0) {
        //var urlCountryEnd = url.indexOf('/', urlBaseEnd+1);
        //if (urlCountryEnd >= 0) urlBase= url.substr(0, urlCountryEnd);
        urlBase = url.substr(0, urlBaseEnd);
      }
    }
    popupError(urlBase);
  }
  else {
    widget.value = stripOrderID(widget.value);
  }
  return isOk;
}
