var gtmFlightsAutocompleter = {};
gtmFlightsAutocompleter.Base = Class.create(Autocompleter.Base, {
  onBlur: function(event) {
    this.hide();

    this.hasFocus = false;
    this.active   = false;

    var direction = this.element.identify().replace('Airport', '');
    var isSpace = $F(this.element).strip() === '';

    if (isSpace) {
      $$('body').first().fire('flightsAutocompleter:update',
                              {
                                   direction: direction,
                                   iata: ''
                              });
        return;
      }
      setTimeout(this._initFastIata.bind(this, event), 0);
  },
  _initFastIata: function(event) {
      if ($(this.element).readAttribute('isfirstupdate') == 'false' && !$(this.update).visible() && $F($(this.element)).length == 3 ) {
          var isDomesticFlights = $(this.element).readAttribute('domestic');
          isDomesticFlights = isDomesticFlights === 'true' ? 'true' : 'false';
          console.log('fastIataDomesticFlights=');
          console.log(isDomesticFlights);

          var direction = this.element.identify().replace('Airport', '');
          var postBody = Object.toQueryString({query: $F(this.element)});
          var urlParametrs = new Hash({
              action: 'location',
              method: 'autocompleteFastIata',
              direction: direction,
              isDomesticFlights: isDomesticFlights,
              clearCache: 'true'
          });
          var url = "/flights/?" + urlParametrs.toQueryString();
          new Ajax.Request(url, {
                           postBody: postBody,
                           onSuccess: this._fastInsertIata.bind(this),
                           onException: function(r, e) {console.log(e);},
                           onFailure: function (e, r) {console.log(e);}});
      } else if ($(this.update).visible() && $F(this.element) != $(this.getCurrentEntry()).innerHTML ) {
          this.selectEntry();
          this.active = false;
      } else if (!$(this.update).visible() && $(this.element).readAttribute('isfirstupdate') == 'false') {
        var direction = this.element.identify().replace('Airport', '');
        $$('body').first().fire('flightsAutocompleter:update',
                                {
                                    direction: direction,
                                    iata: ''
                                });
      }
      this.hide();
  },
  _fastInsertIata: function(transport) {
      if (transport.responseText === 'departure_false' || transport.responseText === 'destination_false') {
        var direction = transport.responseText === 'departure_false' ? 'departure' : 'destination';
        this.element.value = 'Incorrect IATA code';
        $$('body').first().fire('flightsAutocompleter:update',
                                {
                                    direction: direction,
                                    iata: ''
                                });
          return;
      }
      var li = new Element('ul').insert(transport.responseText).firstDescendant();

      this._updateElementFastIata(li);

      setTimeout(this.hide.bind(this), 0);
      this.hasFocus = false;
      this.active = false;
  },
  _updateElementFastIata: function(selectedElement) {
    if (this.options.updateElement) {
      this.options.updateElement(selectedElement);
      return;
    }
    var value = '';
    if (this.options.select) {
      var nodes = $(selectedElement).select('.' + this.options.select) || [];
      if(nodes.length>0) value = Element.collectTextNodes(nodes[0], this.options.select);
    } else
      value = Element.collectTextNodesIgnoreClass(selectedElement, 'informal');

    var bounds = this.getTokenBounds();
    if (bounds[0] != -1) {
      var newValue = this.element.value.substr(0, bounds[0]);
      var whitespace = this.element.value.substr(bounds[0]).match(/^\s+/);
      if (whitespace)
        newValue += whitespace[0];
      this.element.value = newValue + value + this.element.value.substr(bounds[1]);
    } else {
      this.element.value = value;
    }
    this.oldElementValue = this.element.value;

    if (this.options.afterUpdateElement)
      this.options.afterUpdateElement(this.element, selectedElement);
  },
  onObserverEvent: function() {
    this.changed = false;
    this.tokenBounds = null;
    if(this.getToken().length>=this.options.minChars) {
      this.getUpdatedChoices();
    } else {
      this.active = false;
      this.hide();
    }
    this.oldElementValue = this.element.value;
  },
  onKeyPress: function(event) {
    if ($F(this.element).strip() === '') {
        $(this.element).writeAttribute('isfirstupdate', 'false');
        var direction = this.element.identify().replace('Airport', '');
        $$('body').first().fire('flightsAutocompleter:update',
                                {
                                    direction: direction,
                                    iata: ''
                                });
        return;
    }

    if(this.active)
      switch(event.keyCode) {
       case Event.KEY_TAB:
       case Event.KEY_RETURN:
         this.selectEntry();
         Event.stop(event);
         this.hide();
         this.active = false;
         return;
       case Event.KEY_ESC:
         this.onPressEsc(event);
         this.active = false;
         Event.stop(event);
         return;
       case Event.KEY_LEFT:
       case Event.KEY_RIGHT:
         return;
       case Event.KEY_UP:
         this.markPrevious();
         this.render();
         Event.stop(event);
         return;
       case Event.KEY_DOWN:
         this.markNext();
         this.render();
         Event.stop(event);
         return;
      }
     else
       if(event.keyCode==Event.KEY_TAB
         || event.ctrlKey
         || event.altKey
         || event.keyCode==Event.KEY_RETURN
         || event.keyCode==Event.KEY_ESC
         || event.keyCode==Event.KEY_LEFT 
         || event.keyCode==Event.KEY_UP
         || event.keyCode==Event.KEY_RIGHT 
         || event.keyCode==Event.KEY_DOWN
         || event.keyCode==Event.KEY_HOME
         || event.keyCode==Event.KEY_END
         || event.keyCode==Event.KEY_PAGEUP
         || event.keyCode==Event.KEY_PAGEDOWN
         || (Prototype.Browser.WebKit > 0 && event.keyCode == 0)) return;
     this._startRequestAutocomplete();

  },
  _startRequestAutocomplete: function(interval) {
    $(this.element).writeAttribute('isfirstupdate', 'false');

    this.changed = true;
    this.hasFocus = true;
    var interval = interval ? interval : this.options.frequency*1000;
    if(this.observer) clearTimeout(this.observer);
      this.observer =
        setTimeout(this.onObserverEvent.bind(this), interval);
  },
  onPressEsc: function(event) {
      this.selectEntry();
      this.hide();
      this.active = false;
      Event.stop(event);
  },
  onClick: function(event) {
  }
});


Ajax.gtmFlightsAutocompleter = Class.create(gtmFlightsAutocompleter.Base, {
  initialize: function(element, update, url, options) {
    this.baseInitialize(element, update, options);
    this.options.asynchronous  = true;
    this.options.onComplete    = this.onComplete.bind(this);
    this.options.defaultParams = this.options.parameters || null;
    this.url                   = url;
  },
  getUpdatedChoices: function() {
    this.startIndicator();

    var entry = encodeURIComponent(this.options.paramName) + '=' +
      encodeURIComponent(this.getToken());

    this.options.parameters = this.options.callback ?
      this.options.callback(this.element, entry) : entry;

    if(this.options.defaultParams)
      this.options.parameters += '&' + this.options.defaultParams;

    new Ajax.Request(this.url, this.options);
  },

  onComplete: function(request) {
    this.updateChoices(request.responseText);
  },
  markPrevious: function() {
    if(this.index > 0) this.index--;
      else this.index = this.entryCount-1;
    this.getEntry(this.index);
  },

  markNext: function() {
    if(this.index < this.entryCount-1) this.index++;
      else this.index = 0;
    this.getEntry(this.index);
  }
});

var Control_Abstract = {
  _uniqueElement: false,
  _createUniqueElement: function() {
      var uniqueElemen = new Element('div').setStyle({display: 'none'});
      this._uniqueElement = $$('body').reduce().insert(uniqueElemen);
      var uniqueElemenname = uniqueElemen.identify();
  }
};


var Autocomplete_Abstract = Class.create({
	  initialize: function() {
	      document.observe('autocompliterFlights:start', this._init.bind(this));
	  },
	  _init: function(event) {
	      this._initElemeStorage();
	      this._initObserver();
	      this._initAutocompletes();

	      this._createUniqueElement();
	  },
	  _clickAutocomplete: function(event) {
	      Event.element(event).select();
	  }
	}, Control_Abstract);





var Flights_Autocomplete = Class.create(Autocomplete_Abstract, {
  _autocompletes: new Hash({}),
  _elemStorage: {
      departureAutocomplete: false,
      destinationAutocomplete: false
  },
  _autocompleteContainer: {
      container:   false,
      input:       false,
      blockResult: false
  },
  _autocomplete: [],
  _initElemeStorage: function() {
      $$('.flightsAutocompletes').each(function(elem) {
          var type = this.getTypeAutocomplete(elem);

          this._elemStorage[type] = new Object();

          Object.extend(this._elemStorage[type],
                        this._autocompleteContainer);

          this._elemStorage[type].container = elem;
          this._elemStorage[type].input = $(elem).select('input').reduce();
          this._elemStorage[type].input.writeAttribute('isfirstupdate', 'false');

          this._elemStorage[type].blockResult = $(elem).select('div')
                                                       .reduce();
      }.bind(this));
  },
  getTypeAutocomplete: function(elem) {
      var nameElem = elem.identify();
      if (nameElem == 'flightsDestinationAutocompleteContainer') {
          return 'destinationAutocomplete';
      } else if (nameElem == 'flightsDepartureAutocompleteContainer') {
          return 'departureAutocomplete';
      } else {
          throw new Error('bad id by autocompletes');
      }
  },
  _initObserver: function() {
      $H(this._elemStorage).each(function(elem){
          elem = elem.value;
          if (elem) {
              var input = elem.input;
              $(input).observe('click', this._clickAutocomplete.bind(this));
          }
      }.bind(this));
      document.observe('flightsStorage:changeClient', this._changeClienEvent.bind(this));
  },
  _changeClienEvent: function(event) {
      var name = this._storage.getClientName();
      this.changeClientNameInUrl(name);
  },
  _initAutocompletes: function() {
      $H(this._elemStorage).each(function(elem){
          var typeContainer = elem.key;
          elem = elem.value;

          if (elem) {
              var input = elem.input;
              var blockResult = elem.blockResult;
              var direction = typeContainer.replace('Autocomplete', '');
              this._createAutocomplete(input, blockResult, direction);
          }
      }.bind(this));
  },
  _updateAutocompleter: function(text, li) {
      text.writeAttribute('isfirstupdate', 'true');
      var direction = text.identify().replace('Airport', '');
      var iata = li.identify();

      if (iata.length != 3 || $(text).readAttribute('isnan') == 'true') {
          iata = '';
      }

      $(this._uniqueElement).fire('flightsAutocompleter:update',
                                  {
                                      direction: direction,
                                      iata: iata
                                  });
  },
  _createAutocomplete: function(input, blockResult, direction) {
      var clientName, params, queryParams, queryParamsKey, isSetDeparture;
      console.log('sssss');
      console.log(input);
      var isDomesticFlights = $(input).readAttribute('domestic');
      isDomesticFlights = isDomesticFlights === 'true' ? 'true' : 'false';
      console.log(isDomesticFlights);
      params = $H({action:    'location',
                   method: 'autocomplete',
                   direction: direction,
                   isDomesticFlights: isDomesticFlights,
                   clearCache: 'true'}).toQueryString();
      params = '/flights/?' + params;

      queryParams = location.href.toQueryParams();

      queryParamsKey = Object.keys(queryParams);

      var isDirection = queryParamsKey.indexOf(direction);

      if (isDirection != -1) {
          var url = "/flights/?action=location&method=locationTextByIata";
          var postBody = Object.toQueryString({iata: $H(queryParams).get(direction),
                                               direction: direction});
      } else {
          var urlParametrs = new Hash({
              action: 'location',
              method: 'getIataByIp',
              isDomesticFlights: isDomesticFlights
          });
          var url = "/flights/?" + urlParametrs.toQueryString();
          var postBody = Object.toQueryString({direction: direction});
      }
      if (input.readAttribute('primary') == null) {
          var responseHendler = this._setIataInInput.bind(this);
          new Ajax.Request(url, {
                                 postBody: postBody,
                                 onSuccess: responseHendler,
                                 onException: function(r, e) {console.log(e);},
                                 onFailure: function (e, r) {console.log(e);}});
      } else {
          input.value = input.readAttribute('primary');
      }

      this._autocompletes.set(direction, new Ajax.gtmFlightsAutocompleter($(input),
                $(blockResult),
                params,
                {
                    paramName: 'query',
                    frequency: 0.4,
                    afterUpdateElement: this._updateAutocompleter
                                            .bind(this)
                })
      );
  },
  _setIataInInput: function(transport) {
      var searchResponse, autocomplete, input, direction, iata;
      searchResponse = transport.responseJSON;

      if (!searchResponse || (searchResponse && searchResponse.text == -1)) {
          return;
      }

      direction = searchResponse.direction;
      iata = searchResponse.iata;

      autocomplete = direction + 'Autocomplete';
      input = this._elemStorage[autocomplete].input;
      input.value = searchResponse.text;

      $(this._uniqueElement).fire('flightsAutocompleter:update',
                                  {
                                      direction: direction,
                                      iata: iata
                                  });
  },
  changeClientNameInUrl: function(name) {
      this._autocompletes.each(function(elem) {
        var hash    = elem.value.url.toQueryParams();
        hash.client = this._storage.getClientName();
        elem.value.url = './?' + $H(hash).toQueryString();
      }.bind(this));

      $H(this._elemStorage).each(function(elem){
          elem = elem.value;
          if (elem) {
              var input = elem.input;
              $(input).value = 'Origin';
          }
      }.bind(this));
  }
});

var flightsAutocomplete = new Flights_Autocomplete();

var PForm = Class.create({
    initialize: function() {
        this.weekDays = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
        this.months   = ["Jan", "Feb", "Mar", "Apr", "May", "Jun",
                         "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];

        this.prepare();
        this.returnDateElements = ['returnDay', 'returnMonth',
                                   'arrtime', 'bottomCalImage',
                                   'arrivelTimeSign', 'returnSign'];

       this.departure_url   = '/?action=departure';
       this.destination_url = '/?action=destination';
    },
    getDate: function(point) {
        if (point != "departure" && point != "return") {
            return false;
        }
        var date = new Date();
        date.setYear($(point + "Month").value.substr(0, 4));
        date.setMonth($(point + "Month").value.substr(4, 2) - 1);
        date.setDate(parseInt($(point + "Day").value));
        return date;
    },
    moveTo: function(element) {
        if ($('form_container')) {
            $('share').appendChild($('flights_form'));
            $('form_container').remove();
        }
        var flightsElement = elem('div', {id:'form_container'});
        flightsElement.appendChild($('flights_form'));

        $(element).appendChild(flightsElement);

        $("blockResultContainer").update();
        $("blockResultContainer").style.paddingTop = "15px";

        if ($("returnDay").style.display == "none" || $("returnDay").style.visibility == "hidden") {
            $("tripType0").checked = true;
        }

        $("rb") && $("rb").remove();

        $("blockResultContainer").appendChild(elem("br"));

        if ($("birth_container")) {
            $("birth_container").colSpan = 2;
        }

        $$('.delInNewFlightsForm').each(
            function(elem) {
                elem.remove();
            }
        );

        $("flights_form").style.backgroundImage = "none";
        if (! Element.hasClassName("flights_form", "modify_form")) {
            Element.addClassName($("flights_form"), "modify_form");
        }
    },
    prepare: function() {
        $A($("cabin").options).each(function(option) {
            if (option.value == $('cabin').getAttribute("default")) {
                option.selected = true;
            }
        });

        Event.observe("tripTypeR", "click", this.showReturnDate.bindAsEventListener(this));
        Event.observe("tripType0", "click", this.hideReturnDate.bindAsEventListener(this));

        $$('body').first().fire('autocompliterFlights:start');

        this.prepareDates(); 

        var flights = Page.getInstance().getFlights();
        flights.initData();
        var eventHandler = flights.search.bindAsEventListener(flights);
        Event.observe("search_btn", "click", eventHandler);
        setTimeout(function() {Page.getInstance().autoSearch()}, 1000);
    },
    createAutocompleter: function (location) {
        var uid = location + "Airport";
        if ($(uid).nodeName.toLowerCase() == "select") {
            return;
        }
        $(uid).disabled = false;
        $(uid).value = "";
        if ($(uid).getAttribute("primary")) {
            $(uid).value = $(uid).getAttribute("primary");
        }

        var autocompleteUrl = "/flights/?action=autocomplete&" + location;
        if ($(uid).getAttribute("domestic") == 'true') {
            autocompleteUrl = autocompleteUrl + '&domestic';
        }

        new Ajax.Autocompleter(location + "Airport", location + "Autocomplete", autocompleteUrl, {paramName: "query", checkIATA: true, afterUpdateElement: function (text, li) {
            text.value = li.firstChild.nodeValue;
        }});
        Event.observe(uid, "click", function(e) {
            Event.element(e).select();
        });
    },
    hideReturnDate: function() {
        this.returnDateElements.each(function(element) {
            $(element).setStyle({visibility: "hidden"});
        });
    },
    showReturnDate: function() {
        this.returnDateElements.each(function(element) {
            $(element).setStyle({visibility: "visible"});
        });
    },
    prepareDates: function() {
        this.buildDates();
    },
    buildDates: function() {
        var date = new Date();
        var departureDate = new Date();
        departureDate.setDate(departureDate.getDate()+2);
        var dd = departureDate;
        var returnDate = new Date();
        returnDate.setTime(departureDate.getTime()+ parseInt(14*60*60*24 + "000"));
        var rd = returnDate;
        $("departureMonth").value = dd.getFullYear()+""+(dd.getMonth()+1).toPaddedString(2);
        $("returnMonth").value = rd.getFullYear()+""+(rd.getMonth()+1).toPaddedString(2);

        selectedDefaultReturnDay = 0;
        selectedDefaultDepartureDay = 0;

        for (var i = 1; i < 32; i++) {

            var departureLength = $('departureDay').options.length;
            $('departureDay').options[departureLength] = new Option(i.toPaddedString(2), i);

            if (i == departureDate.getDate()) {
                $('departureDay').options[departureLength].selected = true;
            }
            var returnLength = $('returnDay').options.length;
            $('returnDay').options[returnLength] = new Option(i.toPaddedString(2), i);
            if (i == returnDate.getDate()) {
                $('returnDay').options[returnLength].selected = true;
            }

            if ($('defaultDepartureDay').value) {
                if (parseFloat($('defaultDepartureDay').value) == $('departureDay').options[departureLength].value) {
                    selectedDefaultDepartureDay = departureLength;
                }
            }

            if ($('defaultReturnDay').value) {
                if (parseFloat($('defaultReturnDay').value) == $('returnDay').options[returnLength].value) {
                    selectedDefaultReturnDay = returnLength;
                }
            }
        }

        if (selectedDefaultDepartureDay) {
            $('departureDay').options[selectedDefaultDepartureDay].selected = true;
        }
        if (selectedDefaultReturnDay) {
            $('returnDay').options[selectedDefaultReturnDay].selected = true;
        }

        if ($('defaultDepartureMonth').value && $('defaultReturnMonth').value) {
            for (var i = 0; i < 12; i++) {
                if ($("departureMonth").options[i].value == $('defaultDepartureMonth').value) {
                    $("departureMonth").options[i].selected = true;
                }
                if ($("returnMonth").options[i].value == $('defaultReturnMonth').value) {
                    $("returnMonth").options[i].selected = true;
                }
            }
        }
    },
    checkDate: function() {
        var returnMonth    = new Number($("returnMonth").value).toPaddedString(2);
        var returnDay      = new Number($("returnDay").value).toPaddedString(2);
        var departureDay   = new Number($("departureDay").value).toPaddedString(2);
        var departureMonth = new Number($("departureMonth").value).toPaddedString(2);

        var arriveTime = returnMonth + returnDay;
        var departTime = departureMonth + departureDay;

        if (arriveTime < departTime) {
            $("incorrectdate").show();
            return false;
        }
        $("incorrectdate").hide();
        return true;
    },
    getElementText: function(elementId) {
        if ($(elementId)) {
            var nodeName = $(elementId).nodeName.toLowerCase();

            if (nodeName == "select") {
                nodeText = $(elementId).options[$(elementId).selectedIndex].text;
                return nodeText;
            } else {
                return $(elementId).value;
            }
        }
        return false;
    },
    getIATA: function(elementId) {
        if ($(elementId)) {
            var nodeName = $(elementId).nodeName.toLowerCase();

            if (nodeName == "select") {
                nodeText = $(elementId).options[$(elementId).selectedIndex].value;
                return nodeText;
            } else {
                 try {
                    var elementValue = $(elementId).value;
                    if (elementValue) {
                        if(!new RegExp("\[[A-Z]{3}\]").test(elementValue)) {
                            return false;
                        }
                    }
                    if (elementValue == "") {
                        return false;
                    }
                    return elementValue.substr(elementValue.indexOf("[") + 1, 3);
                } catch (exception) {
                    dispatchException(exception);
                }
                return $(elementId).value;
            }
        }
        return false;
    },
    setAutostartParameters: function() {
        var postContainer = $("post");
        var childNode, i = 0;
        while (childNode = postContainer.childNodes[i]) {
            i++;
            if (childNode.id != null) {
                var paramName = childNode.id.replace("_post", "");
                if (paramName == "tripType") {
                    var radioButtonId = "tripType" + childNode.firstChild.nodeValue;
                    if ($(radioButtonId)) {
                        if (childNode.firstChild.nodeValue == "0") {
                            this.hideReturnDate();
                        }
                        $(radioButtonId).checked = true;
                    }
                }
                if ($(paramName)) {
                    if (typeof(childNode.firstChild) == "undefined" ||
                            childNode.firstChild == null) {
                        continue;
                    }
                    switch ($(paramName).nodeName.toLowerCase()) {
                        case "select":
                            for (var j = 0; j < $(paramName).options.length; j++) {
                                var options = $(paramName).options[j];
                                if (options.value == childNode.firstChild.nodeValue) {
                                    $(paramName).options[j].selected = true;
                                    break;
                                }
                            }
                            break;
                        case "input":
                            var nodeValue = childNode.firstChild.nodeValue;
                            if (paramName.indexOf("Airport") != -1 && 
                                $(name = paramName.replace("Airport", "") + "_post").firstChild != null) {
                                nodeValue = $(name).firstChild.nodeValue;
                            }
                            $(paramName).value = nodeValue;
                            break;
                        default:
                            $(paramName).value = childNode.firstChild.nodeValue;
                            break;
                    }
                }
            }
        }
    }
});
