$(document).ready(function(){
    var currency_code   = $("#currency_code").val();
    var currency_symbol = $("#currency_symbol").val();
    var current_city   = "";


    /* Functions */
    function get_amount_with_discount(amount, discount){
        // Return an amount with price reduction
        
        if (discount > 0){
            amount = amount - (amount * discount/100);
        }

        return amount;
    }

    function update_departure_information(data, currency_code, currency_symbol){

        var pricing_details  = data.pricing_details;
        var departure_info   = pricing_details[0];
        var departure_extras = departure_info['extras'];
        var departure_fields = departure_info['fields'];
        var my_own_room_details = data.my_own_room_details;

        // Get the general info for departure
        availability_message = departure_extras.get_availability_message;
        $("#available_spaces").html(availability_message);

        var inca_trail_status = departure_extras.get_inca_trail_status;
        $("#inca_trail_status").html(inca_trail_status);

        var departure_id = departure_info.pk;
        $("#departure_id").val(departure_id);
        $("#departure_id_map").val(departure_id);

        var is_guaranteed = departure_fields.is_guaranteed;
        if (is_guaranteed){
            $('#guaranteed_image').show();
        }else{
            $('#guaranteed_image').hide();
        }

        // Get Local payments for departure
        var local_payments = ''
        for (i=1; i< pricing_details.length; i++){
            if (pricing_details[i]['model'] == 'trips.localpayment'){
                local_payment = pricing_details[i]['fields'];
               // local_payments +=  Math.ceil(local_payment['amount']) + local_payment['currency'] + local_payment['label'] ;
                local_payments += "<dt>" + local_payment['label'] + "</dt>" + "<dd>" + Math.ceil(local_payment['amount']) + "&nbsp;" + local_payment['currency'] + "</dd>" ;
            }
        }
        if (local_payments == ''){
            $('#local_payment_help').hide();
        }else{
            $('#local_payment_help').show();
        }

        // Get the discounted info
        var is_discounted = departure_fields.is_discounted;
        var discount_percent = 0
        if (is_discounted){
            discount_percent = departure_fields.discount_percent;
            $('#discount_percent').html(discount_percent);
            $('#discount_message').show();
        }else{
            $('#discount_message').hide();
        }

        if (my_own_room_details != null){
            var my_own_room_price = my_own_room_details.price;

            if (my_own_room_price != 0){
                my_own_room_price = currency_symbol + my_own_room_price + " " + currency_code.toUpperCase();
                $('#my_own_room').show();
            $('#my_own_room_info').show();
                $('#my_own_room_price').html(my_own_room_price);
            }else{
                $('#my_own_room').hide();
            }
        }

        var pricing_details = data.pricing_details
        var prices = [];
        var price_counter = 0;
        var dominant_price_index = price_counter
        
        // Get Prices
        for (i=1; i < pricing_details.length; i++){
            if (pricing_details[i]['model'] == 'trips.price'){
                prices[price_counter] = pricing_details[i]['fields'];
                price_label = prices[price_counter]['label'];
                // Temporary hack until back end changes any to person
                price_label = price_label.replace('1 Any', '1 Person');
                price_label = price_label.replace('Anys', 'People');
                prices[price_counter]['label'] = price_label;

                if (price_label == '1 Adult' || price_label == '1 Person'){
                    dominant_price_index = price_counter;
                }
                if (price_label == '2 Adults' || price_label == '2 People'){
                    dominant_price_index = price_counter;
                }
                price_counter++;
            }
        }
        // Quick hack if there is only one price
        if (prices.length == 1){
            dominant_price_index = 0;
            $("#list-line").hide();
            }else{
            $("#list-line").show();
        }    

        // Format Prices
        var flight_price = data.flight_price;
        var pricing = '';

        // Show the cities if the departure has changed
        if (data.cities)
            $("#flight_cities").html(data.cities);

        // The following is used to carry flight id to online bookings
        var selected_city = $("#flight_cities :selected");
        var flight_id = selected_city.val();
        current_city = selected_city.text();
        if (flight_id == undefined){ flight_id = 0; }
        if (current_city  == undefined){ current_city = ""; }
        $("#flight_id").val(flight_id);
        $("#flight_city").val(current_city);

        var flight_html = "";
        var price_label = "";
        var acv_asterik = "";

        for (i=0; i < prices.length; i++){
            price = prices[i];

            if ( i == dominant_price_index){
                prefix = "<dt id='dominant'>";
                postfix = "</dt>";
            }else{
                prefix = "<dd class='pricing-micro'>";
                postfix = "</dd>";
            }

            amount = Math.ceil(get_amount_with_discount(price[currency_code], discount_percent));

            if (flight_price > 0)
            {
                acv_asterik = "*";
                amount += flight_price;
                amount = parseFloat(amount).toFixed(2);
                $("#leaving").show();
                $("#flight-include").show();
                $("#flight-exclude").hide();

                // Checks if the acv_pricing_box functions exists, otherwise fails gracefully
                if (typeof(acv_pricing_box) != "undefined") 
                {
                    flight_html = acv_pricing_box(current_city);
                }
            }
            else
            {
                price_label = "&nbsp;<span class='micro break'>( " + price['label'] + "&nbsp;)</span>";
                $("#leaving").hide();
                $("#flight-include").hide();
                $("#flight-exclude").show();
            }
                                        
            pricing += prefix + "<span class='micro currency'>" + currency_symbol +"</span>" + amount + "&nbsp;" + "<span class='micro'>" + currency_code.toUpperCase() + acv_asterik + "</span>" + price_label + flight_html + postfix;
        }
         
        $("#departure_price").html(pricing);

        if (local_payments){
            $("#local_payments").html(local_payments);
            $("#local_payments").show();
        }else{
            $("#local_payments").hide();
        }

    }
        
    function update_departure_information_ajax(currency_code, currency_symbol, flight_id, live){
        // We are first going to update departure info from cache then from compass
        // If live, we want from compass, else we want from cache
        // This helps when it takes a while to get the updated version
        // This helps when it takes a while to get the updated version
        
        // Sanity check: if not true, then anything else is false
        if(live != 'true'){
            live = 'false';
        }

        // Get Departure criteria
        if(!currency_code){ 
            currency_code = 'cad';
        }else{
            currency_code = currency_code.toLowerCase();
        }
        var dossier_code = $("#dossier_code").val();
        var start_date = $("#id_departure_date").val();
        var room_code = $("#id_room").val();

        if (room_code == undefined){ room_code = ""; }
        if (start_date  == undefined){ start_date = ""; }

        // Since this is the first grab of departure information, we don't want to let a user book until
        // at least a cached departure is loaded
        if(live == 'false'){
            var spinning_wheel = '<img src="' + MEDIA_URL + 'static/images/small-loading.gif" />';
            $("#book_now_button").hide();
            $("#available_spaces").html(spinning_wheel);
            $("#departure_price").html(spinning_wheel);
        }

        // Let's get the departure info
        $.getJSON("/trips/departure", 
            {
                'dossier_code': dossier_code,
                'start_date': start_date,
                'room_code': room_code,
                'currency':currency_code,
                'live': live,
                'ajax': 'true',
                'flight_id': flight_id,
                'selected_city': current_city
            }, 
            function(data){                
                update_departure_information(data, currency_code, currency_symbol);

                // Once Updated with current info try and get live info
                if(live == 'false'){
                    update_departure_information_ajax(currency_code, currency_symbol, flight_id, 'true');
                }
                var availability_status  = data.pricing_details[0].extras.get_availability_message;
                if (availability_status != 'Sold Out'){
                    $("#book_now_button").show();
                }
            }
        );
    }

    function update_departures_dropdown(){
        var dossier_code = $("#dossier_code").val();
        var room_code    = $("#id_room").val();
        var year         = $("#year").val();
        var departure_id = $("#departure_id").val();

        if (room_code == undefined){ room_code = ""; }

        $("#id_departure_date").load(
            "/trips/trip/departure_dates_options/", 
            {
                "dossier_code":dossier_code,
                "year": year,
                "room_code": room_code,
                "departure_id": departure_id 
            }
        );
    }

    function update_dates_and_pricing_list(){
        var dossier_code = $("#dossier_code").val();
        var year         = $("#year").val();
        var start_date   = $("#id_departure_date").val();
        var room_code    = $("#id_pricing_room").val();
        if (room_code == undefined){ room_code = ""; }
        if (start_date  == undefined){ start_date = ""; }

        var spinning_wheel = '<img src="' + MEDIA_URL + 'static/images/small-loading.gif" />';
        $("#dates_and_pricing_list").html(spinning_wheel);

        $("#dates_and_pricing_list").load(
            "/trips/trip/dates_and_pricing/", 
            {
                "dossier_code":dossier_code,
                "year": year,
                "room_code":room_code 
            }
        );
    }

    function update_wishlist(){
        $('#user_wishlist').load("/profiles/wishlist");
    }

    function add_trip_to_wishlist(){
        var trip_id = $("#trip_id").val();
        
        $.getJSON("/profiles/add_to_wishlist", 
            {
                'trip_id': trip_id,
                'ajax': 'true'
            }, 
            function(data){
                if (data.OK) {
                    $("#add_to_wishlist").hide();
                    $("#remove_from_wishlist").show();
                    update_wishlist();
                    jQuery.facebox(data.OK);
                }else{
                    jQuery.facebox(data.FAIL);
                }
            }
        );
    }

    function view_hotels_and_transfers_info(currency_code){
        var departure_id = $("#departure_id").val();
        var parameters   = { 
            'id': departure_id, 
            'currency': currency_code,
            'ajax': 'true'
        };

        $.get("/trips/hotels-transfers/", parameters,
            function(data){
                $.facebox(data);
            }
        );
    }

    function remove_trip_from_wishlist(){
        var trip_id = $("#trip_id").val();
        
        $.getJSON("/profiles/remove_from_wishlist", 
            {
                'trip_id': trip_id,
                'ajax': 'true'
            }, 
            function(data){
                if (data.OK) {
                    $("#remove_from_wishlist").hide();
                    $("#add_to_wishlist").show();
                    update_wishlist();
                    $.facebox(data.OK);
                }else{
                    $.facebox(data.FAIL);
                }
            }
        );
    }

    /* Events */
    $("#add_to_wishlist").click(function(){add_trip_to_wishlist();});
    $("#remove_from_wishlist").click(function(){remove_trip_from_wishlist();});

    $("#flight_cities").change(function(){
        var selected = $("#flight_cities option:selected");
        var flight_id = selected.val();
        current_city = selected.text();
        update_departure_information_ajax(currency_code, currency_symbol, flight_id, 'false');
    });

    $("#id_departure_date, #id_room").change(function(){
        update_departure_information_ajax(currency_code, currency_symbol, 0, 'false');
    });

    $("#id_room").change(function(){
        update_departures_dropdown();
    });

    $("#id_pricing_room").change(function(){
        update_dates_and_pricing_list();
    });

    $("#brief_itinerary_link").click(function(){ 
        $("#detailed_itinerary").hide(
            "normal", 
            function(){ 
                $("#brief_itinerary").show("normal"); 
            }
        );
        $('#itinerary_title').html("Brief Itinerary");
    });

    $("#detailed_itinerary_link").click(function(){ 
        $("#brief_itinerary").hide(
            "normal", 
            function(){ 
                $("#detailed_itinerary").show("normal"); 
            }
        );
        $('#itinerary_title').html("Detail Itinerary");
    });

    // Intialize page
    //

    // Itineraries
    if ($("#in_wishlist").val() == 'True'){
        $("#remove_from_wishlist").show()
        $("#add_to_wishlist").hide()
    }else{
        $("#add_to_wishlist").show()
        $("#remove_from_wishlist").hide()
    }

    $("#detailed_itinerary").hide();
    $('#itinerary_title').html("Brief Itinerary");

    update_departure_information_ajax(currency_code, currency_symbol, 0);
    update_dates_and_pricing_list();
    update_wishlist();

    $('#dest-tab-cxontent').tabs({ fxFade: true, fxSpeed: 'fast' });

    $("#hotels_and_transfers").click(function(e){
        e.preventDefault();
        view_hotels_and_transfers_info(currency_code=currency_code);
    });

    $("#dest-guide").carousel({'slideSpeed': "slow", 'dispItems': 4 , 'nextBtn': '<img src="/media-server/static/images/small-arrow-right.png" alt="next" />', 'prevBtn': '<img src="/media-server/static/images/small-arrow-left.png" alt="prev" />'});
});
