var tipo_trayecto;
var OfferHappy = function() {

  var pad2 = function(n) {
    var s = '' + n;
    return '00'.slice(s.length) + s;
  };

  var dateToStr = function(date) {
    var m = (date.getMonth() + 1);
    var d = date.getDate();
    m = pad2(m);
    d = pad2(d);
    return '' + date.getFullYear() + m + d; 
  };

  var strToDate = function(date) {
    return new Date(date.substr(0, 4), (+date.substr(4, 2) - 1), date.substr(6, 2));
  };
  
  var collectKeys = function(obj) {
    var ret = [];
    for (var i in obj) ret.push(i);
    return ret;
  };
  
  var ce = function(name, attrs) {
    var el = document.createElement(name), a;
    if (attrs) {
      for (a in attrs) {
        el[a] = attrs[a];
      }
    }
    return el;
  };

  var createRadio = function() {
    if (document.attachEvent && !window.opera) { // explorer
      return function(attrs) {
        var a, el = document.createElement('<input type="radio" name="' + attrs.name + '">');
        for (a in attrs) {
          el[a] = attrs[a];
        }
        return el;
      };
    }
    else {
      return function(attrs) {
        attrs.type = 'radio';
        return ce('input', attrs);
      };
    }
  }();
  
  var text = function(content) {
    return document.createTextNode(content);
  };

  var clone = function(base) {
    return base.cloneNode(true);
  };

  var inArray = function(needle, haystack) {
    for (var i = 0; i < haystack.length; i += 1) 
      if (haystack[i] === needle) return true;
    return false;
  };
  
  var map = function(a, fn) {
    var ret = [], i;
    for (i = 0; i < a.length; i += 1) {
      ret.push(fn(a[i], i));
    }
    return ret;
  };

  var merge = function(base, extend) {
    for (var p in extend)
      if (extend.hasOwnProperty(p)) {
        if (extend[p] && extend[p].constructor == Object) {
          base[p] = base[p] || {};
          merge(base[p], extend[p]);
        }
        else {
          base[p] = extend[p];
        }
      }
    return base;
  };
  
  var byClass = function(className, name, parent) {
    var ret = [], col;
    parent = parent || document;
    name = name || '*';
    col = parent.getElementsByTagName(name);
    for (var i = 0; i < col.length; i += 1) {
      if (inArray(className, col[i].className.split(/\s+/))) {
        ret.push(col[i]);
      }
    }
    return ret;
  };
  
  var setSelected = function(selected, container) {
    var cur = byClass('selected', 'td', container)[0];
    if (cur) cur.className = cur.className.replace(/(^|\s+)selected(\s+|$)/, '');
    selected.className += ' selected';
  };

  var rangeMonths = function(strInit, strEnd) {
    var months = [], i,
    firstYear = (+strInit.slice(0,4)),
    lastYear = (+strEnd.slice(0,4)),
    endMonth = (+strEnd.slice(-2)),
    endMonthFirstYear = lastYear > firstYear ? 12 : endMonth;
    // each month has a value and a month number
    for (i = (+strInit.slice(-2)); i <= endMonthFirstYear; i += 1) {
      months.push(['' + firstYear + pad2(i), i]);
    }
    if (lastYear > firstYear) {
      for (i = 1; i <= endMonth; i += 1) {
        months.push(['' + lastYear + pad2(i), i]);
      }
    }
    return months;
  };
  
  var objectToForm = function(conf) {
    var p, field, form = DomHelper.find('oh-send-form'), fragment;
    // borramos el form si existe
    if (form.element) form.element.parentNode.removeChild(form.element);
    // creamos un nuevo formulario
    form = ce('form', { method: 'post', id: 'oh-send-form' });
    fragment = document.createDocumentFragment();
    for (p in conf) {
      field = ce('input', { type: 'hidden', name: p, value: conf[p] });
      fragment.appendChild(field);
    }
    form.appendChild(fragment);
    return form;
  };

  var OH = function(opts) {
    opts = opts || {};
    this.config = {
      minAdults : 1,
      maxAdults : 8,
      minChildren : 0,
      maxChildren : 8,
      minBabies : 0,
      maxBabies : 8,
      roundTrip : 'both', // both | oneway | returntrip
      firstDayOfWeek: 1, // lunes
      locale : {
        legendTripType: '¿Qué tipo de trayecto quieres hacer?',
        labelRoundTrip : 'Ida y vuelta',
        labelOneWay    : 'Ida',
        legendDeparture : '¿A dónde y qué día quieres ir? (haz clic en el día del calendario que te interesa)',
        labelOrigin : 'Origen',
        labelDestination : 'Destino',
        labelMonth : 'Mes',
        labelSelectMonth : 'Escoge un mes',
        legendDestination : '¿Qué día quieres volver? (haz clic en el día del calendario que te interesa)',
        labelDeparture: 'Ida',
        labelReturn : 'Vuelta',
        labelTotal : 'Importe total',
        labelButton : 'Comprar',
        legendTravellers : '¿Cuántos pasajeros viajáis?',
        labelAdults : 'Adultos',
        optionAdults : 'adultos',
        optionAdults1 : 'adulto',
        labelChildren : 'Niños',
        optionChildren : 'niños',
        optionChildren1 : 'niño',
        labelBabies : 'Bebés',
        optionBabies : 'bebés',
        optionBabies1 : 'bebé',
        // leyenda
        labelShowLegend : 'Mostrar leyenda',
        legendTitle : 'Leyenda',
        labelClose: 'Cerrar',
        legendPromo : 'Fecha en promoción',
        legendNoPromo : 'Fecha no promocional',
        legendDated : 'Fecha no seleccionable',
        currency: '€',
        dateNoOffer : 'fecha no promocional',
        alertMaxBabies : 'Has introducido un número de pasajeros que no es válido.\nSi quieres reservar un número mayor de bebés que de adultos, ponte en contacto con nuestra Central de Reservas Vueling en el 902 33 39 33.',
        // aeropuertos
        ALC : 'Alicante',
        AMS : 'Amsterdam',
        BCN : 'Barcelona',
        BIO : 'Bilbao',
        BLQ : 'Bolonia',
        BRU : 'Bruselas',
        GRX : 'Granada',
        IBZ : 'Ibiza',
        XRY : 'Jerez',
        LIS : 'Lisboa',
        MAD : 'Madrid',
        AGP : 'Málaga',
        MAH : 'Menorca',
        MXP : 'Milán',
        PMI : 'Palma de Mallorca',
        PAR : 'París',
        FCO : 'Roma',
        SCQ : 'Santiago',
        SVQ : 'Sevilla',
        VCE : 'Venecia',
        NAP : 'Nápoles',
        PSA : 'Pisa',
        ATH : 'Atenas',
        NCE : 'Niza',
        VLC : 'Valencia',
        MLA : 'Malta',
        TCI : 'Tenerife',
        LPA : 'Gran Canaria',
		ILD : 'Lleida',
		ZRH : 'Zurich',
        monthNames : 'Enero,Febrero,Marzo,Abril,Mayo,Junio,Julio,Agosto,Septiembre,Octubre,Noviembre'.split(','),
        weekDayNamesShort : 'DLMMJVSD'.split(''), // de domingo a domingo
        weekDayNames : 'Domingo,Lunes,Martes,Miércoles,Jueves,Viernes,Sábado,Domingo'.split(',') // de domingo a domingo
      }
    };
    merge(this.config, opts);
    this.offers = {};
    this.attributes = {};
  };

  OH.prototype = {

    run: function() {
      this.renderView();
      this.fillSelectOrigin();
      this.initAttributes();
      this.initBindings();
      return this;
    },

    renderView: function() {
      var find = DomHelper.find, locale = this.config.locale,
      fs, leg, ul, li, lab, input, foo, i, id, cont, div, sel, opt, firstDate;
      // ida / ida y vuelta
      fs = find('oh-fs-roundtrip').element;
      leg = ce('h3');
      leg.appendChild(text(locale.legendTripType));
      fs.appendChild(leg);
      ul = ce('ul');
      ul.className = 'inline';
      foo = ['roundtrip', locale.labelRoundTrip, 'oneway', locale.labelOneWay];
      for (i = 0; i < foo.length; i += 2) {
        li = ce('li');
        id = 'oh-' + foo[i];
        input = createRadio({ type: 'radio', name: 'oh-mode', id: id, value: foo[i] });
        lab = ce('label', { htmlFor: id });
        lab.appendChild(input);
        lab.appendChild(text(foo[i+1]));
        li.appendChild(lab);
        ul.appendChild(li);
      }
      fs.appendChild(ul);
      // tenemos que setear la marca aqui para evitar un bug de explorer
      // al desplazar radios por el dom
      find('oh-roundtrip').element.checked = true;
      // seleccion origen
      fs = find('oh-fs-departure').element;
      leg = ce('h3');
      leg.appendChild(text(locale.legendDeparture));
      fs.insertBefore(leg, fs.firstChild);
      cont = byClass('col-1', 'div', fs)[0];
      foo = [ 'origin', locale.labelOrigin, locale.labelOrigin, false, 'destination', locale.labelDestination, locale.labelDestination, true, 'month-departure', locale.labelMonth, locale.labelSelectMonth, true ];
      for (i = 0; i < foo.length; i += 4) {
        id = 'oh-' + foo[i];
        div = ce('div', {className: 'form-item'});
        lab = ce('label', { htmlFor: id });
        lab.appendChild(text(foo[i + 1]));
        div.appendChild(lab);
        sel = ce('select', { id: id, name: id });
        div.appendChild(sel);
        opt = ce('option');
        opt.appendChild(text(foo[i + 2]));
        opt.setAttribute('value', '');
        sel.appendChild(opt);
        cont.appendChild(div);
        if (foo[i + 3]) {
          sel.disabled = true;
        }
      }
      // trigger leyenda
      div = ce('a', { href: '#', id: 'oh-legend-trigger-1', className: 'legend-trigger' });
      div.appendChild(text('» ' + locale.labelShowLegend));
      cont.appendChild(div);
      // calendario origen
      cont = ce('div', { id: 'oh-departure-calendar', className: 'calendar' });
      byClass('col-2', 'div', fs)[0].appendChild(cont);
      firstDate = strToDate('' + Math.max(this.getFirstDate(), dateToStr(new Date())));
      this.renderCalendar(cont, firstDate.getFullYear(), firstDate.getMonth() + 1, function(cell) {
        cell.className += ' disabled';
      });
      // retorno
      fs = find('oh-fs-return').hide().element;
      leg = ce('h3');
      leg.appendChild(text(locale.legendDestination));
      fs.insertBefore(leg, fs.firstChild);
      cont = byClass('col-1', 'div', fs)[0];
      div = ce('div', { className : 'form-item' });
      div.appendChild(text(locale.labelOrigin));
      div.appendChild(ce('div', { id: 'oh-route-departure', className: 'route' }));
      cont.appendChild(div);
      div = ce('div', { className : 'form-item' });
      div.appendChild(text(locale.labelDestination));
      div.appendChild(ce('div', { id: 'oh-route-return', className: 'route' }));
      cont.appendChild(div);
      id = 'oh-' + 'month-return';
      div = ce('div', {className: 'form-item'});
      lab = ce('label', { htmlFor: id });
      lab.appendChild(text(locale.labelMonth));
      div.appendChild(lab);
      sel = ce('select', { id: id, name: id });
      div.appendChild(sel);
      opt = ce('option');
      opt.appendChild(text(locale.labelMonth));
      sel.appendChild(opt);
      cont.appendChild(div);
      // segundo trigger de leyenda
      div = ce('a', { href: '#', id: 'oh-legend-trigger-2', className: 'legend-trigger' });
      div.appendChild(text('» ' + locale.labelShowLegend));
      cont.appendChild(div);
		
      // calendario destino (solo el placeholder)
      div = ce('div', { id: 'oh-return-calendar', className: 'calendar' });
      byClass('col-2', 'div', fs)[0].appendChild(div);
      // info
      foo = [ 'departure', locale.labelDeparture, 'return', locale.labelReturn ];
      for (i = 0; i < foo.length; i += 2) {
        cont = find('oh-info-' + foo[i]).hide().element;
        lab = ce('strong');
        lab.appendChild(text(foo[i + 1]));
        cont.appendChild(lab);
        div = ce('div', {className: 'col-1'});
        cont.appendChild(div);
        div.appendChild(ce('span', { id: 'oh-info-' + foo[i] + '-route' }));
        div.appendChild(ce('span', { id: 'oh-info-' + foo[i] + '-date' }));
        div = ce('div', {className: 'col-2'});
        cont.appendChild(div);
        div.appendChild(ce('span', { id: 'oh-info-' + foo[i] + '-price', className: 'price' }));
      }
      // importe total
      cont = find('oh-total').hide().element;
      lab = ce('strong');
      lab.appendChild(text(locale.labelTotal));
      cont.appendChild(lab);
      div = ce('span', { id: 'oh-total-price' });
      cont.appendChild(div);
      // seccion numero de pasajeros
      cont = find('oh-fs-travellers').hide().element;
      leg = ce('h3');
      leg.appendChild(text(locale.legendTravellers));
      cont.appendChild(leg);
      foo = [
        'adults', locale.labelAdults, locale.optionAdults, locale.optionAdults1,
        'children', locale.labelChildren, locale.optionChildren, locale.optionChildren1,
        'babies', locale.labelBabies, locale.optionBabies, locale.optionBabies1
      ];
      for (i = 0; i < foo.length; i += 4) {
        id = 'oh-' + foo[i];
        div = ce('div', { className : 'form-item' });
        lab = ce('label', { htmlFor: id, className: 'h' });
        lab.appendChild(text(foo[i+1]));
        div.appendChild(lab);
        sel = ce('select', { id : id, name : id });
        input = foo[i].substr(0,1).toUpperCase() + foo[i].substr(1);
        fs = document.createDocumentFragment();
        for (j = this.config['min' + input]; j <= this.config['max' + input]; j += 1) {
          opt = ce('option');
          opt.setAttribute('value', j);
          opt.appendChild(text(j + ' ' + (j == 1 ? foo[i + 3] : foo[i + 2])));
          fs.appendChild(opt);
        }
        sel.appendChild(fs);
        div.appendChild(sel);
        cont.appendChild(div);
      }
      
      
      // boton
      cont = find('oh-button').hide().element;
      ul = ce('a', { href: '#' });
      li = ce('span');
      li.appendChild(text(locale.labelButton));
      ul.appendChild(li);
      cont.appendChild(ul);
      
      // leyenda
      cont = ce('div', { id: 'oh-legend' });
      if (document.attachEvent && !window.opera) {
        div = ce('iframe');
        cont.appendChild(div);
      }
      div = ce('a', { id : 'oh-legend-close', href: '#' });
      div.appendChild(text(locale.labelClose));
      cont.appendChild(div);
      div = ce('div', { className : 'legend-title' });
      div.appendChild(text(locale.legendTitle));
      cont.appendChild(div);
      ul = ce('ul');
      li = ce('li', { className : 'no-promo' });
      li.appendChild(text(locale.legendNoPromo));
      ul.appendChild(li);
      li = ce('li', { className : 'promo' });
      li.appendChild(text(locale.legendPromo));
      ul.appendChild(li);
      li = ce('li', { className : 'dated' });
      li.appendChild(text(locale.legendDated));
      ul.appendChild(li);
      cont.appendChild(ul);
      find('oh-app').element.appendChild(cont);
      return this;
    },

    fillSelectOrigin : function() {
      var sel = DomHelper.find('oh-origin').element;
      var locale = this.config.locale;
      var origins = map(this.getOrigins(), function(shortName) {
        return [ shortName, locale[shortName] + ' (' + shortName + ')'];
      })
      .sort(function(a, b) {
        return a[1].localeCompare(b[1]);
      });
      this.fillSelect(sel, origins);
      return this;
    },
    
    fillSelect : function(sel, options, emptyFirst) {
      var opt, fragment = document.createDocumentFragment();
      if (emptyFirst) {
        while (sel.firstChild) sel.removeChild(sel.firstChild);
      }
      for (var i = 0; i < options.length; i += 1) {
        opt = ce('option');
        opt.setAttribute('value', options[i][0]);
        if (options[i][2]) opt.setAttribute('selected', 'selected');
        opt.appendChild(text(options[i][1]));
        fragment.appendChild(opt);
      }
      sel.appendChild(fragment);
      return this;
    },

    initAttributes : function() {
      var find = DomHelper.find, host = this; // used on attribute callbacks
      this
        .initAttribute('travelType', function(value) {
          var depDate = this.getAttribute('departureDate');
          if (value == 'oneway') {
            find('oh-fs-return').hide();
            find('oh-info-return').hide();
            if (depDate !== undefined) {
              this.updateAttribute('departurePrice', this.getAttribute('departurePrice'));
            }
          }
          else {
            if (depDate !== undefined) {
              this.updateAttribute('departureDate', depDate);
              find('oh-total').hide();
            }
          }
        })
        .initAttribute('origin', function(value) {
          var originSelect, locale = this.config.locale;
          var destinations = map(this.getDestinations(value), function(shortName) {
              return [ shortName, locale[shortName] + ' (' + shortName + ')'];
            })
            .sort(function(a, b) {
              return a[1].localeCompare(b[1]);
            });
          originSelect = find('oh-origin').element;
          if (originSelect.options[0].value == '') {
            originSelect.removeChild(originSelect.options[0]);
          }
          destinations.unshift(['', locale.labelDestination]);
          this.fillSelect(find('oh-destination').enable().element, destinations, true);
        })
        .initAttribute('destination', function(value) {
          var locale = this.config.locale, firstMonth, lastMonth, route, opts = [], i, humanRoute, departureMonth, selected, destSelect, months;
          route = this.offers[this.getAttribute('origin') + value];
          firstMonth = ('' + Math.max(route.getFirstDate(), dateToStr(new Date()))).substr(0,6);
          lastMonth = route.getLastDate().substr(0,6);
          months = rangeMonths(firstMonth, lastMonth);
          departureMonth = this.getAttribute('departureMonth') || firstMonth;
          for (i = 0; i < months.length; i += 1) {
            selected = departureMonth == months[i][0];
            opts.push([months[i][0], locale.monthNames[months[i][1] -1], selected]);
          }
          destSelect = find('oh-destination').element;
          if (destSelect.options[0].value == '') {
            destSelect.removeChild(destSelect.options[0]);
          }
          this.fillSelect(find('oh-month-departure').enable().element, opts, true);
          humanRoute = this.humanReadableRoute(this.getAttribute('origin'), this.getAttribute('destination'));
          find('oh-route-departure').html(humanRoute);
          find('oh-info-departure-route').html(humanRoute);
          humanRoute = this.humanReadableRoute(this.getAttribute('destination'), this.getAttribute('origin'));
          find('oh-route-return').html(humanRoute);
          find('oh-info-return-route').html(humanRoute);
          if (departureMonth) {
            this.updateAttribute('departureMonth', departureMonth);
          }
        })
        .initAttribute('departureMonth', function(value) {
          var locale = this.config.locale, year, month;
          year = (+value.slice(0, 4));
          month = (+value.slice(-2));
          this.renderCalendar(find('oh-departure-calendar').element, year, month, function(cell, date) {
            date = dateToStr(date);
            var today = dateToStr(new Date());
            var price = host.getPrice(host.getAttribute('origin'), host.getAttribute('destination'), date);
            cell._price = price || 0;
            cell._date = date;
            if (today > date) {
              cell.className += ' disabled';
              if (price) cell.className += ' special-disabled';
            }
            else {
              if (price) {
                cell.className += ' special';
                cell.title = host.humanReadableDate(date) + ' (' + price + ' ' + host.config.locale.currency + ')';
              }
              cell.tabIndex = 0;
            }
          });
          find('oh-fs-return').hide();
          find('oh-info-return').hide();
          find('oh-info-departure').hide();
          find('oh-fs-travellers').hide();
          find('oh-button').hide();
          find('oh-total').hide();
        })
        .initAttribute('departureDate', function(value) {
          var locale = this.config.locale, route, firstMonth, lastMonth, opts = [], i, travelType, months;
          find('oh-info-departure-date').html(host.humanReadableDate(value));
			document.getElementById('displayDate11').value = host.humanReadableDate(value);
          find('oh-info-departure').show();
          travelType = this.getAttribute('travelType');
          if (travelType == 'oneway') {
			  tipo_trayecto="ida";
            find('oh-fs-travellers').show();
            find('oh-button').show();
            document.location.hash = 'oh-info-departure';
          }
          else {
			  tipo_trayecto="vuelta";
            route = this.offers[this.getAttribute('origin') + this.getAttribute('destination')];
            firstMonth = '' + Math.max(value.substr(0, 6), route.getFirstDate().substr(0, 6));
            lastMonth = route.getLastDate().substr(0, 6);
            months = rangeMonths(firstMonth, lastMonth);
            for (i = 0; i < months.length; i += 1) {
              opts.push([months[i][0], locale.monthNames[months[i][1] -1], false]);
            }
            this.fillSelect(find('oh-month-return').element, opts, true);
            this.updateAttribute('returnMonth', months[0][0]);
            find('oh-fs-return').show();
            find('oh-info-return').hide();
            find('oh-fs-travellers').hide();
            find('oh-button').hide();
            document.location.hash = 'oh-fs-return';
          }
        })
        .initAttribute('departurePrice', function(value) {
          var total, el = find('oh-info-departure-price').element;
          find('oh-total').hide();
          if (value) {
            total = '' + value + ' ' + this.config.locale.currency;
            find('oh-total-price').html(total);
            find('oh-total').show();
            el.className = '';
          }
          else {
            el.className = 'no-offer';
            total = this.config.locale.dateNoOffer;
          }
          find('oh-info-departure-price').html(total);
        })
        .initAttribute('returnMonth', function(value) {
          var year = value.slice(0,4),
          month = (+value.slice(-2));
          this.renderCalendar(find('oh-return-calendar').element, year, month, function(cell, date) {
            date = dateToStr(date);
            var price = host.getPrice(host.getAttribute('destination'), host.getAttribute('origin'), date);
            if (date >= host.getAttribute('departureDate')) {
              cell._price = price || 0;
              cell._date = date;
              if (price) {
                cell.className += ' special';
                cell.title = host.humanReadableDate(date) + ' (' + price + ' ' + host.config.locale.currency + ')';
              }
              cell.tabIndex = 0;
            }
            else {
              if (price) cell.className += ' special-disabled';
              cell.className += ' disabled';
            }
          });
        })
        .initAttribute('returnDate', function(value) {
          find('oh-info-return-date').html(host.humanReadableDate(value));
		  document.getElementById('displayDate22').value = host.humanReadableDate(value);
          find('oh-info-return').show();
        })
        .initAttribute('returnPrice', function(value) {
          find('oh-total').hide();
          var euros = this.config.locale.currency, partial, el = find('oh-info-return-price').element;
          if (value) {
            el.className = '';
            partial = '' + value + ' ' + euros;
          }
          else {
            el.className = 'no-offer';
            partial = this.config.locale.dateNoOffer;
          }
          find('oh-info-return-price').html(partial);
          var total, p1, p2;
          if ((p1 = this.getAttribute('departurePrice')) && (p2 = this.getAttribute('returnPrice'))) {
            total = p1 + p2 + ' ' + euros;
            find('oh-total-price').html(total);
            find('oh-total').show();
          }
          find('oh-button').show();
          find('oh-fs-travellers').show();
          document.location.hash = 'oh-fs-travellers';
        })
        .initAttribute('adults')
        .updateAttribute('adults', host.config.minAdults)
        .initAttribute('children')
        .updateAttribute('children', host.config.minChildren)
        .initAttribute('babies')
        .updateAttribute('babies', host.config.minBabies);
    },
    
    initBindings : function() {
      var host = this, find = DomHelper.find;
      function handleRadios() {
        host.updateAttribute('travelType', this.value);
      }
      function showLegend() {
        var l = 0, t = 0, legend = find('oh-legend'), p = this, style = legend.element.style;
        var appDiv = find('oh-app').element;
        while (p != appDiv) {
          l += p.offsetLeft;
          t += p.offsetTop;
          p = p.offsetParent;
        }
        style.top = (t - 128) + 'px'; // ajuste bocadillo
        style.left = (l - 228) + 'px';
        legend.show();
        this.blur();
        return false;
      }
      function assignCalendarHandlers(calendar) {
        var el = find('oh-'+calendar+'-calendar').element;
        var handler = function(e) {
          e = e || window.event;
          var target = e.target || e.srcElement;
          if (target.tagName == 'TD' && target.className.search(/(^|\s+)disabled(\s+|$)/) == -1) {
            if (e.type == 'keypress' && e.keyCode != 13) return;
            setSelected(target, this);
            host.updateAttribute(calendar+'Date', target._date);
            host.updateAttribute(calendar+'Price', target._price ? (+target._price) : 0);
          }
        };
        el.onclick = handler;
        el.onkeypress = handler;
        el = null; // evita leak
      };
      find('oh-oneway').element.onclick = handleRadios;
      find('oh-roundtrip').element.onclick = handleRadios;
      find('oh-origin').element.onchange = function() {
        host.updateAttribute('origin', new DomHelper(this).value());
      };
      find('oh-destination').element.onchange = function() {
        host.updateAttribute('destination', new DomHelper(this).value());
      };
      find('oh-month-departure').element.onchange = function() {
        host.updateAttribute('departureMonth', new DomHelper(this).value());
      };
      find('oh-month-return').element.onchange = function() {
        host.updateAttribute('returnMonth', new DomHelper(this).value());
      };
      // TODO handle keyboard enter
      assignCalendarHandlers('departure');
      assignCalendarHandlers('return');
      find('oh-adults').element.onchange = function() {
        host.updateAttribute('adults', new DomHelper(this).value());
      };
      find('oh-children').element.onchange = function() {
        host.updateAttribute('children', new DomHelper(this).value());
      };
      find('oh-babies').element.onchange = function() {
        host.updateAttribute('babies', new DomHelper(this).value());
      };
      find('oh-button').element.onclick = function() {
        var url;
		
		  if(tipo_trayecto == "ida"){
		  //alert("Ruta: "+host.getAttribute('origin')+"-"+host.getAttribute('destination'));
		  vuelingTracker._trackEvent('Offer Happy','Ruta',host.getAttribute('origin')+'-'+host.getAttribute('destination'));
			  }
		  else{
			vuelingTracker._trackEvent('Offer Happy','Ruta',host.getAttribute('origin')+'-'+host.getAttribute('destination')+'-'+host.getAttribute('origin'));
		  //alert("Ruta: "+host.getAttribute('origin')+"-"+host.getAttribute('destination')+"-"+host.getAttribute('origin'));
		  }
		
        if (+host.getAttribute('babies') > +host.getAttribute('adults')) {
          alert(host.config.locale.alertMaxBabies);
          return false;
        }
        host.sendData();
        return false;
      };
      find('oh-legend-trigger-1').element.onclick = showLegend;
      find('oh-legend-trigger-2').element.onclick = showLegend;
      find('oh-legend-close').element.onclick = function() {
        find('oh-legend').hide();
        return false;
      };
      return this;
    },
    
    initAttribute : function(name, callback) {
      this.attributes[name] = { value: undefined, callback: callback };
      return this;
    },
    
    updateAttribute : function(name, value) {
      var attr = this.attributes[name];
      attr.value = value;
      if (attr.callback) {
        attr.callback.call(this, value);
      }
      return this;
    },
    
    getAttribute : function(name) {
      return this.attributes[name].value;
    },

    renderCalendar: function(cont, year, month, cb) {
      while(cont.firstChild) {
        cont.removeChild(cont.firstChild); 
      }
      var h = ce('h4');
      h.appendChild(text(this.config.locale.monthNames[month - 1]));
      cont.appendChild(h);
      var cal = new OH.CalendarMonth(year, month, { cellCallback: cb, prevMonth: false, nextMonth: false, weekDayNames: this.config.locale.weekDayNamesShort });
      cont.appendChild(cal.toHtml());
      return this;
    },

    humanReadableRoute : function(origin, destination) {
      var locale = this.config.locale;
      return locale[origin] + ' (' + origin + ') - ' + locale[destination] + ' (' + destination + ')';
    },
    
    humanReadableDate : function(date) {
      var locale = this.config.locale;
      date = strToDate(date);
      return locale.weekDayNames[date.getDay()] + ' '  + date.getDate() + ' ' + locale.monthNames[date.getMonth()] + ', ' + date.getFullYear(); 
    },

    addOffer : function(offer) {
      this.offers[offer.route] = offer;
      return this;
    },
    
    getOrigins : function() {
      var ret = [], item;
      for (var r in this.offers) {
        item = this.offers[r].origin;
        if (!inArray(item, ret)) {
          ret.push(this.offers[r].origin);
        }
      }
      return ret;
    },
    
    getDestinations : function(from) {
      var ret = [], offer;
      for (var r in this.offers) {
        offer = this.offers[r];
        if (offer.origin == from) {
          ret.push(offer.destination);
        }
      }
      return ret;
    },
    
    getPrice : function(origin, destination, date) {
      return this.offers[origin + destination].getPrice(date);
    },
    
    getCompany : function(origin, destination) {
      return this.offers[origin + destination].getCompany();
    },
    
    getFirstDate : function() {
      var col = [];
      for (var i in this.offers) {
        col.push(this.offers[i].getFirstDate());
      }
      return '' + Math.min.apply(null, col);
    },
    
    sendHandler : function(fn) {
      this.sendCallback = fn;
      return this;
    },
    
    sendData : function() {
      var origin = this.getAttribute('origin');
      var destination = this.getAttribute('destination');
      var travelType = this.getAttribute('travelType') == 'oneway' ? 1 : 2;
      var departDate1 = this.getAttribute('departureDate');
      var departDate2 = this.getAttribute('returnDate');
	  var displayDate1 = document.getElementById('displayDate11').value;
      var displayDate2 = document.getElementById('displayDate22').value;
      var company = this.getCompany(origin, destination);
      var conf = {
        from1 : origin,
        to1 : destination,
        from2: travelType == 2 ? destination : '',
        to2 : travelType == 2 ? origin : '',
        adults : this.getAttribute('adults'),
        children : this.getAttribute('children'),
        infants : this.getAttribute('babies'),
        departDate1 : departDate1,
        departDate2 : travelType == 2 ? this.getAttribute('returnDate') : '',
		displayDate1 : displayDate1,
        displayDate2 : displayDate2,
        travelType : travelType,
        language : jidioma,
        company : company
      };
      return this.sendCallback(conf);
    }
  };


  OH.Offer = function(route, company) {
    this.route = route;
    this.origin = route.substr(0,3);
    this.destination = route.substr(3);
    this.prices = {};
    this.company = company || 'vueling';
  };

  OH.Offer.prototype = {

    setPrice : function(date, price) {
      this.prices[date] = price;
      return this;
    },

    setPricesFrom : function(from, prices) {
      var date = strToDate(from), prices = arguments[1], sup = arguments[2], ret;
      // seleccion de minimos a partir de dos arrays de precios
      if (arguments.length == 3 && prices.constructor == Array && sup.constructor == Array) {
        ret = map(prices, function(p, i) {
          if (p != 0 && sup[i] != 0) {
            return Math.min(p, sup[i]);
          }
          return p || sup[i];
        });
        return this.setPricesFrom.apply(this, [from].concat(ret));
      }
      for (var i = 1, l = arguments.length; i < l; i += 1) {
        this.setPrice(dateToStr(date), arguments[i]);
        date.setDate(date.getDate() + 1);
      }
      return this;
    },

    setPriceFromUntil : function(from, till, price) {
      var date = strToDate(from);
      var dateEnd = strToDate(till);
      while (date <= dateEnd) {
        this.setPrice(dateToStr(date), price);
        date.setDate(date.getDate() + 1);
      }
      return this;
    },

    getPrice : function(date) {
      return this.prices[date];
    },
    
    getCompany : function() {
      return this.company;
    },
    
    getFirstDate : function() {
      return '' + Math.min.apply(null, collectKeys(this.prices));
    },
    
    getLastDate : function() {
      return '' + Math.max.apply(null, collectKeys(this.prices));
    }

  };

  OH.CalendarMonth = function(year, month, opts) {
    month = month - 1; // human to js
    this.firstDate = new Date(year, month);
    this.month = month;
    this.year = year;
    var d = new Date(year, month + 1);
    d.setDate(d.getDate() - 1);
    this.dayLength = d.getDate();
    opts = opts || {};
    this.config = merge({
      prevMonth : true,
      nextMonth : true,
      firstOfWeek : 1,
      weekDayNames : 'DLMXJVSD'.split(''),
      weekDayHeaders : true,
      cellCallback : null
    }, opts);
  };

  OH.CalendarMonth.prototype = {
    
    toHtml : function() {

      var config = this.config;

      var month = this.month; // allow reading from the conf function
      var year = this.year;

      function next() {
        currentDay += 1;
        currentDate = new Date(year, month, currentDay);
      }


      var firstDay, currentDay, currentDate, i, j, table, thead, clonable_tr, tr, clonable_th, th, clonable_td, td;
      firstWeekDay = this.firstDate.getDay();
      if (firstWeekDay < config.firstOfWeek) firstWeekDay += 7;
      currentDay = this.firstDate.getDate() - firstWeekDay;
      next();
      table = ce('table');
      table.className = 'calendar-month calendar-month-' + pad2(this.firstDate.getMonth() + 1);


      clonable_tr = ce('tr');
      // weekday headers
      if (config.weekDayHeaders) {
        thead = ce('thead');
        table.appendChild(thead);
        tr = clone(clonable_tr);
        clonable_th = ce('th');
        thead.appendChild(tr);
        for (i = config.firstOfWeek; i < 7 + config.firstOfWeek; i += 1) {
          th = clone(clonable_th);
          th.appendChild(document.createTextNode(config.weekDayNames[i]));
          tr.appendChild(th);
        }
      }

      tbody = ce('tbody');
      table.appendChild(tbody);

      clonable_td = ce('td');
      tr = clone(clonable_tr);
      tbody.appendChild(tr);

      // first row
      for (i = config.firstOfWeek; i < 7 + config.firstOfWeek; i += 1) {
        if (i >= firstWeekDay || config.prevMonth) {
          td = this.dayCell(currentDate);
        }
        else {
          td = clone(clonable_td);
        }
        tr.appendChild(td);
        next();
      }
      while (currentDay <= this.dayLength) {
        tr = clone(clonable_tr);
        tbody.appendChild(tr);
        for (i = 0; i < 7 && currentDay <= this.dayLength; i += 1) {
          td = this.dayCell(currentDate);
          tr.appendChild(td);
          next();
        }
      }
      // next month
      for ( ; i < 7; i += 1) {
        if (config.nextMonth) {
          td = this.dayCell(currentDate);
        }
        else {
          td = clone(clonable_td);
        }
        tr.appendChild(td);
        next();
      }

      return table;

    },
    dayCell : function(date) {
      var day = date.getDate();
      var month = date.getMonth();
      var config = this.config;
      var cell = document.createElement('td');
      var isoD = dateToStr(date);
      var classes = [];
      classes.push('dow-' + date.getDay());
      classes.push('date-' + isoD);
      if (month > this.month || month === 0 && this.month === 11) classes.push('next-month');
      else if (month < this.month) classes.push('prev-month');
      cell.className = classes.join(' ');
      cell.appendChild(text(day));
      if (config.cellCallback) config.cellCallback(cell, date);
      return cell;
    }
  };


  return OH;
  
}();

