var FlForm = Class.create({
    _clientName: '',
    _firstTime: true,
    initialize: function() {
        this._clientName = getQueryVariable("client");
        
        if (document.getElementById('liInternational') != null && document.getElementById('liDomestic') != null) {
            changeClientLink();
        }
        
        this.prepare();
        this.createLocationElements();
        setTimeout(function() {
            Event.observe("search_btn", "click", this.startSearch.bindAsEventListener(this));
        }.bind(this), 1000);
        this.returnDateElements = ["returnDay", "returnMonth", "arrtime", "bottomCalImage",
                                   "arrivelTimeSign", "returnSign", "return_date", "returnDisappear", "timeDisappear"];
        this._firstTime = false;
    },
    startSearch: function(event) {
        page.search();
    },
    createLocationElements: function() {
        var a = new Affiliate();
        this.createLocationElement("departure",   a.getDepartureType());
        this.createLocationElement("destination", a.getDestinationType());
    },
    createLocationElement: function(location, type) {
        var uid = location + "Airport";
        if (type == "autocomplete") {
            var input = new Element("input", {id: uid,type:"text", name:uid, tabIndex: ((location == "departure") ? 1 : 2)})
                      .addClassName("text location");
            var autocompleteBlock = new Element("div", {id: location + "Autocomplete"}).hide()
                                  .addClassName("auto_complete");

            var primaryValue = $(location + "_element").getAttribute("primary") || "";
            input.value = primaryValue;

            $(location + "_element").parentNode.appendChild(input);
            $(location + "_element").parentNode.appendChild(autocompleteBlock);
            $(location + "_element").parentNode.removeChild($(location + "_element"));

            if (this._firstTime && (this._clientName == 'canberraComAu' || this._clientName == 'newcastleComAu' || this._clientName == 'perthComAu')) {
                var aj = 'new Ajax.Autocompleter(location+"Airport", location+"Autocomplete", "./?action=location.autocomplete&direction=" + location + "&client=' + this._clientName + '2", {paramName: "query", afterUpdateElement: function (text, li) {}});';
                page.setClientName(this._clientName + '2');
            } else {
                var aj = 'new Ajax.Autocompleter(location+"Airport", location+"Autocomplete", "./?action=location.autocomplete&direction=" + location + "&client=" + getQueryVariable("client"), {paramName: "query", afterUpdateElement: function (text, li) {}});';            
            }
            
            eval(location + "Ajax = " + aj);
            eval('this.' + location + "Ajax = " + location + "Ajax");
            Event.observe(location+"Airport", "click", function(e) {
                Event.element(e).select();
            });
            // Initializing requests
        } else if(type == "select") {
            var select = elem("select", {id:uid,name:uid, tabIndex: ((location == "departure") ? 1 : 2)});
            Element.addClassName(select, "text location");
            $(location + "_element").parentNode.appendChild(select);
            $(location + "_element").parentNode.removeChild($(location + "_element"));

            select.appendChild(new Option("Loading, please wait"));
            select.disabled = true;

            // Initializing selects
            var url    = window.location.href.substr(0, window.location.href.indexOf("?"));
            url += "?action=location.select&direction=" + location + "&client=" + getQueryVariable("client");
            new Ajax.Request(url, {method: "get", onSuccess: this.createOptionList.bind(this, location)});
        } else if(type == "hidden") {
            var hidden = elem("input", {id:uid,type:"hidden",value:$(location + "_element").value,name:uid, tabIndex: ((location == "departure") ? 1 : 2)});
            $(location + "_element").parentNode.appendChild(hidden);
            $(location + "_element").parentNode.removeChild($(location + "_element"));
        }
    },
    changeClient: function(client) {
        var a = new Affiliate();
        
        $('departureAirport').value   = 'Origin';
        $('destinationAirport').value = 'Destination';
        
        this.changeLocationElement4Client("departure",   a.getDepartureType(), client);
        this.changeLocationElement4Client("destination", a.getDestinationType(), client);
    },
    changeLocationElement4Client: function(location, type, client) {
        var uid = location + "Airport";
        if (type == "autocomplete") {
            if (location == 'departure') {
                departureAjax.url = "./?action=location.autocomplete&direction=" + location + "&client=" + client;
            }
            if (location == 'destination') {
                destinationAjax.url = "./?action=location.autocomplete&direction=" + location + "&client=" + client;
            }
            
            page.setClientName(client); 
            
//            Event.stopObserving("search_btn", 'click', FlForm.startSearch);
//            Event.stopObserving("search_btn", 'click', FlForm.startSearch);
            // Initializing requests
        } else if(type == "select") {
            var select = elem("select", {id:uid,name:uid, tabIndex: ((location == "departure") ? 1 : 2)});
            Element.addClassName(select, "text location");
            $(location + "_element").parentNode.appendChild(select);
            $(location + "_element").parentNode.removeChild($(location + "_element"));

            select.appendChild(new Option("Loading, please wait"));
            select.disabled = true;

            // Initializing selects
            var url    = window.location.href.substr(0, window.location.href.indexOf("?"));
            url += "?action=location.select&direction=" + location + "&client=" + getQueryVariable("client");
            new Ajax.Request(url, {method: "get", onSuccess: this.createOptionList.bind(this, location)});
        } else if(type == "hidden") {
            var hidden = elem("input", {id:uid,type:"hidden",value:$(location + "_element").value,name:uid, tabIndex: ((location == "departure") ? 1 : 2)});
            $(location + "_element").parentNode.appendChild(hidden);
            $(location + "_element").parentNode.removeChild($(location + "_element"));
        }
    },
    prepare: function() {
        if (! document.getElementById("departureMonth")) {
            return
        }
        this.prepareDates();
        this.citiesFromTo("fromCities", "cityTo", "departureAirport", "destinationAirport", "toCities");
        this.citiesFromTo("toCities", "cityFrom", "destinationAirport", "departureAirport", "fromCities");

        Event.observe("tripTypeR", "click", this.showReturnDate);
        Event.observe("tripType0", "click", this.hideReturnDate);
    },
    citiesFromTo: function(idContainer, attrCity, idLink, idUnlink, idContainerUnlink) {
        if ($(idContainer)) {
            $A($(idContainer).getElementsByTagName("input")).each(function(input){
                Event.observe(input, "click", function(event) {
                   var element = Event.element(event);
                   $(idLink).value = element.value;
                   $(idUnlink).value = $(idContainer).getAttribute(attrCity);
                   $A($(idContainerUnlink).getElementsByTagName("input")).each(function(input){
                        input.checked = false;
                   });
                });
            });
        }
    },
    hideReturnDate: function() {
        $A(form.returnDateElements).each(function (element) {
            if ($(element)) {
                Element.hide(element);
            }
        });
    },
    showReturnDate: function() {
        $A(form.returnDateElements).each(function (element) {
            if ($(element)) {
                Element.show(element);
            }
        });
    },
    prepareDates: function () {
        this.buildDates();
    },
    buildDates: function () {
        var months = {'Jan':0,'Feb':1,'Mar':2,'Apr':3,'May':4,'Jun':5,'Jul':6,'Aug':7,'Sep':8,'Oct':9,'Nov':10,'Dec':11};
        var date = new Date();

        var departureDate = new Date();
        var returnDate = new Date();

        //departureDate.setDate(departureDate.getDate()+2);
        //returnDate.setTime(departureDate.getTime()+ parseInt(14*60*60*24 + "000"));



        if ($('departure_date') && $('return_date')) {
            var currentDepartureDate = $('departure_date').value;
            var currentDepartureDateArray = currentDepartureDate.split(' ');
            departureDate.setFullYear(currentDepartureDateArray[2]*1);
            departureDate.setMonth(eval('months.' + currentDepartureDateArray[1])*1);
            departureDate.setDate(currentDepartureDateArray[0]*1);
            var currentReturnDate = $('return_date').value;
            var currentReturnDateArray = currentReturnDate.split(' ');
            returnDate.setFullYear(currentReturnDateArray[2]*1);
            returnDate.setMonth(eval('months.' + currentReturnDateArray[1])*1);
            returnDate.setDate(currentReturnDateArray[0]*1);
        }
        else {
            departureDate.setDate(departureDate.getDate()+2);
            returnDate.setTime(departureDate.getTime()+ parseInt(14*60*60*24 + "000"));
        }


        // Hack fo IE
        departureMonthElem = $A($$('select[id=departureMonth]')).first();
        returnMonthElem = $A($$('select[id=returnMonth]')).first();
        departureDayElem = $A($$('select[id=departureDay]')).first();
        returnDayElem = $A($$('select[id=returnDay]')).first();

        departureMonthElem.value = departureDate.getFullYear()+""+((departureDate.getMonth()+1) < 10 ? "0"+(departureDate.getMonth()+1) : (departureDate.getMonth()+1));
        returnMonthElem.value = returnDate.getFullYear()+""+((returnDate.getMonth()+1) < 10 ? "0"+(returnDate.getMonth()+1) : (returnDate.getMonth()+1));

        for(var i = 1; i < 32; i++) {
            var departureLength = departureDayElem.options.length;
            departureDayElem.options[departureLength] = new Option((i < 10 ? ("0"+i) : i), i);
            if(i == departureDate.getDate()) {
                departureDayElem.options[departureLength].selected = true;
            }

            var returnLength = returnDayElem.options.length;

            returnDayElem.options[returnLength] = new Option((i < 10 ? ("0"+i) : i), i);
            if(i == returnDate.getDate()) {
                returnDayElem.options[returnLength].selected = true;
            }
        }

        // Best fare helpers
        if (document.getElementById("cachedRecord") != null) {
            departureDayElem.value   = $('departureDayRecord').firstChild.nodeValue;
            returnDayElem.value      = $('destinationDayRecord').firstChild.nodeValue;
            departureMonthElem.value = $('departureDateRecord').firstChild.nodeValue;
            returnMonthElem.value    = $('destinationDateRecord').firstChild.nodeValue;
            setTimeout(function() {
                $('departureAirport').value =  $("departureRecord").firstChild.nodeValue;
            }, 500);
        }
    },
    checkDate: function () {
        // Hack fo IE
        departureMonthElem = $A($$('select[id=departureMonth]')).first();
        returnMonthElem = $A($$('select[id=returnMonth]')).first();
        departureDayElem = $A($$('select[id=departureDay]')).first();
        returnDayElem = $A($$('select[id=returnDay]')).first();

        var returnMonth = returnMonthElem.value > 9 ? returnMonthElem.value : "0"+returnMonthElem.value;
        var returnDay   = returnDayElem.value > 9 ? returnDayElem.value : "0"+returnDayElem.value;

        var departureDay     = departureDayElem.value > 9 ? departureDayElem.value : "0"+departureDayElem.value;
        var departureMonth   = departureMonthElem.value > 9 ? departureMonthElem.value : "0"+departureMonthElem.value;

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

        if(arriveTime <= departTime) {
            $("incorrectdate").style.display = "";
            return false;
        }
        $("incorrectdate").style.display = "none";
        return true;
    },
    observeSearch: function() {
        if(typeof(this.counter) == "undefined") {
            this.counter = 0;
        }
        this.counter++;
        if(this.counter >= 2) {
            Event.observe("search_btn", "click", flights.search);
        }
    },
    createOptionList: function(location, response) {
        var size = 0;
        var selected = false;
        var root     = response.responseXML.getElementsByTagName("list")[0];
        var i        = 0;
        var select   = $(location + "Airport");

        select.options.length = 0;
        for (var i = 0, length = select.length; i < length; i++) {
            select.options[i].remove();
        }
        while (node = root.childNodes[i]) {
            i++;
            if (node.nodeType == 3) {
                continue;
            }
             selected = ((attributeValue = node.getAttribute("selected")) != null) ? attributeValue : false;
             var k = 0;
             var name = false;
             var iata = false;
             while (dataNode = node.childNodes[k]) {
                 k++;
                 if (dataNode.nodeType == 3) {
                     continue;
                 }
                 switch (dataNode.nodeName.toLowerCase()) {
                     case "name":
                         name = dataNode.firstChild.nodeValue;
                         break;
                     case "iata":
                         iata = dataNode.firstChild.nodeValue;
                         break;
                     default:break;
                 }
             }
             if (name != false && iata != false) {
                 var option = elem("option", {value: iata}, false, name);
                 select.appendChild(option);
                 if (selected) {
                     option.selected = true;
                 }
             }
             size++;
        }
        select.disabled = false;
    }
});