/*
Class: DynamicRating

Arguments:
  elmt - required, the visual rating control
  options - optional, see options below

Options:
*/
var DynamicRating = new Class({
  options: {
    size: 6,
    prefix: 's',
    values: {
      0: '00',
      1: '10',
      2: '20',
      3: '30',
      4: '40',
      5: '50'
    },
    prefixes: {},
    update: null,
    textNode: false,
    strings: null,
    attributeNode: false,
    ratingNode: false,
    ratingNodeClass: false
  },

  initialize: function(elmt, options) {
    this.setOptions(options);
    this.src = elmt;
    this.src.addEvent('mouseenter', this.enter.bindWithEvent(this));
    this.src.addEvent('mouseleave', this.leave.bindWithEvent(this));
    this.src.addEvent('click', this.select.bindWithEvent(this));
    this.handler = this.move.bindWithEvent(this);

    // find current class
    this.current = -1;
    for (var i = 0; i <= this.options.size && this.current < 0; i++) {
      if (this.src.hasClass(this.classFor(i))) this.current = i;
    }
    this.selected = this.current;

    // calculate edge bounds
    this.width = this.src.getSize().size.x;
    this.per = Math.round(this.width / 5);
  },

  classFor: function(i) {
    return $pick(this.options.prefixes[i], this.options.prefix) + this.options.values[i];
  },

  getIndexForPosition: function(pos) {
    var x = Math.max(pos - this.offsets.left, 1);
    x = Math.ceil(x / this.per);
    x = Math.min(x, 5);
    return x;
  },

  enter: function(e) {
    this.src.addEvent('mousemove', this.handler);
    this.offsets = this.src.getCoordinates();
  },

  leave: function(e) {
    this.src.removeEvent('mousemove', this.handler);
    this.show(this.selected);
    if (this.selected <= 0 && this.options.ratingNode && this.options.ratingNodeClass) {
      this.options.ratingNode.addClass(this.options.ratingNodeClass);
    }
  },

  move: function(e) {
    this.show(this.getIndexForPosition(e.page.x));
  },

  show: function(c) {
    if (c > 5) c = 5; // Bounds check
    this.src.removeClass(this.classFor(this.current));
    this.src.addClass(this.classFor(c));
    this.current = c;
    if (this.options.textNode && this.options.strings) {
      this.options.textNode.setText(this.options.strings[this.current]);
      if (this.options.ratingNode && this.options.ratingNodeClass) {
        this.options.ratingNode.removeClass(this.options.ratingNodeClass);
      }
    }
  },

  select: function(e) {
    this.selected = this.getIndexForPosition(e.page.x);
    if (this.options.update) {
      this.options.update.value = this.selected;
    }
    if (this.options.attributeNode) {
      this.options.attributeNode.show();
    }

    if (isInlineForm()) {
      inlineFormModified();
    }
  }
});
DynamicRating.implement(new Options);

///
/// Support Functions
///

var updatePurpose = function(e) {
  e = new Event(e);
  var src = $(e.target);
  var hide = "notWith" + src.id.substring(src.id.indexOf("_")+1).capitalize();
  var box = src.getParent('dd').getElement('div.addl').setStyle('display', 'inline');
  var select = box.getElement('select');
  select.show();
  select.removeProperty('disabled');
  var selected = select.options[select.selectedIndex].value;
  var idx = 0;
  if (!select.allOptions) {
    select.allOptions = $A(select.options);
  }
  select.empty();
  var i = 0;
  select.allOptions.each(function(o) {
    o = $(o);
    if (!o.hasClass(hide)) {
      try {
        select.add(o, null); // standards-compliant, doesn't work in IE
      }
      catch(ex) {
        select.add(o); // IE only
      }
      // only record new selected index if not reseting
      if (src.skipReset && o.value == selected) idx = i;
      i++;
    }
  });
  if (src.skipReset) src.skipReset = false;
  select.selectedIndex = idx;
}

var updateReservation = function(e) {
  e = new Event(e);
  var src = $(e.target);
  var show = "with" + src.id.substring(src.id.indexOf("_")+1).capitalize();
  src.getParent('dd').getElements('div.rdoExt').each(function(ext) {
    if (ext.hasClass(show)) ext.show();
    else ext.hide();
  });
}

var requestPreview = function() {
  if (window.PREVIEW_REQUESTED) return;
  window.PREVIEW_REQUESTED = true;
  new Ajax('/UserReviewPreview', {
    data: $('USER_REVIEW_FORM'),
    evalScripts: true,
    onComplete: previewResponse
  }).request();
}

var previewResponse = function(t, x) {
  window.PREVIEW_REQUESTED = false;
  if (t.indexOf('PREVIEW_ERROR') >= 0) {
    disableUnloadCheck();
    $('submitAction').value = "submitPreview";
    submitURForm();
  }
  else {
    new ta.overlays.CenteredOverlay({
      backdrop: ta.overlays.BACKDROP_ALWAYS,
      showCloseButton: false,
      style: 'ur_prev',
      onLoad: function(lb) {
        var h = window.getHeight() - 50;
        if (lb.container.getCoordinates().height > h) {
          lb.inner.getElement('.traveler').setStyle('height', h - 100);
          lb.position();
        }
        $('PREVIEW_CANCEL').addEvent('click', lb.hide.bind(lb));
      }
    }).loadRemoteSuccess(t);
  }
}

// bound to radio button
var changeSearchType = function() {
  if (window.searchType) {
    $$('span.'+window.searchType.id).hide();
  }
  window.searchType = this;
  $('SRCH_BOX').show();
  $$('span.'+this.id).setStyle('display','inline');
  var q = $('query');
  if (q.value.length > 0) searchByType();
  q.focus();
  q.select();
}

var searchByType = function(e) {
  if (e) new Event(e).stop();
  new Ajax('/TypeAheadJson?action=PROPERTY', {
    data: $('UR_FIND'),
    onComplete: displaySearchResults
  }).request();
}

var displaySearchResults = function(t, x) {
  var box = $('RESULT_LIST');
  var error = box.getElement('.error').remove();
  box.empty().adopt(error);
  var data = eval('('+t+')');
  if (!data || data.length < 1) {
    error.show();
    $('WRBTN').hide();
  }
  else {
    error.hide();
    $('WRBTN').setStyle('display', 'inline');
    data.each(function(i){
      new Element('div', {'class':'optn'}).adopt(
        new Element('input', {type:'radio', name:'detail', id:'detail_'+i.value, value:i.value}),
        new Element('label', {'for':'detail_'+i.value}).setText(i.name)
      ).injectInside(box);
    });
    box.setStyle('height', data.length < 8 ? 'auto' : '120px');
  }
  $('UR_SELECT_ERROR').hide();
  $('SRCH_RSLT').show();
}

var writeReview = function() {
  var form = $('UR_SELECT');
  var ok = false;
  form.getElements('input[type=radio]').each(function(r){
    if (r.checked) {
      ok = true;
      form.submit();
      return;
    }
  });
  // user did not pick a property in the list
  if (!ok) $('UR_SELECT_ERROR').setStyle('display', 'inline');
}

var fromInlineReview = false;
var loginSuccess = function(returnTo, tt) {
  disableUnloadCheck();
  if (isInlineForm()) {
    hideIFrame();
    if (fromInlineReview) {
      submitURFormAjax();
    } else {
      if (returnTo != null && returnTo.length > 0){
        window.location = returnTo;
      }
    }
  }
  else {
    submitURForm();
  }
}

var resetPassword = function(email, returnTo){
  returnTo = window.location.protocol + '//' + window.location.hostname + returnTo;
  var lb = new ta.overlays.CenteredOverlay({
    backdrop: ta.overlays.BACKDROP_ALWAYS,
    onHide: function(){
      submitURForm();
    }
  });
  lb.loadRemoteContent(returnTo + "&skin=iframe");
}

var checkUnload = function(e) {
  if (!$defined(e)) e = window.event;
  if (e) e.returnValue = JS_review_lost;

  if (isInlineForm()) {
    new Ajax('/ActionRecord?action=InlineFormCanceled').request();
  }

  return JS_review_lost;
}

var isInlineForm = function() {
  var form = $('USER_REVIEW_FORM');
  return form && form.inlineForm && form.inlineForm.value == 'true';
}

var disableUnloadCheck = function() {
  window.removeEvent('beforeunload', checkUnload);
}

var enableUnloadCheck = function() {
  window.addEvent('beforeunload', checkUnload);
}

var removePhoto = function() {
  var container = this.getParent('div.photo');
  var input = container.getElement('input.fldID');
  input.name = input.name.replace(/id$/, 'remove');
  $('submitAction').value = "submitRemove";
  submitURForm();
}

function getFootprint()
{
    try
    {
        var FootprintId = TALSO.get('CookieId');

        if( FootprintId == '' )
        {
            TALSO.set( 'CookieId', $('LsoId').value );
            if( TALSO.get('CookieId') != $('LsoId').value )
            {
                $('LsoId').value = '';
            }
        }

        else $('LsoId').value = FootprintId;
    }

    catch (e)
    {
        if( $('LsoId') ) $('LsoId').value = '';
    }

    if( $('LsoId') ) return $('LsoId').value;
    return '';
}

var manageLsoId = function() {
  $('screenWidth').value = screen.width;
  $('screenHeight').value = screen.height;
  getFootprint();
}

var submitURForm = function(disableUnload) {
  prepareSubmission();
  if (validateURForm) $('USER_REVIEW_FORM').submit();
}

var submitURFormAjax = function() {
  prepareSubmission();
  var form = $('USER_REVIEW_FORM');
  var uri = form.action;

  var ops = {
    data: form,
    onComplete: submitComplete,
    method: 'POST',
    evalScripts: true
  }

  new Ajax(uri, ops).request();
}

var submitComplete = function(txt, xml) {
  if (txt.match(/id="UR_THANKS"/)) {
    new ta.overlays.CenteredOverlay({
      backdrop: ta.overlays.BACKDROP_ALWAYS
    }).loadRemoteSuccess(txt);
    var ops = {
      update: $('INLINE_FORM'),
      onComplete: function() {
        window.behavior.apply($("INLINE_FORM"))
      }
    }
    new Ajax($('editUrl').value, ops).request();
  }
  else {
    $('INLINE_FORM').innerHTML = txt;
    window.behavior.apply($("INLINE_FORM"));
  }
}

var prepareSubmission = function() {
    $('SBMT_WRP').hide();
    if ($('PRVW_WRAP')) {
        $('PRVW_WRAP').hide();
        $('PRVW_SPNR').show();
    }
    else {
        $('SBMT_SPNR').show();
    }
    disableUnloadCheck();
    manageLsoId();
}

var validateURForm = function() {
  var form = $('USER_REVIEW_FORM');

  // make sure title is not a sample title
  var title = $('ReviewTitle');
  if (title.hasClass('focusClear') && // only used w/ sample title
        title.value == title.defaultValue)
  {
    title.value = "";
  }
  return true;
}

var validateEateryThanks = function(e) {
  new Event(e || window.event).stop();
  var form = $('EATERY_THANKS');

  // make sure user selected a restaurant
  var url = false;
  form.getElements('input[type=radio]').some(function(input) {
    if (input.checked) url = input.value;
    return input.checked;
  });
  if (url) {
    Cookie.set('NPID', 1578, {domain: cookieDomain, time:5})
    window.location = url;
  }
  else $('EATERY_THANKS_ERROR').setStyle('display', 'inline');
}

function submitButtonHandler(event) {
  if (event) new Event(event).stop();
  submitURForm(true);
}

function submitButtonHandlerAjax(event) {
  if (event) new Event(event).stop();
  closeLightbox(); // close preview lightbox if applicable
  fromInlineReview = true;
  submitURFormAjax(true);
}

function previewLinkHandler(event) {
  $('submitAction').value = "submitPreview";
  submitURForm(true);
}

function previewLinkHandlerAjax(event) {
  $('submitAction').value = "submitPreview";
  fromInlineReview = true;
  submitURFormAjax(true);
}

function thanksFromSave() {
  ta.store('inlineFormThanksFromSave', true);
}

/*
    BEHAVIOR RULES
*/

//
// Hotel Edit
//

// Login iFrame
rules['#USER_REVIEW_FORM'] = function(elmt) {
  if (!isInlineForm()) {
    if (!previousReviewLightbox()) {
      enableUnloadCheck();
    }
  }

  // manage login/migration case
  var params = ['tt','ur','returnTo',window.location];

  if ($('ur_form_facebook_id')) {
    params.push('facebookId');
    params.push($('ur_form_facebook_id').value);
  }

  if (elmt.hasClass('loginRequired'))
  {
    if (dest = elmt.className.match(/fromGeo_(\d+)/)) {
        params.push('geo', dest[1]);
    }
    login(params);
  }

  else if (elmt.hasClass('migrationRequired'))
  {
    migrate(params);
  }

  if (elmt.hasClass('preview')) requestPreview();
}

// if appropriate, show a lightbox notifying user about previous reviews on property.
// Returns true if lightbox was shown.
var previousReviewLightbox = function() {
  var prevBox = document.getElementById("previousReviewMsg");
  if (prevBox) {
    var overlay = new ta.overlays.CenteredOverlay({backdrop: ta.overlays.BACKDROP_ALWAYS, showCloseButton: false, style: 's4 dg'}).loadRemoteSuccess(prevBox.innerHTML);
    ta.store("userreview.prevReviewMsg", overlay);
    return true;
  }
};

var closePreviousReviewLightbox = function(evt) {
  var overlay = ta.remove("userreview.prevReviewMsg");
  document.forms.USER_REVIEW_FORM.followup.value = "true";
  if (overlay) {
    overlay.hide(evt);
  }
}

var submitPreviousReview = function(evt) {
  document.forms.USER_REVIEW_FORM.followup.value = "true";
  submitButtonHandler(evt);
}

linkMap['js_letMeGo'] = disableUnloadCheck;

// rating circles
rules['#USER_REVIEW_FORM .rating'] = function(elmt) {
  dt = elmt.getElement('dt');
  dd = elmt.getElement('dd');
  selectedRating = addOverallDynamicRating(dt);
  addAttributeRatings(dd, selectedRating);
}

rules['#DEST_REVIEW_FORM .firstRating'] = function(elmt) {
  selectedRating = addOverallDynamicRating(elmt);
}


rules['#DEST_REVIEW_FORM .rating'] = function(elmt) {
  if (elmt)
  {
    selectedRating = elmt.getElement('input[type=hidden]');
    if (!selectedRating) {
      return 0;
    }

    var rateElmt = elmt.getElement('.rate');
    if (rateElmt)
    {
      var pattern = /qid.*[^\s]/;
      var arr = pattern.exec(rateElmt.className);
      var qid = null;
      if (arr != null && arr.length > 0 && arr[0].length > 3) {
        qid = arr[0].substring(3);
      }

      if (qid) {
        new DynamicRating(rateElmt, {
          update: selectedRating,
          textNode: elmt.getElement('em'),
          strings: RATING_STRINGS,
          prefixes: {0: 'gs'},
          ratingNode: $('ratingFlag' + qid),
          ratingNodeClass: 'flagged'
        });
      }
    }
  }
}

// Purpose of Trip radio buttons
rules['#USER_REVIEW_FORM dd.purpose input[type=radio]'] = function(elmt) {
  elmt.addEvent('click', updatePurpose);
  if (elmt.checked) {
    elmt.skipReset = true;
    elmt.click();
  }
}

rules['#USER_REVIEW_FORM input, #USER_REVIEW_FORM textarea, #USER_REVIEW_FORM select'] = function(elmt) {
  elmt.addEvent('change', inlineFormModified);
}

var inlineFormModified = function() {
  if (!ta.has('inlineFormModified')) {
    enableUnloadCheck();
    new Ajax('/ActionRecord?action=InlineFormModified').request();
    ta.store('inlineFormModified', true);
  }
};

// Tips & guidelines toggles
rules['#USER_REVIEW_FORM dd#REVIEW_TEXT, #USER_REVIEW_FORM dd#PHOTOS'] = function(elmt) {
  var lnk = elmt.getElement('span.tips');
  var box = elmt.getElement('div.tips');
  lnk.addEvent('click', function() {
    box.toggle();
    lnk.toggleClass('open');
  });
}

rules['#REVIEW_TEXT p.abortOK a'] = function(elmt) {
  elmt.addEvent('click', function() { disableUnloadCheck(); } );
}

// Describe your trip - Other
rules['#USER_REVIEW_FORM dl#UR_TRIP_TAGS dd.other'] = function(elmt) {
  var chk = elmt.getElement('input[type=checkbox]');
  var box = elmt.getElement('input[type=text]');
  chk.addEvent('click', box.toggle.bind(box));
}

// Amenities table - show 'Best out there?' option when Yes is selected
rules['#USER_REVIEW_FORM dd#HOTEL_AMENITIES table tbody tr'] = function(elmt) {
  var chk = elmt.getElement('input.yes');
  var box = elmt.getElement('td.best .chkSet');
  if (!box) return;
  var fn = function() {
    if (chk.checked) this.show();
    else this.hide();
  };
  elmt.getElements('input[type=radio]').addEvent('click', fn.bind(box));
}

// Preview Lightbox
ajaxRules['.traveler .review a'] = function(elmt) {
  elmt.addEvent('click', function(e) {new Event(e).stop();});
}

// Fraud "Learn more" flyout
ta.userreview = {
  fraudOverlay: function(evnt, elmt){
    new Event(evnt).stop();
    elmt.onclick = null;
    var g = $('geo');
    var d = $('detail');
    var params = (g || d) ? ("&g="+g.value+"&d="+d.value) : "";
    new ta.overlays.RelativeOverlayBelow({
      activate: ta.overlays.ACTIVATE_CLICK,
      style: 'typeO fraud',
      showCloseButton: true,
      remoteContent: '/vpages/fraud.html?lt=evt'+params
    }, elmt);
  }
};

// Remove photo "link"
rules['#PHOTOS div.photo span.hvrIE6'] = function(elmt) {
  elmt.addEvent('click', removePhoto.bind(elmt));
}

//
// Landing Page
//

// select property type
rules['#SRCH_TYPE input[type=radio]'] = function(elmt) {
  elmt.addEvent('click', changeSearchType.bind(elmt));
}

// search box
rules['#UR_FIND'] = function(elmt) {
  elmt.addEvent('submit', searchByType.bindWithEvent(elmt));
}

// Write Review button
rules['#WRBTN'] = function(elmt) {
  elmt.addEvent('click', writeReview);
}

// Unattached review link - post empty form
rules['#SRCH_RSLT .tips .hijack a'] = function(elmt) {
  elmt.addEvent('click', function(e) {
    new Event(e).preventDefault();
    var form = $('UR_SELECT');
    $A(['type_hotel', 'type_attraction', 'type_restaurant', 'type_location']).each(function(type){
      var input = $(type);
      if (input != null && input.checked) $('property_type').value = input.value;
    });
    form.getElements('input[type=radio]').each(function(r) { r.checked = false; });
    $('ReviewName').value = $('query').value;
    form.submit();
  });
}

rules['#UR_PROFILE'] = function(elmt) {
  elmt.addEvent('submit', function (e) {
    elmt.action = elmt.action + '?' + elmt.toQueryString();
    return true;
  });
}

//
// Restaurant Edit
//

rules['#EATERY_RESERVATIONS .rdoSet input'] = function(elmt) {
  elmt.addEvent('click', updateReservation);
  if (elmt.checked) {
    elmt.skipReset = true;
    elmt.click();
  }
}

rules['#EATERY_THANKS'] = function(form) {
  form.addEvent('submit', validateEateryThanks);
}

function isMaxLength(obj,mlength){
	if (obj.value && obj.value.length>=mlength)
	{
		obj.value=obj.value.substring(0,mlength-1);
	}
}

function addOverallDynamicRating(elmt) {
  if (!elmt) {
    return 0;
  }

  selectedRating = elmt.getElement('input[type=hidden]');
  if (!selectedRating) {
    return 0;
  }

  new DynamicRating(elmt.getElement('.rate'), {
    prefix: 'n',
    update: selectedRating,
    textNode: elmt.getElement('em'),
    strings: RATING_STRINGS,
    prefixes: {0: 'g'},
    attributeNode: $('attributeRatings'),
    ratingNode: $('ratingFlag'),
    ratingNodeClass: 'flagged'
  });

  return selectedRating.value;
}

function thanksSaveSelectedAjax(event) {
  if (event) new Event(event).stop();
  var form = $('UR_PROFILE');

  var uri = form.action;

  var ops = {
    data: form,
    applyBehavior: true
  }

  ops.update = $('THANK_YOU');
  ops.method = 'POST';

  new Ajax(uri, ops).request();
}

function addAttributeRatings(elmt, selectedRating) {
  if (!elmt) {
    return;
  }

  ratingSelectors = elmt.getElements('.rating');
  if (!ratingSelectors) {
    return;
  }

  ratingSelectors.each(function(item, index) {
    new DynamicRating(item.getElement('.rate'), {
      update: item.getElement('input[type=hidden]'),
      prefixes: {0: 'gs'}
    });
  });

  documentBody = $(document.body);
  if ((!selectedRating || selectedRating == 0) && !documentBody.hasClass('domn_zh_CN')) {
    elmt.hide();
  }
}


function onChangeTextArea(event,elmt,id,maxLen,truncate)
{
  var result = true;
  if (elmt.value.length >= maxLen && event.keyCode != 8 && event.keyCode != 46 && (event.keyCode < 37 || event.keyCode > 40))
  {
    elmt.value = elmt.value.substring(0,maxLen);
    result = false;
  }
  $(id).setHTML(elmt.value.length);
  return result;
}

function setSubmitAction(value,pid)
{
  $('submitAction').value=value;
  if (pid)
    $('pid').value=pid;
}


function focusReviewText(elmt) {

  elmt = $(elmt);
  if (elmt.hasClass('defaultText'))
  {
    elmt.value = '';
    elmt.style.color = '#2c2c2c';
    elmt.removeClass('defaultText');
  }
}

function toggleInlineForm(elmt) {
  var div = $('INLINE_FORM_DIV');
  var open = !div.hasClass('closed');
  div.toggleClass('closed');
  div.setStyle('display', open ? 'none' : 'block');

  var expander = $('EXPANDER');
  expander.setStyle('background-position', open ? '-146px -1560px' : '-121px -1589px');
}

function updatePhotoAjax(event) {
  if (event) new Event(event).stop(); thanksSaveSelectedAjax(event);
}

function iframeLoaded(elmt) {
  if (ta.has('inlineFormThanksFromSave')) {
    ta.remove('inlineFormThanksFromSave');
    closeLightbox();
  }
  else {
    var div = $('THANK_YOU');
    div.innerHTML = elmt.innerHTML;
    window.behavior.apply(div);
  }
}

function closeThanks() {
  closeLightbox();
}

function closeLightbox() {
  var lb = ta.retrieve('overlays.current');
  if (lb) lb.hide();
}

function fraudPeek(event) {
  $('noFraudPeek').value="1";

  // Record the peek.
  new Ajax('/ReportIAP?action=fdetails&fp=' + getFootprint()).request();

  ta.call('ta.overlays.Factory.relRight', event);
}

function submitLufthansa(event) {
  new Event(event).stop();
  new Ajax('/MemberProfileController', {
    data: [
      {
        'Action': 'LufthansaMM'
      },
      $('LUFTHANSA_FORM')
    ],
    onFailure: function(e) { alert(JS_Ajax_failed); },
    onComplete: function(txt,xml) {
      if(txt.match(/^{/)) {
        var data = eval( '(' + txt + ')' );
        if(data.ERROR) {
          ta.overlays.showInLightbox(data.ERROR);
          return;
        }
        alert(JS_Ajax_failed);
        return;
      }
      if(txt.match(/LHERROR/)) {
        $('LUFTHANSA_ERROR').setHTML(txt);
      }
      else {
        $('LUFTHANSA_CONTAINER').setHTML(txt);
      }
    }
  }).request();
}

function initSearchTypeFromHash()
{
  if (location.hash.length > 1)
  {
    var elt = $(location.hash.substr(1));
    if (elt != null && elt.name == "type")
    {
      elt.checked="checked";
      var boundfn = changeSearchType.bind(elt);
      boundfn();
    }
  }
}
