var Flights = Class.create({
    initialize: function () {
        this.timer = 0;
        this.timerInterval = false;
        this.resultUrl = "/flights/?action=result";
        this.searchUrl = "/flights/?action=search";
        this.initData();
    },
    initData: function () {
        if (typeof(this.data) == "undefined") {
            this.data = new Data();
        }
    },
    getData: function () {
        return this.data;
    },
    search: function() {
        if (!Page.getInstance().getForm().checkDate()) {
            return;
        }
        if (!checkIATA($("departureAirport"))) {
            alert("Please type departure airport");
            return;
        }
        if (!checkIATA($("destinationAirport"))) {
            alert("Please type destination airport");
            return;
        }

        if ($F("departureAirport") == $F("destinationAirport")) {
            alert("Departure and destination are the same.");
            return;
        }
        setTimeout(function () {
            Page.getInstance().getForm().moveTo("share");
            Element.hide("subscribe_block");
            $("bestFareRecord") && $("bestFareRecord").hide();
            PrimaryLayout.getInstance().renderBottomLinks();
        }, 1000);
        this.data.reset();

        this.checkClientRedirect();

        if (typeof(this.timeoutHandler) != "undefined") {
            clearTimeout(this.timeoutHandler);
        }
        clearInterval(this.timerInterval);
        this.timerInterval = false;
        this.timer = 0;

        if (!this.holdingPage) {
            holdingPage = new Page.HoldingPage();
        } else {
            holdingPage.animate(false);
        }
        holdingPage.show();
        setTimeout(this.searchRequest.bind(this), 3000);
    },
    checkClientRedirect: function() {
        var checkRedirect;
        new Ajax.Request("/flights/?action=checkRedirect", {
            postBody: $H({
                destination:    $("destinationAirport").value
            }).toQueryString(),
            onSuccess: function (response) {
                if (response.responseText.replace(/^\s+|\s+$/g,"").length > 0) {
                    var form = new Element('form', {action: response.responseText, method: 'post'});
                    var elements = Form.serialize("searchfrm", true);
                    $H(elements).each(function(input) {
                        form.appendChild(new Element('input', {type:'hidden', name: input[0], value:input[1]}));
                    });
                    document.body.appendChild(form);
                    form.submit();
                }
            }
        });
    },
    searchRequest: function () {
        Page.getInstance().getMatrix().selectedAirlines = [];

        setTimeout(function () {
            holdingPage.hide();
            Page.getInstance().getMatrix().show();
            PrimaryLayout.getInstance().renderBottomLinks();
        },  27000);

        setTimeout(function() {
            var serialized = Form.serialize("searchfrm", true);
            serialized.departureAirport = serialized.departureAirport.substr(serialized.departureAirport.indexOf("[") + 1, 3);
            serialized.destinationAirport = serialized.destinationAirport.substr(serialized.destinationAirport.indexOf("[") + 1, 3); 
            new Ajax.Request(this.searchUrl, {
                postBody: $H(serialized).toQueryString(),
                onSuccess: this.processQueryResult.bind(this),
                onException: function(r, e) {console.log(e);},
                onFailure: function (e, r) {console.log(e);}
            });
            setTimeout(function() {
                this.carbon = new Carbon();
            }.bind(this), 1000);
        }.bind(this), 2000);
        var form = Page.getInstance().getForm();
        var departureDate = form.getDate("departure");
        var returnDate    = form.getDate("return");
        try {
            var datesString = departureDate.toGtmString() + " - " + returnDate.toGtmString();
        } catch (e) {
            var datesString = $("outbound_departing_date_post").firstChild.nodeValue
                            + " - "
                            + $("inbound_departing_date_post").firstChild.nodeValue;
        }
        this.getData().setData("datesString", datesString);
    },
    processQueryResult: function(transport) {
        var searchResponse = transport.responseJSON[0];
        /*
        var tmp = '[{"criteria":{"departure":{"airport":"Brisbane","code":"BNE","country":"Australia","area":"Australasia"},"destination":{"airport":"Sydney Kingsfordsmith","code":"SYD","country":"Australia","area":"Australasia"}},"sessionId":213516,"currency":"GBP","vendors":[{"id":33,"code":"Opodo","name":"Opodo","logo":"\/publicMedia\/vendors\/opodo.gif","limit":145,"url":"http:\/\/opodo.com","airline":false},{"id":56,"code":"AirlineNetwork","name":"Airline Network","logo":"\/publicMedia\/vendors\/airlinenetwork.gif","limit":145,"url":"http:\/\/www.airline-network.co.uk","airline":false},{"id":59,"code":"Ebookers","name":"ebookers","logo":"\/publicMedia\/vendors\/ebookers.gif","limit":145,"url":"http:\/\/osa.ebookers.com\/","airline":false},{"id":1024,"code":"BestFlights","name":"Best Flights","logo":"\/publicMedia\/vendors\/bestflights.gif","limit":160,"url":"http:\/\/travelmarket.bestflights.com.au","airline":false},{"id":1026,"code":"BritishAirways","name":"British Airways","logo":"\/publicMedia\/vendors\/britishairways.gif","limit":145,"url":"http:\/\/www.britishairways.com","airline":"BA"},{"id":1029,"code":"LastMinute","name":"Lastminute.com","logo":"\/publicMedia\/vendors\/lastminute.gif","limit":145,"url":"http:\/\/lastminute.com","airline":false},{"id":1042,"code":"StaAustralia","name":"STA Australia","logo":"\/publicMedia\/vendors\/staaustralia.gif","limit":145,"url":"http:\/\/statravel.com.au\/","airline":false},{"id":1304,"code":"Southall","name":"Southall Travel","logo":"\/publicMedia\/vendors\/southall.gif","limit":145,"url":"http:\/\/www.southalltravel.co.uk\/index.aspx","airline":false},{"id":1314,"code":"VirginBlue","name":"Virgin Blue","logo":"\/publicMedia\/vendors\/virginblue.gif","limit":145,"url":"http:\/\/bookings.virginblue.com.au","airline":"DJ"},{"id":1330,"code":"TravelComAu","name":"Travel.com.au","logo":"\/publicMedia\/vendors\/travelcomau.gif","limit":145,"url":"http:\/\/travel.com.au","airline":false},{"id":1331,"code":"Travelocity","name":"Travelocity","logo":"\/publicMedia\/vendors\/travelocity.gif","limit":160,"url":"http:\/\/travel.travelocity.com","airline":false},{"id":1359,"code":"JetStar","name":"Jetstar","logo":"\/publicMedia\/vendors\/jetstar.gif","limit":145,"url":"https:\/\/jetstar.com","airline":"JQ"}]}]';
        var searchResponse = tmp.evalJSON();
        searchResponse = searchResponse[0];
        console.log('search');
        console.log(searchResponse);
        */
        
        this.sessionId = searchResponse.sessionId;
        this.currency = searchResponse.currency;
        $A(searchResponse.vendors).each(function(vendorData) {
            var vendor = Object.extend((new Vendor()), vendorData);
            this.getData().addVendor(vendor);
        }.bind(this));
        setTimeout(this.stageResults.bind(this), 5000);
        this.getData().setData("criteria", searchResponse.criteria);
        this.getData().setData("sessionId", this.sessionId);
        this.getData().setData("currency", this.currency);
        this.getData().setData("response", searchResponse);
    },
    stageResults: function() {
        this.timerInterval = setInterval(function() {
            this.timer++;
        }.bind(this), 1000);
        this.fetchResults();
    },
    fetchResults: function() {
        if (this.timeoutHandler) {
            clearTimeout(this.timeoutHandler);
        }
        this.timeoutHandler = setTimeout(function() {
            var url = "/flights/?action=status&id=" + this.sessionId;
            new Ajax.Request(url, {
                onSuccess: this._processStatus.bind(this)
            });
            setTimeout(function() {
                var url = this.resultUrl + "&sessionId=" + this.sessionId
                        + "&currency=" + this.currency;
                new Ajax.Request(url, {
                    onSuccess: this._processResults.bind(this)
                });
            }.bind(this), 1000);
        }.bind(this), 5000);
    },
    _processStatus: function(transport) {
        this.vendorCodes = transport.responseJSON;
        this.getData().getVendors().each(function(vendor) {
            if (this.vendorCodes.length > 0) {
                if (this.vendorCodes.indexOf(vendor.getCode()) != -1) {
                    vendor.setFinished(false);
                    return;
                }
            }
            vendor.setFinished(true);
        }.bind(this));
        if (this.vendorCodes.length == 0) {
            setTimeout(function() {
                this._finishSearchProcess();
            }.bind(this), 10000);
        }
        this.vendorCodes = null;
    },
    _processResults: function(transport) {
        var data = this.getData();
        this.fetchResults();
        var searchResponse = transport.responseJSON[0];
        
        /*
        var tmp = '[{"prices":[{"id":"5807571","vendor":"Opodo","price":"217.40","deepLink":"http:\/\/www.opodo.co.uk\/opodo\/AvailabilityServlet?DISTANCE_UNIT=&RMSCHID=RMSCHID&INC_AIRLINE_1=&TRIP_TYPE=R&B_LOCATION_1=BNE&E_LOCATION_1=SYD&B1_DAY=14&B1_MONTH=200902&B_TIME_TO_PROCESS_1=ANY&B2_DAY=15&B2_MONTH=200902&returnTime=ANY&B_TIME_TO_PROCESS_2=ANY&MAX_CONNECTIONS=&CABIN=E&PREF_AIRLINE_1_DDN_EXISTS=true&AIRLINE_SELECTED_IN_POPUP=&SELECTED_AIRLINE_NAME=&NUM_OF_ADTS=1&NUM_OF_CHD=0&NUM_OF_INFS=0&Int_Id=~FS~SER&DEFAULT_FIELDS=&departureTime=ANY&MULTISTOP_SUBMIT=N&Mkt_Id=1&CMP=uk-aff-fl-000000","details":{"outbound":{"airline":"QF","departingTime":"05:00","arrivingTime":"07:30","stops":"0","duration":"01:30","days":"0"},"inbound":{"airline":null,"departingTime":"06:35","arrivingTime":"07:05","stops":"0","duration":"01:30","days":"0"}}},{"id":"5807540","vendor":"Ebookers","price":"212.40","deepLink":"http:\/\/www.ebookers.com\/partner\/offsitesearch?type=air&triptype=roundtrip&origin=BNE&dest=SYD&adults=1&children=0&departdate=2009-02-14&departspan=Anytime&returndate=2009-02-15&returnspan=Anytime&cabin=C&selectKey=QF521BNESYD0214C_QF544SYDBNE0215C&selectedprice=GBP%7C212.40","details":{"outbound":{"airline":"QF","departingTime":"10:15","arrivingTime":"12:45","stops":"0","duration":"02:30","days":null},"inbound":{"airline":null,"departingTime":"18:05","arrivingTime":"18:35","stops":"0","duration":"00:30","days":null}}},{"id":"5807549","vendor":"LastMinute","price":"96.00","deepLink":"http:\/\/www.lastminute.com\/lmn\/lfe\/flights\/search\/search_helper.jhtml?CATID=85&dc=BNE&cc=NONE&adv=false&lfe_best_price=true&lfe_sub_agent=LMC&lfe_failure_url=\/lmn\/lfe\/flights\/homepage\/homepage.jhtml?CATID=85&_D:lfe_failure_url=&lfe_success_url=\/lmn\/lfe\/flights\/results\/results.jhtml?CATID=85&_D:lfe_success_url=&lfe_delegate_to_ts=false&lfe_currency=GBP&lfe_language=EN&lfe_number_of_results=100&lfe_ext_search=true&new_lfe_locale=en_GB&new_lfe_inc_pub=true&new_lfe_inc_nett=true&new_lfe_inc_lcc=true&new_lfe_inc_charter=true&new_lfe_inc_it=true&new_lfe_inc_trains=true&new_lfe_calendar_success_url=\/lmn\/lfe\/flights\/specialoffers\/flights_calendar_view.jhtml?CATID=85&_D:new_lfe_calendar_success_url==&\/com\/lastminute\/lfe\/dynamo\/handler\/SearchFormHandler.multiSearch=false&_D:\/com\/lastminute\/lfe\/dynamo\/handler\/SearchFormHandler.multiSearch=&lfe_success_tq_url=\/lmn\/lfe\/flights\/results\/tq_results.jhtml?CATID=85&_D:lfe_success_tq_url=&error_url=\/site\/travel\/flights\/flights-search-error.html&lfe_destination=SYD&_D:lfe_calendar_view_only=&0=&lfe_origin=BNE&lfe_dep_day=14&lfe_dep_month=02&lfe_dep_time=0001&lfe_ret_day=15&lfe_ret_month=02&lfe_ret_time=0001&lfe_ticket_type=true&lfe_cabin_class=Y&lfe_num_adult=1&lfe_num_senior=0&lfe_num_child=0&lfe_num_infant=0&lfe_carrier=NONE","details":{"outbound":{"airline":"JQ","departingTime":"12:45","arrivingTime":"15:15","stops":"0","duration":null,"days":null},"inbound":{"airline":null,"departingTime":"11:35","arrivingTime":"12:05","stops":"0","duration":null,"days":null}}},{"id":"5807550","vendor":"LastMinute","price":"215.19","deepLink":"http:\/\/www.lastminute.com\/lmn\/lfe\/flights\/search\/search_helper.jhtml?CATID=85&dc=BNE&cc=NONE&adv=false&lfe_best_price=true&lfe_sub_agent=LMC&lfe_failure_url=\/lmn\/lfe\/flights\/homepage\/homepage.jhtml?CATID=85&_D:lfe_failure_url=&lfe_success_url=\/lmn\/lfe\/flights\/results\/results.jhtml?CATID=85&_D:lfe_success_url=&lfe_delegate_to_ts=false&lfe_currency=GBP&lfe_language=EN&lfe_number_of_results=100&lfe_ext_search=true&new_lfe_locale=en_GB&new_lfe_inc_pub=true&new_lfe_inc_nett=true&new_lfe_inc_lcc=true&new_lfe_inc_charter=true&new_lfe_inc_it=true&new_lfe_inc_trains=true&new_lfe_calendar_success_url=\/lmn\/lfe\/flights\/specialoffers\/flights_calendar_view.jhtml?CATID=85&_D:new_lfe_calendar_success_url==&\/com\/lastminute\/lfe\/dynamo\/handler\/SearchFormHandler.multiSearch=false&_D:\/com\/lastminute\/lfe\/dynamo\/handler\/SearchFormHandler.multiSearch=&lfe_success_tq_url=\/lmn\/lfe\/flights\/results\/tq_results.jhtml?CATID=85&_D:lfe_success_tq_url=&error_url=\/site\/travel\/flights\/flights-search-error.html&lfe_destination=SYD&_D:lfe_calendar_view_only=&0=&lfe_origin=BNE&lfe_dep_day=14&lfe_dep_month=02&lfe_dep_time=0001&lfe_ret_day=15&lfe_ret_month=02&lfe_ret_time=0001&lfe_ticket_type=true&lfe_cabin_class=Y&lfe_num_adult=1&lfe_num_senior=0&lfe_num_child=0&lfe_num_infant=0&lfe_carrier=NONE","details":{"outbound":{"airline":"QF","departingTime":"05:00","arrivingTime":"07:30","stops":"0","duration":null,"days":null},"inbound":{"airline":null,"departingTime":"06:35","arrivingTime":"07:05","stops":"0","duration":null,"days":null}}},{"id":"5807544","vendor":"VirginBlue","price":"101.69","deepLink":"http:\/\/bookings.virginblue.com.au\/skylights\/cgi-bin\/skylights.cgi?event=search&module=SB&page=SEARCH&language=EN&mode=&sid=&ref=&travel=2&from1=BNE&to1=SYD&from2=SYD&to2=BNE&departDay1=14&departMonth1=200902&departDay2=15&departMonth2=200902&ADULT=1&CHILD=0&INFANT=0&dispType=new&toCity1=SYD&toCity2=%3F%3F%3F&departDate1=20090214&departDate2=20090215&numberMarkets=2&CMP=AFC-GTMmetasearch","details":{"outbound":{"airline":"DJ","departingTime":"04:55","arrivingTime":"07:25","stops":null,"duration":"02:30","days":null},"inbound":{"airline":null,"departingTime":"07:00","arrivingTime":"07:25","stops":null,"duration":"00:25","days":null}}},{"id":"5807545","vendor":"JetStar","price":"76.51","deepLink":"https:\/\/jetstar.com\/skylights\/cgi-bin\/skylights.cgi?event=search&module=SB&page=SEARCH&language=EN&mode=&sid=&ref=&jetsaverplus1=0&jetsaverplus2=0&travel=2&from1=BNE&to1=SYD&from2=SYD&to2=BNE&departDay1=14&departMonth1=200902&depart1FlexBy=0101&departDay2=15&departMonth2=200902&depart2FlexBy=0101&ADULT=1&defaultADULT=-1&CHILD=0&defaultCHILD=-1&INFANT=0&defaultINFANT=-1&WCHR=0&SDOG=0&promoCode=&carrier=JQ&toCity1=SYD&toCity2=%3F%3F%3F&departDate1=20090214&departDate2=20090215&numberMarkets=2","details":{"outbound":{"airline":"JQ","departingTime":"12:45","arrivingTime":"15:15","stops":null,"duration":null,"days":null},"inbound":{"airline":null,"departingTime":"11:35","arrivingTime":"12:05","stops":null,"duration":null,"days":null}}}]}]';
        var searchResponse = tmp.evalJSON();
        searchResponse = searchResponse[0];
        console.log('result');
        console.log(searchResponse);
        */
        
        $A(searchResponse.prices).each(function(priceData) {
            var price = Object.extend((new Price()), priceData);
            this.getData().addAirlineCode(price.details.outbound.airline);
            if (price.details.inbound && price.details.inbound.airline) {
                this.getData().addAirlineCode(price.details.inbound.airline);
            }
            this.getData().addPrice(price);
        }.bind(this));
        this._processAirlines();
        if (this.timer > data.getMaxLimit() || data.isFinished()) {
            setTimeout(function () {
                this._finishSearchProcess();
            }.bind(this, 3000));
        }
    },
    _finishSearchProcess: function() {
        try {
            if (this.timerInterval) {
                clearInterval(this.timerInterval);
            }
            if (this.timeoutHandler) {
                clearInterval(this.timeoutHandler);
            }
        } catch (e) {
            dispatchException(e);
        }
        this.timer = 0;
        Page.getInstance().getMatrix().finishSearching();
    },
    _processAirlines: function() {
        var data = Page.getInstance().getFlights().getData();
        if (data.getAirlineCodes().length == 0) {
            Page.getInstance().getMatrix().redraw();
            return;
        }
        var parameters = data.getAirlineCodes().join(",");
        data.clearAirlineCodes();
        new Ajax.Request("/flights/?action=airlines", {
            method: "post",
            postBody: "airlines=" + parameters,
            onSuccess: function(transport) {
                var airlines = transport.responseJSON;
                $A(airlines).each(function(airlineData) {
                    try {
                        var airline = Object.extend((new Airline()), airlineData);
                        Page.getInstance().getFlights().getData().addAirline(airline);
                    } catch (e) {
                        dispatchException(e);
                    }
                }.bind(this));
                console.log('flights start redraw');
                Page.getInstance().getMatrix().redraw();
            },
            onFailure: function(transport) {
                Page.getInstance().getMatrix().redraw();
            }
        });
    }
});
//Page.getInstance().autoSearch();
//Page.getInstance().getFlights().search();