/**
 * Travel Voucher class used for AJAX and UI functionality in the Booking Flow Pages 
 * Booking Flow.
 *
 * @author John Faircloth
 */
 
var TravelVouchers = new function() {
    this.emptyText = 'voucher #';
    this.vouchersNeeded = 0;
    this.hasError = false;
    this.errorMessage = '';
    this.isPhaseTwo = false;
    this.replaceOptions = '';
    this.filteredOrginCities = '';
    this.filteredDestCities = '';
    this.updateVoucherInputs = function() {
        var paxCount = $('#numpass').val();
        
        if ($('#oneWay').attr('checked')) {
            var multiplier = 1;
        } else {
            var multiplier = 2;
        }
        
        this.vouchersNeeded = paxCount * multiplier;
        
        $(".text-box").each(function (i) {
           if(i < TravelVouchers.vouchersNeeded) {
               $(this).show();
               if ($(this).val() == TravelVouchers.emptyText) {
                    $(this).addClass("voucher-empty");
               }
               $(this).removeClass("voucher-error");
           } else {
               $(this).hide();
               $(this).val(TravelVouchers.emptyText);
               $(this).removeClass("vouher-error");
               $(this).addClass("voucher-empty");
               
           }
        });
    };
    
    this.validateVouchers = function() {
        
        // first check to see if the have the right number of vouchers to proceed
        $(".text-box").each(function (i) {
            if(i < TravelVouchers.vouchersNeeded) {
                if ($(this).val() == '' || $(this).val() == TravelVouchers.emptyText) {
                    $(this).removeClass('voucher-empty');
                    $(this).addClass('voucher-error');
                    TravelVouchers.hasError = true;
                    TravelVouchers.errorMessage = 'Please populate all voucher fields with vaild vouchers.'
                }
            }
        });
        
        if (this.hasError) {
            this.displayError();
        } else {
            
            var params = $('#input_form').serialize();
            $.ajax({
                type: 'POST',
                url: '/aaRes/aaRes_validateVouchers.php',
                data: params,
                dataType: 'json',
                success: function(r){
                    //alert(r);
                    //var response = JSON.parse(r);
                    var response = r;
                   // console.log(response);
                    
                    if (response.error == true) {
                        
                        for(var i=0; i < response.invalidVouchers.length; i++) {
                            $('#voucher_'+response.invalidVouchers[i]).addClass('voucher-error');
                        }
                        TravelVouchers.displayError(response.errorMessage, response.showContinue);
                    } else {
                        $('#bookType').val(response.bktype);
                        TravelVouchers.filterCities(response.replaceOptions, response.orginCityFilter, response.destCityFilter);
                        TravelVouchers.filterCalendars(response.limitFlights);
                        TravelVouchers.phaseTwo();
                    }
                    
                },
                error: function(x, status, error){
                    TravelVouchers.displayError(ajax_general_error);
                }
            });
        }
    };
    
    this.filterCities = function(replaceOptions, orginCities, destCities) {
        this.replaceOptions = replaceOptions;
        $('#replaceOptions').val(replaceOptions);
        if (this.replaceOptions && this.replaceOptions.length > 0) {
            var parts = this.replaceOptions.split(',');
            var subparts = null;
            var map = new Array();
            var selectOrgin = false;
            var selectDest = false
            for(var i = 0; i < parts.length; i++) {
                subparts =  parts[i].split('#');
                $("#depcity option[value='"+subparts[0]+"']").val(subparts[1]);    
                $("#retcity option[value='"+subparts[0]+"']").val(subparts[1]);    
            }
            
        }
        
        
        this.filteredOrginCities = orginCities;
        $('#orginCityFilter').val(orginCities);
        
        if (this.filteredOrginCities && this.filteredOrginCities.length > 0) {
            
            $('#depcity option').each(function() {
                if($(this).val() != '') {
                    if(TravelVouchers.filteredOrginCities.search($(this).val()) == -1) {
                        $(this).remove();
                    }    
                }
            });
        }
        
        this.filteredDestCities = destCities;
        $('#destCityFilter').val(destCities);
        
        if (this.filteredDestCities && this.filteredDestCities.length > 0) {
            $('#retcity option').each(function() {
                if($(this).val() != '') {
                    if(TravelVouchers.filteredDestCities.search($(this).val()) == -1) {
                        $(this).remove();
                    }    
                }
            }); 
        }
        
    };
    
    this.filterCalendars = function(limitFlights) {
        if(limitFlights) {
            $('#limitFlights').val(limitFlights);
        }
    };
    
    this.phaseTwo = function() {
        $('#phaseTwo').val(1);
        this.isPhaseTwo = true;
        $('#flight-selection').show();
        $(".text-box").attr("readonly", "true");
        $(".text-box").removeClass('voucher-error');
    };
    
    this.phaseOne = function() {
        $('#phaseTwo').val(0);
        this.isPhaseTwo = false;
        $('#depcity').val('');
        $('#retcity').val('');
        subForm();
    };
    
    this.displayError = function(str, showContinue) {
        if (!str) str = this.errorMessage;
        
        if (showContinue) {
            $('#control_continue').show();
            $('#control_close').hide();
        } else{
            $('#control_continue').hide();
            $('#control_close').show();
        }
        $('#error-window-title').text('Error Occured!');  
        $('#error-window-text').text(str);
        this.errorMessage = '';
        this.hasError = false;
        $('#error_window').center({width:895, height:780});
        $('#error_window').show();
          
    };
    
    this.removeError = function() { 
         $('#error_window').hide();
        
    };
    
    this.updateVoucherTitles = function() {
        $(".text-box").each(function (i) {
            TravelVouchers.updateVoucherTitle(this);
        });
    };
    
    this.updateVoucherTitle = function(o) {
        if ($(o).val() == "") {
            $(o).addClass("voucher-empty");
            $(o).val(this.emptyText);
        } 
    }
}

/**
 * Add JQuery events after page load.
 */
$(function(){
    if ($('#redeemVoucher').val() != 1) {
        return;
    }
    
    /**
     * Event to update UI to show change date options.
     *
     * @return false
     */
     TravelVouchers.updateVoucherInputs();
     TravelVouchers.updateVoucherTitles();
     TravelVouchers.filterCities($('#replaceOptions').val(), $('#orginCityFilter').val(), $('#destCityFilter').val());
     
     if ($('#phaseTwo').val() == 1) {
        TravelVouchers.phaseTwo();
     }
     $('.text-box').blur(function() { 
        if ($(this).val() == '') { 
            $(this).addClass("voucher-empty");
            $(this).val(TravelVouchers.emptyText); 
        } 
     }); 
     
     $('.text-box').focus(function() { 
        $(this).removeClass("voucher-error");
        if ($(this).val() == TravelVouchers.emptyText) { 
            $(this).val(''); 
            $(this).removeClass("voucher-empty");
            
            TravelVouchers.removeError();
        } 
     }); 
     
     $('#numpass').change(function() {
         if (TravelVouchers.isPhaseTwo) {
            TravelVouchers.phaseOne();
         } else {
            TravelVouchers.removeError();
            TravelVouchers.updateVoucherInputs();
         }
     });
     
     $('#oneWay, #oneWay_no').click(function() {
         if (TravelVouchers.isPhaseTwo) {
            TravelVouchers.phaseOne();
         } else {
            TravelVouchers.removeError();
            TravelVouchers.updateVoucherInputs();
         }
     });
     
     $('#numpass').blur(function() {
         TravelVouchers.updateVoucherInputs();
     });
     
     $('#search-flights').click(function() {
         if (!TravelVouchers.isPhaseTwo) {
          TravelVouchers.removeError();
          TravelVouchers.validateVouchers();
         }
     });
     
     $('#close-window, #cancel-window').click(function() {
          TravelVouchers.removeError();
     });
     
     $('#continue-window').click(function() {
          location.href='/aaRes/aaBookingFlow_1.php'; 
     });
});