function _(key) {
  return Translations[key]
}

function ajax_error() {
  Alertbox.hide_unless_delayed()
  alert('Internal Server Error')
  if (document.getElement('div.transient')) {
    transient.hide()
  }
}

var Carrousel = new Class({
  Implements: Options, options: {
    'referer'           : document,
    'container'         : 'carrousel',
    'buttonNext'        : 'button-next',
    'buttonPrevious'    : 'button-previous',
    'addSelectors'      : true,
    'selectorClass'     : 'selector',
    'selectorId'        : 'carrousel_btn_',
    'subSelectorId'     : 'carrousel_dim_btn_',
    'selectorPosition'  : 'bottom',
    'selected'          : 'selected'
  },
  initialize: function(carrousel, options) {
    this.setOptions(options)
    this.carrousel = carrousel
    if (!this.carrousel || this.carrousel.getElements('li').length == 0) return false
    this.carrousel_window = this.carrousel.getElements('ul').getParent()[0]
    this.carrousel_items = this.carrousel.getElement('ul').getChildren('li')
    this.carrousel_length = this.carrousel_items.length
    this.carrousel_current = 0
    this.carrousel_move = this.carrousel_items[0].getSize().x
		this.subs = null;
    // Get Multidimensional lists
    this.subs = (this.carrousel_items[0].getElements('ul').length > 0)
    if(this.subs) {
      this.carrousel_sub_items   = new Array()
      this.carrousel_sub_lengths = new Array()
      this.carrousel_sub_current = new Array()
      
      this.carrousel_items.each( function(li, i) {
        this.carrousel_sub_items[i]   = li.getElements('li')
        this.carrousel_sub_lengths[i] = li.getElements('li').length
        this.carrousel_sub_current[i] = 0
      }.bind(this))
      
      this.carrousel_sub_move = this.carrousel_sub_items[0][0].getSize().y
    }

    window.addEvent('load', function() {
      this.build()
    }.bind(this))
  },
  build: function() {
    // Build selectors
    this.addSelectors(0);
 		// this.addSelectors(1); // FIXME (Didier L.)
    if(this.carrousel_length <= 1) { return }
    // Build buttons
    var that = this
    new Element('a', {
      'class': that.options.buttonPrevious
    }).addEvent('click', function(e) {
      e.stop()
      that.move(that.carrousel_current - 1)
      return false
    }).inject(this.carrousel_window, 'before')
    new Element('a', {
      'class': this.options.buttonNext
    }).addEvent('click', function(e) {
      e.stop()
      that.move(that.carrousel_current + 1)
      return false
    }).inject(this.carrousel_window, 'after')
  },
  addSelectors: function(lvl) {
    if(!lvl) { lvl = 0 }
    if(!this.options.addSelectors && 0 == lvl) { return }
    if(!this.div) { this.div = new Element('div', {'class': this.options.selectorClass+'s' }) }
    else { this.div.empty() }
    var div = this.div
    if(0 == lvl) { elements = this.carrousel_items  }
    else { elements = this.carrousel_sub_items }
    elements.each(function(e, i) {
      btn = new Element('div', {
        'class':  ((0 == lvl ? this.options.selectorId : this.options.subSelectorId)+i) + ' ' + this.options.selectorClass
      }).addEvent('click', function(e){
        if(0 == lvl) { this.move(i) }
        else { this.moveSubs(i) }
      }.bind(this)).inject(div, 'bottom')
      if(0 == lvl && this.carrousel_current == i) { btn.addClass(this.options.selected) }
      if(1 == lvl && this.carrousel_sub_current[this.carrousel_current] == i) { btn.addClass(this.options.selected) }
    }.bind(this))
    
    div.inject(this.carrousel, this.options.selectorPosition)
    if(0 == lvl) {
			width = div.getFirst().getWidth() == 0 ? 10 : div.getFirst().getWidth(); // FIXME (Didier Lafforgue): fixed bug in IE8
      var wid = this.carrousel_length * (width + div.getFirst().getStyle('margin-left').toInt() + div.getFirst().getStyle('margin-right').toInt())
    } else {
      var wid = this.carrousel_sub_lengths[this.carrousel_current] * (div.getFirst().getWidth() + div.getFirst().getStyle('margin-left').toInt() + div.getFirst().getStyle('margin-right').toInt())
    }
    div.setStyle('width', wid)
  },
  move: function (pos) {
    if (pos > this.carrousel_length-1) { pos = this.carrousel_length-1 }
    else if (pos < 0) { pos = 0 }
    if (this.carrousel_current == pos) { return }
    this.carrousel_current = pos
    this.carrousel.getElement('ul').tween('margin-left', 0-(this.carrousel_current * this.carrousel_move))

    this.carrousel.getElements('.'+this.options.selected).removeClass(this.options.selected)
    this.carrousel.getElement('.'+this.options.selectorId+pos).addClass(this.options.selected)

    if(this.subs) { this.addSelectors(1) }
  },
  moveSubs: function (pos) {
    if (pos > this.carrousel_sub_lengths[this.carrousel_current]-1) { pos = this.carrousel_sub_lengths[this.carrousel_current]-1 }
    else if (pos < 0) { pos = 0 }
    if (this.carrousel_sub_current[this.carrousel_current] == pos) { return }
    this.carrousel_sub_current[this.carrousel_current] = pos
    this.carrousel_items[this.carrousel_current].getElement('ul').tween('margin-top', (0-(pos * this.carrousel_sub_move)))
    this.carrousel.getElements('.'+this.options.selected).removeClass(this.options.selected)
    this.carrousel.getElement('#'+this.options.selectorId+pos).addClass(this.options.selected)
  }
})

function init_carrousel(root) {
  root.getElements(".carrousel").each(function(carrousel){
    new Carrousel(carrousel)
  })
}

var TabStrip = new Class({
  initialize: function(tabs, panels) {
    this.tabs = tabs
    this.panels = panels
    if(!this.tabs || !this.panels) return false
    this.current = 0
    this.build()
  },
  build: function() {
    this.panels.setStyle('display', 'none')
    this.tabs.each( function(tab, i) {
      if(tab.hasClass('current')) {
        this.current = i
        return
      }
    }.bind(this))
    this.panels[this.current].setStyle('display', 'block')
    this.tabs.each(function(tab, i) {
      if(this.panels[i]) {
        tab.addEvent('click', function() {
          this.activate(i)
        }.bind(this))
      }
    }.bind(this))
  },
  activate: function(pos) {
    if(!this.tabs[pos] || !this.panels[pos]) return
    this.current = pos
    this.tabs.removeClass('current')
    this.panels.setStyle('display', 'none')
    this.tabs[this.current].addClass('current')
    this.panels[this.current].setStyle('display', 'block')
    this.panels.fireEvent('resize')
  }
})
function init_tabstrip(referer) {
  referer.getElements('ul.tabs').each( function(ul) {
    var tabs = ul.getElements('li')
    var panels = ul.getAllNext('.panel')
    new TabStrip(tabs, panels)
  })
}

var Copier = new Class({
  Implements: Options, options: {
    'referer'     : document.body,
    'target'      : /copy-(\w.+)/,
    'targetId'    : true,
    'originals'   : 'original',
    'copies'      : 'copied',
    'removeLink'  : 'remove-copier',
    'removeInput' : 'hidden-remover',
    'iteration'   : 'iteration'
  },
  initialize: function(copier, options) {
    this.setOptions(options)
    this.copier = copier
    if(!this.copier) { return false }
    this.target_name = this.options.target.exec(copier.getProperty('class'))[1]
    this.target = this.options.referer.getElement((this.options.targetId ? '#' : '.') + this.target_name)
    if(!this.target) { return false }
    // Event : copy
    this.copier.removeEvents('click').addEvent('click', function(e) {
      e.stop()
      if('input' == this.copier.get('tag')) { this.copier.checked = false }
      this.copy()
      return false
    }.bind(this))
    // Events : remove originals
    var that = this
    this.target.getElements('.'+this.options.removeLink).each( function(link) {
      if(link.getProperty('rel') == that.target_name) {
        link.removeEvents('click').addEvent('click', function() {
          that.remove(that.target)
          return false
        })
      }
    })
    this.options.referer.getElements('.'+this.options.originals).each( function(el) {
      el.getElements('.'+that.options.removeLink).each( function(link) {
        if(link.getProperty('rel') == that.target_name) {
          link.removeEvents('click').addEvent('click', function(link) {
            that.remove(el, link)
            return false
          }.pass(link))
        }
      })
    })
  },
  copy: function(target) {
    var that = this
    if(!target) { target = this.target }
    var copies = target.getAllNext('.'+this.options.copies).extend(target.getAllNext('.'+this.options.originals))
    var lastcopy = (copies.length > 0) ? copies.getLast() : target
    var clone = target.clone(true, true)
    clone.removeProperty('id').addClass(this.options.copies).setStyle('display', 'block')
    clone.getElements('.'+this.options.copies).dispose()
    clone = this.iterate(clone, copies.length)
    clone.getElements('.'+this.options.removeLink).removeEvents('click').addEvent('click', function(clone) {
      that.remove(clone)
      return false
    }.pass(clone))
    clone.inject(lastcopy, 'after')
    target.fireEvent('resize')
    clone.ajaxize.delay(100, clone)
  },
  iterate: function(clone, count) {
    var that = this
    var target = this.target_name.slice('original_'.length).replace(/_[0-9]*$/, '')
    var new_id = new Date().getTime()
    clone.getElements('input, select, textarea').each( function(el) {
      var id = el.getProperty('id')
      var name = el.getProperty('name')
      if(id) {
        var ids = el.getProperty('id').match(eval('/(.*'+target+'_)(\\d+)(.*)/'))
        if(ids) { id = el.getProperty('id').replace(ids[1]+ids[2], ids[1]+new_id) }
      }
      if(null != name) {
        var names = el.getProperty('name').match(eval('/(.*\\['+target+'\\]\\[)(\\d+)(\\].*)/'))
        if(!names) {
          var names = el.getProperty('name').match(eval('/('+target+'\\[)(\\d+)(\\].*)/'))
        }
        if (names) {name = el.getProperty('name').replace(names[1]+names[2], names[1]+new_id)}
      }
      el.setProperties({
        'id': id,
        'name': name
      })
      el.resetElement()
    })
    clone.getElements('.copier').each( function(copier) {
      var oldTarget = this.options.target.exec(copier.getProperty('class'))[1]
      var newTarget = oldTarget.replace(/(\d+)/, new_id)
      clone.getElements('*').each(function(el) {
        if(el.getProperty('id') == oldTarget) {
          el.setProperty('id', newTarget)
        }
      })
      copier.setProperty('class', copier.getProperty('class').replace(oldTarget, newTarget))
    }.bind(this))
    
    clone.getElements('.'+this.options.iteration).each( function(el) {
      var exp = /(\d+)/
      var text = el.get('text')
      exp.exec(text).each(function(num) {
        text = text.replace(num.toInt(), num.toInt() + count)
      })
      el.set('text', text)
    })
    return clone
  },
  remove: function(target, link) {
    if(target == this.target) {
      target.getElements('.'+this.options.copies).dispose()
      target.resetElement()
    } else if(target.hasClass(this.options.copies)) {
      target.dispose()
    } else if(target.hasClass(this.options.originals)) {
      target.setStyle('display', 'none')
      var hidden_remover = link.getPrevious('.'+this.options.removeInput)
      if (!hidden_remover)
        hidden_remover = link.getNext('.'+this.options.removeInput)
      if (hidden_remover)
        hidden_remover.setProperty('value', 1)
    }
  }
})
function init_copier(referer) {
  if(!referer) { referer = document.body }
  referer.getElements('.copier').each( function(copier) {
    new Copier(copier, {'referer': referer})
  })
}

function dt_deployer(referer) {
  if(!referer) { referer = document.body }
  referer.getElements('.deployer').addEvent('click', function() {
    var dt = this.getParent('dt')
    var dd = dt.getNext('dd')
    if(this.getParent().hasClass('hide')) {
      this.getParent().removeClass('hide')
      this.getParent().addClass('show')
      dd.setStyle('display', 'block')
    } else {
      this.getParent().removeClass('show')
      this.getParent().addClass('hide')
      dd.setStyle('display', 'none')
    }
  })
}

function init_deployer(referer) {
  referer.getElements('.slider').each( function(btn) {
    btn.addEvent('click', function(e) {
      e.stop()
      var target = $(this.getProperty('rel'))
      if (target) {
        if (target.hasClass('hidden')) target.removeClass('hidden')
        else target.addClass('hidden')
      }
      return false
    })
  })
}
function wrapper(elements, size, model) {
  if(!model) { model = 'wrap-' }
  elements.each( function(el) {
    var html = el.get('html')
    el.empty()
    el.addClass(model+'0')
    var parent = el
    for(i = 1; i < size; i++) {
      parent = new Element('div', {
        'class': model+i
      }).inject(parent)
    }
    parent.appendText(html)
  })
}

function init_tooltip(referer) {
  if(!referer) { referer = document.body }
  referer.getElements('.tool-tip').each(function (tip) {
    var trig = $(tip.getProperty('rel'))
    if(trig && 'textarea' == trig.get('tag')) {
      new Tooltip(tip, trig, { on: 'focus', off: 'blur', pos: 'above'})
    } else {
      new Tooltip(tip, trig, { on: 'mouseover', off: 'mouseout', pos: 'right'})
    }
  })
}

function pop_up(options) {
  if(options.length == 0) { return }
  if(options.url != null) {
    Alertbox.hide_unless_delayed()
    transient.ajax(options.url, {
      onSuccess: ajaxize_form,
      onFailure: ajax_error,
      onException: ajax_error 
    })
  } else if(options.text != null) {
    transient.display(options.text)
  }
}

function init_fancyUpload(referer) {
  if(!referer) { referer = document.body }
  referer.getElements('ul.uploads').each( function(ul) {
    if(Browser.Plugins.Flash.version < 9) { return }
    var button = ul.getElement('.copier')
    var up_fields = ul.getElement('input[type=file]')
    if(!button && !up_fields) { return }
    button.getParent('li').setStyle('display', 'none')
    up_fields.getParent('li').setStyle('display', 'none')
    var clone = button.clone().removeClass('copier').inject(ul, 'after')
    var up = new FancyUpload3.Attach(ul, clone, {
      /* FancyUpload Showcase
       *
       * @license   MIT License
       * @author    Harald Kirschner <mail [at] digitarald [dot] de>
       * @copyright Authors
       */
      path:               '/javascripts/swiff-uploader.swf',
      method:             'POST',
      appendCookieData:   true,
      data:               { authenticity_token: document.getElement('input[name=authenticity_token]').get('value') },
      fileSizeMax:        2048 * 1024,
      typeFilter:         {'Images (*.jpg, *.jpeg, *.gif, *.png)': '*.jpg; *.jpeg; *.gif; *.png'},
      verbose:            false,
      onSelectFail: function(files) {
        files.each(function(file) {
          new Element('li', {
            'class': 'file-invalid',
            events: {
              click: function() {
                this.destroy()
              }
            }
          }).adopt(
            new Element('span', {html: file.validationErrorMessage || file.validationError})
          ).inject(this.list, 'bottom')
        }, this)
      },
      onFileSuccess: function(file) {
      //  new Element('input', {type: 'checkbox', 'checked': true, 'disabled':true}).inject(file.ui.element, 'top')
        file.ui.element.highlight('#e6efc2')
      },
      onFileError: function(file) {
        file.ui.cancel.set('html', 'Retry').removeEvents().addEvent('click', function() {
          file.requeue()
          return false
        })
        new Element('li', {
          'class': 'file-invalid'
        }).addEvent('click', function() {
          this.destroy()
        }).adopt(
          new Element('span', {html: file.errorMessage})
        ).replaces(file.ui.element)
        file.remove()
      },
      onFileRequeue: function(file) {
        file.ui.element.getElement('.file-error').destroy()
        file.ui.cancel.set('html', 'Cancel').removeEvents().addEvent('click', function() {
          file.remove()
          return false
        });
        this.start()
      }
    })
  })
}

function init_accordion(reference) {
  if (Browser.Engine.trident && Browser.Engine.version < 5)
    return(false);
  if(!reference) { reference = document.body }
  reference.getElements('ul.accordion').each( function(ul) {
    var current = ul.getElements('.togglers').indexOf(ul.getElement('.togglers.current'))
    var myAccordion = new Fx.Accordion(ul.getElements('.togglers'), ul.getElements('.accordion-element'), {
      trigger: 'click',
      display: -1,
      show: current,
      alwaysHide: true,
      initialDisplayFx: false
    })
  })
}

function ads_in_iframe(root){
  if(!Browser.Engine.gecko) return
  var ads = root.getElement('.block-advertisement .ads')
  
  if (!ads) return
  var iframe = new IFrame({
    styles: {
      width: 310,
      height: 410
    },
    'frameborder': 0,
    'scrolling': 'no'
  }).inject(ads, 'before')
  
  var _document = iframe.contentWindow.document
  _document.open()
  _document.write("<style type=\"text/css\">\n<!--\n body { text-align:center; }\n-->\n</style>");
  _document.write(ads.get('html'))
  _document.close()
  ads.destroy()
}

function init_enum_deployer(referer) {
  referer.getElements('a.deployer-enum').each( function(link) {
    link.removeEvents().addEvent('click', function(e) {
      e.stop()
      var id = this.getProperty('id')
      var preview = this.getParent('div')
      preview.addClass('hidden')
      var div = $(preview.getNext('div'))
      div.removeClass('hidden')
      var p = div.getElement('p') ? div.getElement('p') : div
      if (!p.getElement('a')) {
        a = new Element('a', {
          'id' : 'hide-' + id,
          'class': 'deploy',
          'href' : '#',
          'text' : link.getProperty('rel')
        })
        a.addEvent('click', function(e) {
          e.stop()
          link.getParent('div').removeClass('hidden')
          this.getParent('div').addClass('hidden')
          return false
        }).inject(p)
        return false
      }
    })
  })
}
Element.implement({
  ajaxize: function() {
    if(typeof(Calendar) == 'function') {
      this.getElements('.calendar-area').each( function(cal) {
        var calendar = new Calendar(cal)
      })
    }
    init_carrousel(this)
    init_accordion(this)
    init_payment_choices()
    init_tabstrip(this)
    if(typeof(FancyUpload3) != 'undefined') {
      init_fancyUpload(this)
    }
    init_copier(this)
    init_tooltip(this)
    dt_deployer(this)
    init_deployer(this)
    ajaxize_form(this)
    init_fancy_search()
    init_booking_pricings()
    init_input_focus(this)
    init_contact_form(this)
    init_home_search(this)
    admin_edit_balance(this)
    init_enum_deployer(this)
    
    this.getElements('a.ajax-put').removeEvents('click').addEvent('click', function(e) {
      e.stop()
      var u = this.get('href').split('?')
      new Request({
        url: u[0],
        method: 'PUT',
        evalResponse: true,
        onFailure: ajax_error,
        onException: ajax_error
      }).send(u[1])
      return false
    })
    
    this.getElements('a.transient').removeEvents('click').addEvent('click', function(e) {
      e.stop()
      transient.ajax(this.href, {
        onFailure: ajax_error,
        onException: ajax_error 
      })
      return false
    })
  },
  
  shake: function(amount) {
    if (!amount) amount = 50
    var orig = this.getLeft()
    new Fx.Tween(this, {
        property: 'left',
      transition: Fx.Transitions.Elastic.easeOut
    }).start(orig+amount, orig)
  } 
})


// ============================================================================
// Language methods

function domainLanguage () {
  if (document.domain.match('.fr')) {
    return 'fr';
  } else if (document.domain.match('.es')) {
    return 'es';
  } else {
    return 'en';
  }
}

function browserLanguage() {
  // detect the browser language, keep the first 2 chars only
  var lang = (navigator.language) ? navigator.language : navigator.userLanguage; 
  lang = lang.substring(0,2);
  
  // if the lang is neither fr nor es, default to en
  if (lang != 'fr' && lang != 'es') { lang = 'en'; }
  return lang;
}

function promptForLanguage () {
  // returns false if the hide_language_switch cookie is set, returns true otherwise
  return (document.cookie.length > 0 && document.cookie.indexOf('hide_language_switch' + "=") !=- 1) ? false : true;
}

function preventLanguagePrompt () {
  var expiry_date = new Date();
  expiry_date.setDate(expiry_date.getDate() + 7); // expire in 7 days
  document.cookie = 'hide_language_switch=1;expires=' + expiry_date.toUTCString();
}

function showLanguagePrompt (lang) {
  var div = $('language_prompt').getElement('.' + lang);
  
  var close_button = new Element('a', {
    'class':'close',
    'html':'[x]',
    'href':'#'
  }).addEvent('click', function(e) {
    $('language_prompt').slide();
    preventLanguagePrompt();
    return false
  })
  
  div.grab(close_button);
  div.show();
}

function checkLanguage () {
  // stop here if the user has already dismissed a language prompt
  if (promptForLanguage()) {
    
    // show the appropriate language text if the browser language and the site language don't match
    if (browserLanguage() != domainLanguage()) {
      showLanguagePrompt(browserLanguage());
    }
  }
}

// ============================================================================
// http://blog.stchur.com/2007/04/06/serializing-objects-in-javascript/
function serialize(_obj) {
   // if (typeof _obj.toSource !== 'undefined' && typeof _obj.callee === 'undefined') { return _obj.toSource(); }
   switch (typeof _obj) {
      case 'number':
      case 'boolean':
      case 'function':
				return _obj;
				break;
      case 'string':
				return '"' + _obj + '"';
				break;
      case 'object':
				var str;
	        if (_obj.constructor === Array || typeof _obj.callee !== 'undefined') {
	           str = '[';
	           var i, len = _obj.length;
	           for (i = 0; i < len-1; i++) { str += serialize(_obj[i]) + ','; }
	           str += serialize(_obj[i]) + ']';
					} else {
						str = '{';
						var key;
						for (key in _obj) { str += '"' + key + '" :' + serialize(_obj[key]) + ','; }
						str = str.replace(/\,$/, '') + '}';
	        }
	        return str;
	        break;
      default:
         return 'UNKNOWN';
         break;
   }
}

var transient

var geocoder = null;
var foo = null;

window.addEvent('domready', function() {
  // Google Analytics
  if (typeof(_gat) != 'undefined') {
    $try(function() { _gat._getTracker('UA-1991319-1')._trackPageview() })
  }

  transient = new Transient
  Alertbox.inject(document.body)
  Ajaxloader.inject(document.body) 

  window._alert = window.alert
  window.alert = function(message) { Alertbox.display(message) }
  
  var notice = document.getElement('.flash')
  if(notice && notice.hasClass('pop_up')) {
    var options = notice.getElement('.option')
    if('text' == options.getProperty('id')) {
      pop_up({'text': options.get('html')})
    } else if('url' == options.getProperty('id')) {
      pop_up({'url': options.get('html')})
    }
    notice.dispose()
  } else if(notice) {
    alert(notice.get('text'), 4000)
    notice.dispose()
  }
  
  $(document.body).ajaxize()
  wrapper(document.getElements('h3'), 3, 'wrap-h3-')

  // sort box for accommodations page
  if($('order') && $('order_submit')) {
    $('order_submit').hide();
    $('order').addEvent('change', function(){ this.form.submit(); });
  }
  
  checkLanguage();
})