/* AMEXSearchForm
 * Controls and stores the information about the search form
 * Requires AMEXMapCountries.js
 */
/*********************************************************************************
 *
 *      DO NOT EDIT BELOW THIS LINE
 *
 *********************************************************************************/
var AMEXSearchForm = Class.create({
    initialize: function() {
        this.countryList = COUNTRIES;
        this.inputSet;
        this.airportField = $$('.saddress1')[0];
        this.isTopDest = false;

        // search radius information
        this.radius;
        this.kmInMiles;

        if ($('opt_mi_km')) {
            $('opt_mi_km').select('a').invoke('observe', 'click', this.setRadiusUnits.bindAsEventListener(this));

            this.radiusOptions = { 'mi': { r1:1, r2:5, r3:10, r4:25, r5:50 }, 'km': { r1:5, r2:10, r3:25, r4:50, r5:100 }};
            this.radiusUnits = $('opt_mi_km').select('a.selected')[0].innerHTML;
            this.updateRadiusSelect(this.radiusUnits);

            $('opt_radius').observe('change', function(event) {
                this.radius = Number($('opt_radius').getValue());
            }.bind(this));
        }
        this.setFieldsFromUrl();
        this.setFormFromCurrent(false);

        $$('.scountry')[0].observe('change', this.changeCountry.bindAsEventListener(this));

        if($('SRHeading')) {
            $('SRHeading').select('button').invoke('observe', 'click', function(event) {
                // $$('.sstate2')[0].setValue('');
                event.stop();
            });
        }

        // Get Directions page
        if ($('ReviseSearch')) {
            if($('ReviseSearch').hasClassName('directions')) {
                $('ReviseSearch').select('button').invoke('observe', 'click', function(event) {
                    // $$('.sstate2')[0].setValue('');
                    event.stop();
                });
                $('ReviseSearch').select('input').invoke('observe', 'keypress', function(event) {
                    // $$('.sstate2')[0].setValue('');
                    if (event.keyCode == Event.KEY_RETURN) {
                        event.stop();
                        document.fire('search:submit');
                    }
                });
           } else {
                $('ReviseSearch').select('input').invoke('observe', 'keypress', function(event) {
                    // $$('.sstate2')[0].setValue('');
                    if (event.keyCode == Event.KEY_RETURN) {
                        if(!$('ReviseSearch').hasClassName('landing')) {
                            event.stop();
                        }
                        document.fire('search:submit');
                    }
                });
            }
            $('ReviseSearch').select('button').invoke('observe', 'click', function(event) {
                // $$('.sstate2')[0].setValue('');
                document.fire('search:submit');
            });
        }

        // Landing page
        if ($('find_location')) {
            $('find_location').select('input').invoke('observe', 'keypress', function(event) {
                // $$('.sstate2')[0].setValue('');
                if (event.keyCode == Event.KEY_RETURN) {
                    document.fire('search:submit');
                }
            });
            $('find_location').select('button').invoke('observe', 'click', function(event) {
                // $$('.sstate2')[0].setValue('');
                document.fire('search:submit');
            });
        }

        // airport selection
        this.cachedAirportCountry;
        if ($('window')){
            $('window').hide();
            $$('.launch_window').invoke('observe', 'click', this.showAirportList.bindAsEventListener(this));
            $('close_window').observe('click', this.hideAirportList.bindAsEventListener(this));
            $$('.airportcountry').invoke('observe', 'change', this.changeAirportCountry.bindAsEventListener(this));
        }

                // Top destinations for Japan set up
        if (window.location.pathname.indexOf('jp') != -1) {

        }
    },
    loadStateProvince: function(country) {
        $('locationEntry:sstate2').innerHTML = '';
        switch(country) {
            case 'CA' :
                $('locationEntry:sstate2').insert(SearchHelper.getProvinces()).up().show();
                $('locationEntry:sstate2').value = 'default';
            break;
            case 'US' :
                $('locationEntry:sstate2').insert(SearchHelper.getStates()).up().show();
                $('locationEntry:sstate2').value = 'default';
            break;
            default :
                $('locationEntry:sstate2').up().hide();
                $('locationEntry:sstate2').value = 'default';
            break;
        }
    },
    changeCountry: function(event) {
        var newVal = event.target.getValue();
        this.setCountry(newVal);
        this.setFormFromCurrent(true);
        this.loadStateProvince(newVal);
    },
    setCountry: function(country) {
        this.currentCountry = country;
    },
    setState: function (state) {
        this.currentState = state;
    },
    setFormFromCurrent: function(clear) {
        switch(this.getAbilities('geocode')) {
            case 'City' :
                $('searchAddress').setStyle({ display: 'none' });
                $('searchPostal').setStyle({ display: 'none' });
                $('searchCity').setStyle({ display: 'block' });
                this.inputSet = 'searchCity';
                if ($('find_location')) {
                    $('AddressField').setStyle({ display: 'none' });
                }
                this.airportField = $$('.scity2')[0];
            break;
            case 'Postcode' :
                $('searchAddress').setStyle({ display: 'none' });
                $('searchPostal').setStyle({ display: 'block' });
                $('searchCity').setStyle({ display: 'none' });
                this.inputSet = 'searchPostal';
                if ($('find_location')) {
                    $('AddressField').setStyle({ display: 'block' });
                    this.airportField = $$('.saddress1')[0];
                } else {
                    this.airportField = $$('.saddress3')[0];
                }
            break;
            default :
                $('searchAddress').setStyle({ display: 'block' });
                $('searchPostal').setStyle({ display: 'none' });
                $('searchCity').setStyle({ display: 'none' });
                this.inputSet = 'searchAddress';
                this.airportField = $$('.saddress1')[0];
                if ($('find_location')) {
                    $('AddressField').setStyle({ display: 'block' });
                }
            break;
        }
        if (clear) {
            $$('#searchAddress input, #searchPostal input, #searchCity input').invoke('setValue', '');
        }
        var country = $$('.scountry')[0].getValue();
        if (country != ('US' || 'CA')) {
            $('locationEntry:sstate2').up().hide();
        }
    },
    getFormValues: function() {
        var params = 'scountry='+this.currentCountry+'&sstate='+this.currentState+'&';
        switch(this.getAbilities('geocode')) {
            case 'City' :
                params += Form.serializeElements(Form.getInputs($('searchCity')));
            break;
            case 'Postcode' :
                params += Form.serializeElements(Form.getInputs($('searchPostal')));
            break;
            default :
                params += Form.serializeElements(Form.getInputs($('searchAddress')));
            break;
        }
        console.log(params);
        return params;
    },
    getAbilities: function(ability) {
        return this.countryList.get(this.currentCountry).get(ability);
    },
    getRadiusInMiles: function() {
        if(this.radiusUnits == 'km') {
            return Math.round(this.radius/1.609344);
        } else {
            return this.radius;
        }
        //return this.radius * ((this.radiusUnits == 'km') ? this.kmInMiles : 1);
    },
    getMilesInKm: function(distance) {
        return Math.round((distance*1.609344)*10)/10;
    },
    getRadiusOptionsAsHTML: function(unit) {
        var str = '';
        var obj = this.radiusOptions[unit];
        for (var key in obj) { str += '<option>' + obj[key] + '</option>';  }
        return str;
    },
    updateRadiusSelect: function(unit) {
        $('opt_radius').stopObserving('change');
        $('opt_radius').replace(
            '<select id="opt_radius" name="opt_radius">' + this.getRadiusOptionsAsHTML(unit) + '</select>'
        );
        $('opt_radius').setValue(this.radiusOptions[this.radiusUnits]['r3']);
        this.radius = this.radiusOptions[this.radiusUnits]['r3'];
        $('opt_radius').observe('change', function(event) {
            this.radius = Number($('opt_radius').getValue());
        }.bind(this));
    },
    setRadiusUnits: function(event) {
        event.stop();
        this.radiusUnits = event.target.innerHTML;
        $('opt_mi_km').select('a').each(function(link) {
            link.removeClassName('selected');
            if(event.target == link) {
                link.addClassName('selected');
            }
        }.bind(this));
        this.updateRadiusSelect(this.radiusUnits);
    },
    isValidSearch: function() {
        switch(this.getAbilities('geocode')) {
            case 'City' :
                if($$('.scity2')[0].getValue().blank() && $$('.saddress1')[0].getValue().length != 3) {
                    return false;
                } else { return true; }
            break;
            case 'Postcode' :
                var address;
                ($('find_location')) ? address = $$('.saddress1')[0].getValue() : address = $$('.saddress3')[0].getValue();
                if(($$('.scity3')[0].getValue().blank() && $$('.spostalcode')[0].getValue().blank()) && address.length != 3) {
                    return false;
                } else { return true; }
            break;
            case 'Address' :
                if($$('.scity1')[0].getValue().blank() && $$('.saddress1')[0].getValue().length != 3) {
                    return false;
                } else { return true; }
            break;
            default :
                if($$('.saddress1')[0].getValue().blank()) {
                    return false;
                } else { return true; }
            break;
        }
    },
    setValuesFromQuery: function(query) {
        g_query = query;
        this.currentCountry = query.getCountry();
        this.setFormFromCurrent(true);

        switch(this.getAbilities('geocode')) {
            case 'City' :
                $$('.scity2')[0].setValue(query.getCity());
                //$$('.scounty')[0].setValue(query.getCounty());
                $$('.spostalcode')[0].setValue(query.getPostalCode());
                // $$('.sstate2')[0].setValue(query.getState());
            break;
            case 'Postcode' :
                $$('.saddress3')[0].setValue(query.getStreet());
                $$('.scity3')[0].setValue(query.getCity());
                //$$('.scounty')[0].setValue(query.getCounty());
                $$('.spostalcode')[0].setValue(query.getPostalCode());
                $$('.sstate2')[0].setValue(query.getState());
            break;
            default :
                $$('.saddress1')[0].setValue(query.getStreet());
                $$('.scity3')[0].setValue(query.getCity());
                //$$('.scounty')[0].setValue(query.getCounty());
                // $$('.sstate2')[0].setValue(query.getState());
            break;
        }

    },
    setFieldsFromUrl: function() {
        // Load the country field from URL query params.
        var params = window.location.search.toQueryParams();

        // Set country and state select boxes.  If the value is explicitly passed
        // in the URL query params, set the select box to that value.  If not in URL,
        // use the default value of the select box.
        if (params.scountry) {
            var countryCode = params.scountry;
        if (countryCode == "UK") {
              countryCode = "GB";
            }

            $$('.scountry')[0].setValue(countryCode);
        params.scountry = countryCode;
        } else {
            params.scountry = $$('.scountry')[0].getValue();
        }
        this.loadStateProvince(params.scountry);
        if (params.sstate) {
            $$('.sstate2')[0].setValue(params.sstate);
        } else {
            params.sstate = $$('.sstate2')[0].getValue();
            if (params.sstate == "default") params.sstate = "";
        }

        this.currentCountry = params.scountry;
        this.currentState = params.sstate;
        // City and address fields depend on which form inputSet we're using.
        var addressSel = '';
        var citySel = '';

        switch(this.getAbilities('geocode')) {
            case 'City' :
                citySel = ".scity2";
            break;
            case 'Postcode' :
                addressSel = ".saddress3";
                citySel = ".scity3";
            break;
            case 'Address' :
                addressSel = ".saddress1";
                citySel = ".scity1";
            break;
            default :
                addressSel = ".saddress1";
                citySel = ".scity3";
            break;
        }

        // Load values into the form if found in the URL.
        if (addressSel && params.saddress) { $$(addressSel)[0].setValue(params.saddress); }
        if (params.scity) { $$(citySel)[0].setValue(params.scity); }
        if (params.spostalcode) { $$('.spostalcode')[0].setValue(params.spostalcode); }
    },
    setValuesFromParams: function(query) {
        this.setCountry(query['scountry']);
        this.setState(query['sstate2']);
        this.setFormFromCurrent(true);
        // each query key must match the id of the input field
        var queryKeys = Object.keys(query);
        queryKeys.each(function(key) {
            if($(key)) { $(key).value = query[key]; }
        });
    },
    getSearchRequest: function() {
      var resultsfor, scountry, sstreet, scity, scounty, sstate, spostal;
      switch(AMEXSearchForm.instance.inputSet) {
          case 'searchCity' :
              scountry = $$('.scountry')[0].getValue();
              scity = $$('.scity2')[0].getValue();
							//scounty = $$('.scounty')[0].getValue();
							//$$('.scounty')[0].setValue("");
              // sstate = $$('.sstate2')[0].getValue();
              // if (sstate == 'default') {
              //     sstate = '';
              // }

              address = new MQAddress();
              address.setCountry(scountry);
              address.setCity(scity);
							if (scounty !== null && scounty != '') {
								address.setCounty(scounty);
							}
              // address.setState(sstate);

              // resultsfor = scity+', '+(sstate ? sstate+', ' : '')+$$('.scountry')[0].down('option[value='+this.currentCountry+']').innerHTML;
              resultsfor = scity+', '+$$('.scountry')[0].down('option[value='+this.currentCountry+']').innerHTML;
          break;
          case 'searchAddress':
              scountry = $$('.scountry')[0].getValue();
              sstreet = $$('.saddress1')[0].getValue();
              scity = $$('.scity1')[0].getValue();
							//scounty = $$('.scounty')[0].getValue();
							//$$('.scounty')[0].setValue("");
              sstate = $$('.sstate2')[0].getValue();
              if (sstate == 'default') {
                  sstate = '';
              }

              address = new MQAddress();
              address.setCountry(scountry);
              address.setStreet(sstreet);
              address.setCity(scity);
							if (scounty !== null && scounty != '') {
								address.setCounty(scounty);
							}
              if (sstate !== null && sstate != '') {
                address.setState(sstate);
              }

              if(sstreet) { sstreet += ', '; }
              if(scity) { scity += ', '+(sstate ? sstate+', ' : ''); }

              resultsfor = sstreet+scity+$$('.scountry')[0].down('option[value='+this.currentCountry+']').innerHTML;
          break;
          case 'searchPostal' :
              scountry = $$('.scountry')[0].getValue();
              sstreet = $$('.saddress3')[0].getValue();
              scity = $$('.scity3')[0].getValue();
              spostal = $$('.spostalcode')[0].getValue();
							//scounty = $$('.scounty')[0].getValue();
							//$$('.scounty')[0].setValue("");
              sstate = $$('.sstate2')[0].getValue();
              if (sstate == 'default') {
                  sstate = '';
              }
              address = new MQAddress();
              address.setCountry(scountry);
              address.setStreet(sstreet);
              address.setCity(scity);
              address.setPostalCode(spostal);
							if (scounty !== null && scounty != '') {
								address.setCounty(scounty);
							}
              if (sstate !== null && sstate != '') {
                address.setState(sstate);
              }
              if(sstreet) { sstreet += ', '; }
              if(scity) { scity += ', '+(sstate ? sstate+', ' : ''); }
              if(spostal) { spostal += ', '; }
              resultsfor = sstreet+scity+spostal+$$('.scountry')[0].down('option[value='+this.currentCountry+']').innerHTML;
          break;
      }

      return { address: address, resultstring: resultsfor };
    },
    // Show airport code or top destination popup.
    showAirportList: function(event) {
        var countryCode = $$('.scountry')[0].getValue().toLowerCase();
        this.isTopDest = event.target.hasClassName('cities');

        if (Prototype.Browser.IE) {
          $$('#find_location select, #locationEntry fieldset select').invoke('hide');
        }

        if ((this.cachedAirportCountry == countryCode) && (window.location.pathname.indexOf('jp') == -1)) {
            $('window').show();
            return;
        }

        if (this.isTopDest) {
            var tdSelect = $$('.airportcountry')[1];
            var defaultCountry = $$('.scountry')[0];
            tdSelect.value = defaultCountry.value;

            // If country assignment in popup fails, fall back on USA (the top destination
            // country list is shorter than the main country list).
            if (tdSelect.value != defaultCountry.value) {
                tdSelect.value = "US";
                countryCode = "us";
            }
        } else {
            $$('.airportcountry')[0].value = $$('.scountry')[0].value;
        }

        this.updateAirportList(event, countryCode);


        $('window').show();
        event.stop();
    },
    updateAirportList: function(event, countryCode) {
        $('airportBody').innerHTML = 'Loading...';
        var insertLocation = $('airportBody');
        if (typeof event != 'object') {
            countryCode = event;
        }
        var framePath = '';
        if ((window.location.pathname.indexOf('jp') != -1) && this.isTopDest) {
            framePath = '/cities/select_destination_' + countryCode + '.html';
        } else {
            framePath = '/airport-' + Lang.LANG_URL + 'select_airport_' + countryCode + '.html';
        }

        // TODO: update ajax call for rails app
        new Ajax.Updater(insertLocation, framePath, {
            method: 'get',
            onSuccess: this.bindAirportForm.bind(this, insertLocation)
        });

        this.cachedAirportCountry = countryCode;
    },
    bindAirportForm: function(insertLocation, transport) {
        setTimeout(function(){
            insertLocation.getElementsBySelector('.iframe li a').each(function(anchor){
                anchor.observe('click', this.chooseAirport.bind(this, anchor));
            }.bind(this));

            insertLocation.getElementsBySelector('ul.alphabet li a').each(function(letter){
                letter.observe('click', this.chooseLetter.bind(this));
            }.bind(this));

        }.bind(this),100);
        if (this.isTopDest) {
            $$('.airport_code_labels').each(function(element){ element.hide(); })
            $$('.topdest_labels').each(function(element){ element.show(); })
        } else {
            $$('.airport_code_labels').each(function(element){ element.show(); })
            $$('.topdest_labels').each(function(element){ element.hide(); })
        }
    },
    hideAirportList: function(event) {
        if (Prototype.Browser.IE) {
          $$('#find_location select, #locationEntry fieldset select').invoke('show');
        }
        $('window').hide();
    },
    chooseLetter: function(event) {
        var letter = event.target.hash.replace('#', '');
        var div = $$('div.iframe')[0];
        div.scrollTop = $(letter).positionedOffset().top - div.positionedOffset().top - 5;
        event.stop();
    },
    chooseAirport: function(anchor) {
        if (this.isTopDest) {
            var newCountry = $$('.airportcountry')[1].value;
            $$('.scountry')[0].value = newCountry;
            $$('.scity3')[0].value = anchor.select('input').first().value;
        } else {
            var newCountry = $$('.airportcountry')[0].value;
            $$('.scountry')[0].value = newCountry;
            this.airportField.value = anchor.select('input').first().value;
        }
        this.setCountry(newCountry);
        this.setFormFromCurrent(false);
        this.loadStateProvince(newCountry);

        this.hideAirportList();
    },
    changeAirportCountry: function(event) {
        var newCountry = event.target.getValue();
        this.updateAirportList(newCountry.toLowerCase());
        event.stop();
    }
});

AMEXSearchForm.init = function() { AMEXSearchForm.instance = new AMEXSearchForm(); };
document.observe('dom:loaded', AMEXSearchForm.init);

