/**
 * Validate the entered attraction city.  If valid then create and navigate to the URL for the specified attraction.
 */
function attractionFormOnSubmit()
{
    var url = $('attractionCityUrl').value;
    if (url == '') 
    {
        // TODO: Maybe we do have a match in the list and they typed it or did a copy/paste?
        alert(JS_choose_valid_city);
        return false;
    }
    
    // Find selected radio for category parameter.
    var radios = $$('input[name=c]');
    var category = "0";
    for(y=0;y<radios.length;y++){
        if (radios[y].checked) {
            category = radios[y].value;
            break;
        }
    }
    if (category != "0") {
        url = url.replace("-Activities-","-Activities-c"+category+"-");
    }

    document.location.href = url 
    return false;
}

/**
 * Selects 'all attractions' and disables radio buttons if broad, and enables all radio buttons if not broad.
 */
function updateAttractionCategory(broad)
{
    var radios = $$('input[name=c]');
    
    if (broad) {
        radios[0].checked = true;
        for(y=0;y<radios.length;y++){
            radios[y].disabled = true;
        }
    }
    else {
        for(y=0;y<radios.length;y++){
            radios[y].disabled = false;
        }
    }
}

/**
 * Validate the entered restaurant city.  If valid then create and navigate to the URL for the specified attraction.
 */
function restaurantFormOnSubmit()
{
    var url = $('restaurantCityUrl').value;
    if (url == '') 
    {
        // TODO: Maybe we do have a match in the list and they typed it or did a copy/paste?
        alert(JS_choose_valid_city);
        return false;
    }
    
    document.location.href = url;
    return false;
}

/**
 * Process the Cruise Critic Cruise Review form from the Plan the Perfect Trip Cruise Critic Tab
 *
 * expects a Cruise Critc CruiseLineId to be selected - redirect to the Cruise Critic site
 * with this Id.
 */
function cruiseCriticReviewFormOnSubmit()
{
    var CRUISE_CRITIC_DEFAULT_COUNTY = 'us';
    var CRUISE_CRITIC_URL_BASE_MAP = new Object();
    CRUISE_CRITIC_URL_BASE_MAP['us'] = "/ShowUrl-a_url.http%3A__2F____2F__www__2E__cruisecritic__2E__com__2F__reviews__2F__cruiseline__2E__cfm__3F__CruiseLineID%3D";
    CRUISE_CRITIC_URL_BASE_MAP['uk'] = "/ShowUrl-a_url.http%3A__2F____2F__www__2E__cruisecritic__2E__co__2E__uk__2F__reviews__2F__cruiseline__2E__cfm__3F__CruiseLineID%3D";
    var CRUISE_CRITIC_URL_TAIL = ".html";
    var cruiseLineSelectBox = $('cruiseLineReview');
    var cruiseCriticCountry = $('cruiseCriticCountry').value;
    if (cruiseLineSelectBox.selectedIndex == 0)
    {
        alert(JS_select_a_cruise_line);
        return false;
    }

    var cruiseLineId = cruiseLineSelectBox.options[cruiseLineSelectBox.selectedIndex].value;

    //Build the URL
    // the last 5 chars are the .html added by $util.encode() when the velocity file is processed
    var countryUrlBaseMap = CRUISE_CRITIC_URL_BASE_MAP[cruiseCriticCountry]
    if (countryUrlBaseMap == undefined)
    {
        countryUrlBaseMap = CRUISE_CRITIC_URL_BASE_MAP[CRUISE_CRITIC_DEFAULT_COUNTY];
    }
    var cruiseLineReviewUrl = countryUrlBaseMap + cruiseLineId + CRUISE_CRITIC_URL_TAIL;
    //alert("jump To:" + cruiseLineReviewUrl);
    window.open(cruiseLineReviewUrl);
    return false;
}


var semSearchGoToSelectedPage = function(elemt, resObj, elmt) {
    $('mainSearchSubmit').onclick = function () { location.href=resObj.url; return false; };
    location.href=resObj.url;
};

rules['input.semTypeAhead[type=text]'] = function(elmt) {
 if (action = elmt.className.match(/\bact(\w+)\b/)) {
   var onSelectFunc = elmt.className.match(/\bonSel-([\w\.]+)\b/);
   if ((onSelectFunc != null) && (onSelectFunc.length > 0))
   {
       onSelectFunc = eval(onSelectFunc[1]);
   }
   
   //  check if we have a custom zIndex
   var zIndex = 42; //  42 is the default in Autocompleter.js
   var zIndexClass = elmt.className.match(/zIndex-(\d+)/);
   if (zIndexClass != null)
   {
       zIndex = zIndexClass[1];
   }
   
   new Autocompleter.Ajax.JsonSEM(elmt, "/TypeAheadJson?action="+action[1], {
     ajaxOptions: {method:'get'},
     postVar: 'query',
     inheritWidth: false,
     'zIndex':zIndex,
     onSelect: function(elemt, resObj) {
       if (onSelectFunc) {
         onSelectFunc(elemt, resObj, elmt);
       }
     }
   });
 }
}

ajaxRules['input.attractionTypeAhead'] = function(elmt) {
  if (action = elmt.className.match(/\bact(\w+)\b/)) {
    new Autocompleter.Ajax.Json2(elmt, "/TypeAheadJson?action="+action[1], {
      ajaxOptions: {method:'get'},
      postVar: 'query',
      inheritWidth: false,
      onSelect: function(elmt, resObj) {
        $('attractionCityUrl').value = resObj.url;
        updateAttractionCategory(resObj.broad);
      }
    });
  }
}

ajaxRules['input.restaurantTypeAhead'] = function(elmt) {
  if (action = elmt.className.match(/\bact(\w+)\b/)) {
    new Autocompleter.Ajax.Json2(elmt, "/TypeAheadJson?action="+action[1], {
      ajaxOptions: {method:'get'},
      postVar: 'query',
      inheritWidth: false,
      onSelect: function(elmt, resObj) {
        $('restaurantCityUrl').value = resObj.url;
      }
    });
  }
}

rules['span.dsrc'] = function(elmt) 
{ 
  var elmtP = elmt.getParent();
  // Make AJAX call to get content -delay it 10ms to let IE process the rest of the JS first.
  (function () {
    new Ajax('/' + elmt.innerHTML + '.html', {
      update: elmtP,
      onComplete: function(txt, xml) { window.behavior.apply(elmtP);  } // apply any defined behavior
      }).request();
  }).delay(10);
}

ajaxRules['#ATTRACTION_FORM'] = function(elmt) {
  elmt.addEvent('submit', function(e) {
    if (!attractionFormOnSubmit()) { (new Event(e)).stop(); }
  });
}

ajaxRules['#RESTAURANT_FORM'] = function(elmt) {
  elmt.addEvent('submit', function(e) {
    if (!restaurantFormOnSubmit()) { (new Event(e)).stop(); }
  });
}

ajaxRules['#CRUISE_CRITIC_REVIEWS_FORM'] = function(elmt) {
  elmt.addEvent('submit', function(e) {
    if (!cruiseCriticReviewFormOnSubmit()) { (new Event(e)).stop(); }
  });
}

rules['#FLIGHT_FORM input.flightTypeAhead[type=text]'] = function(elmt) {
  var action = elmt.className.match(/\bact(\w+)\b/);
  if (action) {
    new Autocompleter.Ajax.Json2(elmt, "/TypeAheadJson?action="+action[1], {
      ajaxOptions: {method:'get'},
      postVar: 'query',
      className: 'autocompleter-choices flights',
      inheritWidth: false,
      selectOnBlur: true,
      onSelect: function(elmt, resObj) {
        elmt.value = resObj.value;
        elmt.fireEvent('updateairport');
      }
    });
  }
};

rules['#UNDER_13'] = function(elmt) {
	  var text ="<div class='coppa'><div class='alertIcon'><img src='img2/generic/site/alert.gif'></div>";
	  text+="<div class='alertText'>";
	  text+="<div class='title'>"+JS_coppa_sorry+"</div>";
	  text+=JS_coppa_privacy+"<br/><br/>";
	  text+=JS_coppa_deleted+"<br/><br/>";
	  text+="<img id='LIGHTBOX_CLOSE' alt="+JS_close+" src="+JS_close_image+"></div></div>";
    ta.overlays.showInLightbox(text);
};

// FFM FLIGHT_FORM_META
var HomeFFM = {
  makeAutocompleter: function(elmt) {
    new Autocompleter.Ajax.Flights(elmt, "/TypeAheadJson?action=AIRPORT", {
      ajaxOptions: {method:'get'},
      postVar: 'query',
      minLength: 3,
      className: 'autocompleter-choices flights',
      inheritWidth: false,
      selectOnBlur: true,
      onSelect: function(elmt, resObj) {
        elmt.value = resObj.name;
        $(elmt.id + 'Code').value = resObj.value;
      }
    });
    elmt.addEvent('focus', function() {
      HomeFFM.hideCalendar();
      elmt.select();
    });
  },
  hideCalendar: function() {
    if (window.calendar && window.calendar.flyout) {
      window.calendar.flyout.hide(false);
    }
  },
  moreOptionsSubmit: function(hashTag) {
    if (!hashTag || typeof(hashTag) == 'undefined') {
      hashTag = 'more';    
    }
    $('FLIGHT_FORM_META').action='/Flights#' + hashTag;
    $('FLIGHT_FORM_META').submit();
    return false;
  },
  setLastDate: function(elmt) {
    var lastDate = new Date();
    lastDate.setHours(0,0,0,0);
    // 330 days in milliseconds: 330*24*60*60*1000 = 28512000000
    lastDate.setTime(lastDate.getTime() + 28512000000);
    elmt.lastDate = lastDate;
  }
};
rules['#metaFlightFrom'] = HomeFFM.makeAutocompleter;
rules['#metaFlightTo'] = HomeFFM.makeAutocompleter;
rules['#metaCheckInSpan'] = HomeFFM.setLastDate;
rules['#metaCheckOutSpan'] = HomeFFM.setLastDate;

// Must match the order of items in CurrencyCriteria. used to translate
// indexes to currency codes - so that changes to currency criteria can 
// repopulate prices in the max rate filter
var currencyCodes = new Array ("USD", "EUR", "GBP", "CAD", "AUD", "CHF", "JPY", "RMB", "INR", "SEK", "BRL", "TRY", "DKK", "MXN", "NOK", "PLN", "SGD", "THB");

function currencyIndex (currency)
{
   for (var i = 0; i < currencyCodes.length; i++)
   {
      if (currency == currencyCodes[i]) {return "" + i;}
   }
   return "0";
}

function setCurrency (currency, bCriteria)
{
   var input;
   if (bCriteria)
   {
      document.getElementById("zfk").value = currency == null ? 0 : currency;
   }
   else
   {
      document.getElementById("currency").
               value= currency == null ? 'USD' : currency;
   }

   if (currency == null) return 'USD';
   return bCriteria ? currencyCodes [parseInt(currency)] : currency;
}

// HAC-Related stuff that Used to live in tripadvisor.js
function fillRates(currency, bCriteria)
{
   currency = setCurrency (currency, bCriteria);
   var rateSelect = document.
                       getElementById(bCriteria ? "zfp" : "minmaxrate").options;
   rateSelect.length = 0;
   var levels = currencyLevel[currency];
   for (var i = 0 ; i < levels.length ; i += 2)
   {
       var label = levels[i];
       var value = bCriteria ? i/2 : levels[i+1];
       rateSelect[i/2] = new Option(label, value);

       // if the current max rate is in the minmax value string, select it
       if ( levels[i+1].indexOf("," + maxRate) > 0)
       {
	   rateSelect.selectedIndex = i/2;
       }
   }
}

function fillRatesAndClear(currency, bCriteria)
{
	maxRate = '9999999';
	fillRates(currency, bCriteria);
}

function setLCurrency (currency, bCriteria)
{
   var input;
   if (bCriteria)
   {
      $("l1currency").value = currency == null ? 0 : currency;
   }
   else
   {
      $("currency").value= currency == null ? 'USD' : currency;
   }

   if (currency == null) return 'USD';
   return bCriteria ? currencyCodes [parseInt($("l1currency").value)] : currency;
}

function fillRatesLightning(priceSelectVal)
{
   $("l1currency").value = (priceSelectVal == null) ? 0 : priceSelectVal;
   currency = currencyCodes [parseInt($("l1currency").value)];
   var currencyVals = currencyHash [parseInt($("l1currency").value)];
   
   if($('priceSelect'))
   {
     $('priceSelect').setProperty('class', ''); 
     $('priceSelect').addClass('s' + currencyVals.steps);
     $('priceSelect').addClass('mn' + currencyVals.min);
     $('priceSelect').addClass('mx' + currencyVals.max);
     $('priceSelect').addClass('smin' + currencyVals.selMin);
     $('priceSelect').addClass('smax' + currencyVals.selMax);
     $('priceSelect').addClass('dualSliderTest');
     $('priceSelect').addClass('round');
     $('priceSelect').addClass('namepslider');
     $('priceSelect').addClass('cur' + parseInt($("l1currency").value));
     dualSliderRule($('priceSelect'));
   }
}

var homeHacGeoChanged = function(elmt, response) {
  $('HAC_FORM').geo.value = response.value;

  // pool test flight search popunder
  var flightAirInput = $('geoAirport');
  if( flightAirInput && typeof(gHomeAirport) != "undefined" && gHomeAirport != "" ) {
    if(response.value != '') {  
      new Ajax('/AirportFromGeoAjax?g=' + response.value, {
        method: 'get',
        onComplete: function(txt) {
          if( txt == gHomeAirport) {          
            flightAirInput.value = "";
            $('popFltSrch').hide();  // hide the checkbox
          } else {
            flightAirInput.value = txt;
            $('popFltSrch').show();  // show the checkbox
          }
        }
      }).request();
    }
  }
}

/* If hidden geo field has been set, clear it when we type in the text input
 * field. It will be set again if the user chooses from typeahead.
 */
rules['#hacGeo'] = function(elmt) {
    var ignoreKeys = ['enter', 'up', 'down', 'left', 'right', 'tab']; //mootools constants
    elmt.addEvent('keypress', function(e) {
        var evt = new Event(e);
        if(ignoreKeys.indexOf(evt.key) == -1)
        {
            $('HAC_FORM').geo.value = '';
        }
    });
}

/*
 * Update the rate drop down for the accommodation overview
 */
function updateOverviewRate()
{
  //  get the selected periodicity
  var pricePeriodWeekly = $('pricePeriod_w');
  var periodicity = pricePeriodWeekly && pricePeriodWeekly.checked ? 'w' : 'd';

  //  get the selected currency
  var l1currency = $("l1currency");
  var currency = l1currency ? l1currency.value : 0; // default to USD

  //  grab the price select and empty all children except the 'Any' option
  var select = $('l1price');
  var anyOptionLabel = select.getElement('option').innerHTML;
  select.empty();
  var anyOption = new Element('option', {'value':0});
  anyOption.innerHTML = anyOptionLabel;
  select.appendChild(anyOption);

  //  construct the map key and get the new set of options
  var key = periodicity + '_' + currency;
  var options = periodicPriceMap[key];
  for (var optionLabel in options)
  {
      var newOption = new Element('option', {'value':options[optionLabel]});
      newOption.innerHTML = optionLabel;
      select.appendChild(newOption);
  }
}/**
 * @class
 * Support functions used on VRACSearch servlet as well as the VRAC form (typeahead, etc.).
 */
ta.servlet.VRACSearch = {

    /**
     * @param {HTMLElement} elmt the typeahead elemnt
     * @param {Object} response the typeahead response 
     */
    homeVRGeoChanged:function(elmt, response)
    {
      $('VRAC_FORM').geo.value = response.value;
      var vrAlternatives = $('vrAlternatives');
      if (!response.vrpresent)
      {
        var buffer = [];
        buffer.push('<div class="sorry">');
        buffer.push(msg_no_vrs.replace('{0}', response.name));
        buffer.push('</div>');
    
        if (response.hasHotels)
        {
            var href = response.hotelUrl;
            if (!href)
            {
                href = '/Hotels-g' + response.value;
            }
    
            buffer.push('<div class="searchHotels">');
            buffer.push('<a href="' + href + '" rel="nofollow">');
            buffer.push(msg_search_hotels.replace('{0}', response.name));
            buffer.push('</a>');
            if (response.vralternatives.length == 0)
            {
                buffer.push('&nbsp;');
                buffer.push(msg_try_nearby);
            }
            buffer.push('</div>');
        }
        if (response.vralternatives.length > 0)
        {
            buffer.push('<div class="check">');
            buffer.push(msg_check_nearby);
            buffer.push('</div>');
            buffer.push('<ul class="locations">');
            var length = response.vralternatives.length;
            for (var i = 0; i < length; i++)
            {
                var vrAlt = response.vralternatives[i];
                buffer.push('<li><span class="fkLnk hvrIE6" onclick="ta.servlet.VRACSearch.chooseVracAlternative(\'');
                buffer.push(vrAlt.name);
                buffer.push('\',\'');
                buffer.push(vrAlt.value);
                buffer.push('\');">');
                buffer.push(vrAlt.name);
                buffer.push('</span></li>');
            }
            buffer.push('</ul><ul class="distance">');
            for (var i = 0; i < length; i++)
            {
                var vrAlt = response.vralternatives[i];
                buffer.push('<li>');
                buffer.push((vrAlt.unit == 'm' ? msg_miles_away : msg_km_away).replace('{0}', vrAlt.dist));
                buffer.push('</li>')
            }
            buffer.push('</ul>')
        }
    
        //  set the content
        var content = vrAlternatives.getElement('.content');
        content.innerHTML = buffer.join('');
        
        //  now that the new elements are part of the DOM add the 'hvrIE6' behavior
        if (window.ie6)
        {
            content.getElements('.hvrIE6').each(rules['span.hvrIE6']);
        }
        
        //  show the alternatives
        ta.servlet.VRACSearch.showVracAlternatives();
      }
      else
      {
          ta.servlet.VRACSearch.hideVracAlternatives();
      }
    },
    
    chooseVracAlternative:function(name, value)
    {
        $('vracGeo').value = name;
        $('VRAC_FORM').geo.value = value;
        ta.servlet.VRACSearch.hideVracAlternatives();
    },
    
    showVracAlternatives:function(event, element)
    {
        //  'vrMidForm' is present on the home page and lander typeaheads but not the /VRACSearch typeahead
        var vrMidForm = $('vrMidForm');
        if (vrMidForm)
        {
            vrMidForm.style.display = 'none';
        }

        $('vrAlternatives').style.display = 'block';
    },
    
    hideVracAlternatives:function(event, element)
    {
        $('vrAlternatives').style.display = 'none';

        //  'vrMidForm' is present on the home page and lander typeaheads but not the /VRACSearch typeahead
        var vrMidForm = $('vrMidForm');
        if (vrMidForm)
        {
            vrMidForm.style.display = 'block';
        }
    },
    
    hideVracAlternativesAndClearBox:function(event, element)
    {
        ta.servlet.VRACSearch.hideVracAlternatives();
        $('vracGeo').value = '';
    }
};/**
 * 
 * @author dwigginton
 * @since  2010.06.16
 *
 *  Generate a flight search popunder via checkbox on HAC 
 */
ta.popups.FlightSearch = {
   
  /**
   *  Onclick for the HAC submit button, determines if flight search is selected, converts an input to name=pid  
   */
   popFlightSearch: function(event, elmt) {
   var chkFS = $('findFlights');
   var hacForm = $('HAC_FORM');
   var pidInput = $('pidTarget');
   
   if( chkFS && chkFS.checked ) {
     try {
       if( hacForm.pid ) {
         hacForm.pid.value = "3384";
       } else {
         if(pidInput) { 
           pidInput.name = "pid"; // pidTarget -->  pid 
         }
       }
       ta.popups.FlightSearch.openWindow();
     }
     catch(e) {}
   } 
   return true;   
  },
  
  /**
   *  Open the popunder 
   */
  openWindow:function() {
    var sUrl = ta.popups.FlightSearch.getChpFltsUrl();
    var w = 780;
    var h = 580;
    if( window.screen ) {   //  all supported browsers 
      w = ( screen.availWidth > 1000 ) ? 1000: 780;    
      h = parseInt( .8 * screen.availHeight );  //  a high % of available height
    } 
    var winOps = "width=" + w + ",height=" + h + ",screenX=25,screenY=25,left=25,top=25,toolbar=1,location=1,directories=1,status=1,menubar=1,resizable=1,copyhistory=1,scrollbars=1";
    var OPEN_FLT_POP = window.open(sUrl, 'FlightSearch', winOps);
    if (OPEN_FLT_POP != null )
    {
      OPEN_FLT_POP.opener = self;
      OPEN_FLT_POP.blur();
    }
  },
  
  /**
   *  Format dates for CheapFlights URL ( which is always US format )
   */
  flightsDate: function ( sDate, bUS ) {
    var aItms = sDate.split('/');
    if( !aItms.length ) {
       return sDate;
    }
    for(var i=0; i < aItms.length; i++ ) {
      if(aItms[i].length < 2) {
        aItms[i] = '0' + aItms[i];
      }
    }
    return (bUS) ? aItms[2] + aItms[0] + aItms[1] : aItms[2] + aItms[1] + aItms[0];
  },
 
  /**
   *  Build the url for the popunder
   */
  getChpFltsUrl: function () {
        
    // got dates
    var chpFltsUrl = 'CheapFlights?travelers=1&cos=0&nonstop=no&nearby0=no&nearby1=no&time0=anytime&time1=anytime&';
    // no dates
    var fareCalUrl = 'FareCalendar?adults=1&';
    
    var chkIn = $('checkIn').value;
    var chkOut = $('checkOut').value;
    var strDates = chkIn + chkOut;
    var aPrms = [];
    
    aPrms.push( 'date0=' + ta.popups.FlightSearch.flightsDate(chkIn, gIS_US ));  
    aPrms.push( 'date1=' + ta.popups.FlightSearch.flightsDate(chkOut, gIS_US ));  
    aPrms.push( 'airport0=' + gHomeAirport );
    //aPrms.push( 'geo=60745');  // Note: geo determines currency
    
    // Get the destination airport
    if( typeof(gAirportFromPageLoc) != "undefined" ) {
      aPrms.push( 'airport1=' + gAirportFromPageLoc );
    } else {  // non geo pages: airport is retrieved as part of typeahead
      var destFromPage = $('geoAirport');
      if( destFromPage ) {
        aPrms.push( 'airport1=' + destFromPage.value ); 
      }
    }
    
    // if the date field is not mm/dd/yyy etc.
    if( parseInt(strDates) ) {
      return chpFltsUrl + aPrms.join('&');
    } else {
      return fareCalUrl + aPrms.join('&');    
    }
  }  
 };
 