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 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("");
};
