(function ($) {

    /**
     * The recommended way for producing HTML markup through JavaScript is to write
     * theming functions. These are similiar to the theming functions that you might
     * know from 'phptemplate' (the default PHP templating engine used by most
     * Drupal themes including Omega). JavaScript theme functions accept arguments
     * and can be overriden by sub-themes.
     *
     * In most cases, there is no good reason to NOT wrap your markup producing
     * JavaScript in a theme function.
     */

    Drupal.behaviors.fernweh_messages_action = {
        attach: function (context, settings) {
            // mCustomScroller initialization
            if ($(".modal-scroll").length > 0) {
                $(".modal-scroll").mCustomScrollbar({
                    scrollButtons: {enable: true},
                    theme: "dark-thick"
                });
            }

            $('.messages').each(function () {
                var $this = $(this);
                if (!$this.hasClass("error")) { // Auto-close only if there is no error
                    setTimeout(function () {
                        $this.slideUp("slow", function () {
                            $(this).html('');
                        });
                    }, 5000);  //hide error messages after 5 seconds (only if it not error)
                }
            });
            // Bind dismiss error message only once
            $(".message_dismiss_link").once().click(function (e) {
                e.preventDefault();
                $(this).parent().slideUp("slow", function () {
                    $(this).html('');
                });
            });

            // Money field validation
            if ($("input.cost-inr").length > 0) {

                $("input.cost-inr").attr("autocomplete", "off")
                $("input.cost-inr").on("keyup", function () {
                    var valid = /^\d{0,14}(\.\d{0,2})?$/.test(this.value),
                            val = this.value;
                    if (!valid) {
                        this.value = val.substring(0, val.length - 1);
                    }
                });
            }

            // Statuses comment
            if ($('#commerce-product-ui-product-form').length > 0) {
                $('#commerce-product-ui-product-form').submit(function (e) {
                    if ($(".statuses-item").length > 0) {
                        var $items = [];
                        $(".statuses-item").each(function (e) {
                            var id = $(this).attr('id');
                            var statuses_id = id.match(/\d+/);
                            $items.push(statuses_id);
                        });
                        $('#fernweh_statuses_hidden_ids').val($items.join(','))
                    }
                });
            }

            // Service Type change
            if ($('input[name*=field_lead_service_type]').length > 0) {

                var checkbox_service_type = $('input[name*=field_lead_service_type]:checked');
                var idVal = checkbox_service_type.attr("id");
                handleAddServiceChange(checkbox_service_type.val(), idVal, false);

                $('input[name*=field_lead_service_type]').change(function () {
                    var value = $('input[name*=field_lead_service_type]:checked').val();
                    var idVal = $(this).attr("id");
                    handleAddServiceChange(value, idVal, true);
                });
            }

            function handleAddServiceChange(value, idVal, empty) {

                var label = ($("label[for='" + idVal + "']").text());
                $('div.group-lead-service-flight.field-group-div h3').find('span').text(label);
                var $to = $('input[name*=field_lead_service_flight_to]');
                var $to_id = $to.attr('id');
                var $to_label = $("label[for='" + $to_id + "']");
                var $to_wrapper = $to.closest('.field-type-text');
                var $from = $('input[name*=field_lead_service_flight_from]');
                var $from_id = $from.attr('id');
                var $from_label = $("label[for='" + $from_id + "']");
                var $from_wrapper = $from.closest('.field-type-text');
                var $pnr = $('input[name*=field_lead_service_flight_pnr]');
                var $pnr_id = $pnr.attr('id');
                var $pnr_label = $("label[for='" + $pnr_id + "']");
                var $pnr_wrapper = $pnr.closest('.field-type-text');
                var $free_text = $('textarea[name*=field_lead_free_text]');
                var $free_text_id = $free_text.attr('id');
                var $free_text_label = $("label[for='" + $free_text_id + "']");
                var $free_text_wrapper = $free_text.closest('.field-type-text-long');
                var $cost = $('input[name*=field_lead_service_flight_cost]');


                var $current_url = window.location.href;
                var $fragment = $current_url.split('/');
                if (empty) {
                    $free_text.val('');
                    $pnr.val('');
                    $from.val('');
                    $to.val('');
                    $cost.val('');
                }
                var $required_indicator = '<span class="form-required" title="This field is required.">*</span>';

                switch (value) {
                    case "Flight":
                    case "railway":
                        $to.attr("required", 'required');
                        $to_label.text('To').append($required_indicator);
                        $to_wrapper.show();
                        $from.attr("required", 'required');
                        $from_label.text('From').append($required_indicator);
                        $from_wrapper.show();
                        $pnr_label.text('PNR');
                        $pnr_wrapper.show();
                        $free_text_wrapper.hide();
                        $('#edit-field-lead-ser-flight-traveldate label').html('Date<span class="form-required" title="This field is required.">*</span>');
                        $('.field-name-field-lead-service-checkout-date').hide();
                        break;
                    case "airport_transfer":
                    case "miscellaneous":
                        $to.removeAttr('required');
                        $to_wrapper.hide();
                        $to_label.find('span').remove();
                        $from.removeAttr("required");
                        $from_wrapper.hide();
                        $from_label.find('span').remove();
                        $pnr_label.text('Reference Number');
                        $pnr_wrapper.show();
                        $free_text_wrapper.show();
                        $('#edit-field-lead-ser-flight-traveldate label').html('Date<span class="form-required" title="This field is required.">*</span>');
                        $('.field-name-field-lead-service-checkout-date').hide();
                        break;
                    case "hotel":
                        $to.removeAttr('required');
                        $to_wrapper.hide();
                        $from.attr("required", 'required');
                        $from_label.text('Hotel Name').append($required_indicator);
                        $from_wrapper.show();
                        $pnr_label.text('Reference Number');
                        $pnr_wrapper.show();
                        $free_text_wrapper.hide();
                        $('#edit-field-lead-ser-flight-traveldate label').html('Check-in Date<span class="form-required" title="This field is required.">*</span>');
                        $('#edit-field-lead-service-checkout-date label span.form-required').remove();
                        $('#edit-field-lead-service-checkout-date label').html('Check-out Date<span class="form-required" title="This field is required.">*</span>');
                        $('.field-name-field-lead-service-checkout-date').show();
                        break;
                    case "insurance":
                        $to.removeAttr("required");
                        $to_wrapper.hide();
                        $to_label.find('span').remove();
                        $from.attr("required", 'required');
                        $from_label.text('Sector').append($required_indicator);
                        $from_wrapper.show();
                        $from_label.find('span').remove();
                        $pnr_wrapper.hide();
                        $pnr_label.text('Reference Number');
                        $free_text_wrapper.hide();
                        $('#edit-field-lead-ser-flight-traveldate label').html('Date<span class="form-required" title="This field is required.">*</span>');
                        $('.field-name-field-lead-service-checkout-date').hide();
                        break;
                }
            }

            // Form cancel button confirmation
            if ($('.form-actions a.fn-btn-cancel').length > 0) {
                $('.form-actions a.fn-btn-cancel').on('click', function (e) {
                    var response = confirm("Are you sure you want to leave this page?");
                    if (response == true) {
                        return true;
                    }
                    else {
                        e.preventDefault();
                    }
                });
            }
            // Confirm box if comments added was not saved
            $('.form-actions #edit-submit:not(".processed"), .view-id-order_details .view-header a:not(".processed")').addClass('processed').on('click', function (e) {
                if ($('#edit-fbss-status').val().length > 0) {
                    var response = confirm("Your comments have not been added. Are you sure you want to continue?");
                    if (response == true) {
                        return true;
                    }
                    else {
                        e.preventDefault();
                    }
                }
            });



            // Lead status change make attachment required
//            if ($('select[name*=field_lead_status]').length > 0) {
//
//                $('select[name*=field_lead_status]').change(function() {
//                    var $required_indicator = '<span class="form-required" title="This field is required.">*</span>';
//                    var $attch = $('input[name*=field_lead_service_flight_attche]');
//                    var $attch_id = $attch.attr('id');
//                    var $attch_label = $attch.closest('.form-item').find('label');
//                    if ($(this).val() == 47) { // Wow
//                        $attch_label.append($required_indicator);
//                        $attch.attr("required", "required")
//                    } else {
//                        $attch_label.find('span').remove();
//                        $attch.removeAttr("required");
//                    }
//                });
//            }


            // Date field restrict to present and future
//            if($( "#edit-field-lead-closing-date-und-0-value-datepicker-popup-0").length>0){
//                var dates = $( "#edit-field-lead-closing-date-und-0-value-datepicker-popup-0" ).datepicker({
//                    defaultDate: "+1w",
//                    changeMonth: true,
//                    numberOfMonths: 1,
//                    minDate : 0,
//                    maxDate : "+3Y",
//                    onSelect: function( selectedDate ) {
//                        var option = this.id == "textbox1id" ? "minDate" : "maxDate",
//                            instance = $( this ).data( "datepicker" );
//                        date = $.datepicker.parseDate(
//                            instance.settings.dateFormat ||
//                                $.datepicker._defaults.dateFormat,
//                            selectedDate, instance.settings );
//                        dates.not( this ).datepicker( "option", option, date );
//                    }
//                });
//            }

            // Account and Credit card transaction data export button URL
            if ($('.view-account-transaction').length > 0 || $('.view-credit-card-transaction').length > 0) {
                if ($('a.btn-download').length > 0) {
                    if ($('.feed-icon a').length > 0) {
                        $('a.btn-download').attr('href', $('.feed-icon a').attr('href'));
                        $('.feed-icon a').remove();
                    }
                }
            }


        }
    };
    Drupal.behaviors.fernweh_leads_filter_action = {
        attach: function (context, settings) {
            $('.view-id-lead_listing .filter-icon a, a.close.filter-header, .view-id-order_listing .filter-icon a').on("click", function (e) {
                e.preventDefault();
                $('#filter-result').toggle();
            });

            var options = '';
            var $input_selector = "#edit-field-lead-service-type-value";
            var $filter_select = "#lead-service-type-select";
            var $date_field_name = "field_lead_closing_date_value";
            var $select_filter_field_name = "field_lead_service_type_value";
            if ($('#edit-status-wrapper').length > 0 || $('input[name*=field_oder_date_purchase_value]').length > 0) {
                $input_selector = "#edit-status-wrapper";
                $filter_select = "#order-status-select";
                $date_field_name = "field_oder_date_purchase_value";
                $select_filter_field_name = "status";

            }
            String.prototype.capitalize = function () {
                return this.toLowerCase().replace(/\b\w/g, function (m) {
                    return m.toUpperCase();
                });
            };

            $($input_selector + ' option').each(function (index) {
                var $this = $(this);
                if (index > 0) {
                    if ($this.val() != "processing") {
                        var $optionLabel = ($this.val() == 'canceled') ? 'cancelled' : $this.val();
                        options += '<option value="' + $this.val() + '">' + $optionLabel.capitalize() + '</option>';
                    }
                }
            });
            var $service_type = "All";
            var $min_date = "";
            var $max_date = "";
            // Dropdown filter
            $('select' + $filter_select).append(options);
            $('select' + $filter_select).on('change', function () {
                $service_type = $(this).val();
                var $value = $date_field_name + '[min][date]=&' + $date_field_name + '[max][date]=&' + $select_filter_field_name + '=' + $service_type;
                var $path = window.location.href.split('?')[0] + '?combine=&' + $value;
                window.location.href = $path;
            });
            // Calender filter
            $(document).on('click', 'button.applyBtn', function (e) {
                $min_date = $('input[name=daterangepicker_start]').val();
                $max_date = $('input[name=daterangepicker_end]').val();

                var $value = $date_field_name + '[min][date]=' + $min_date + '&' + $date_field_name + '[max][date]=' + $max_date + '&' + $select_filter_field_name + '=All';
                var $path = window.location.href.split('?')[0] + '?combine=&' + $value;
                window.location.href = $path;
            });


            // Making field_lead_account mandatory
            if ($('input[name*=field_lead_account]').length > 0) {
                $('input[name*=field_lead_account]').on('blur', function () {
                    var val = $(this).val();
                    var matches = val.match(/\(\d+\)/g);
                    if (matches == null) {
                        $(this).addClass('error');
                        if ($('#account-error-lead').length == 0) {
                            $(this).after('<span id="account-error-lead" class="error">Please select account from options</span>');
                        }
                    } else {
                        $(this).removeClass('error');
                        if ($('#account-error-lead').length > 0) {
                            $('#account-error-lead').remove();
                        }
                    }
                });
            }



        }
    };

    Drupal.behaviors.imageAutoUpload = {
        attach: function (context, settings) {
            $('form', context).delegate('input.form-file', 'change', function () {
                $(this).next('input[type="submit"]').mousedown();
            });
        }
    };

    Drupal.behaviors.viewListUIAlter = {
        attach: function (context, settings) {
//            $('.view-id-vendor_listing .views-table tbody tr').each(function (e) {
//                var orderCount = parseInt($('td.views-field-order-id a', this).html());
//                var leadCount = parseInt($('td.views-field-product-id a', this).html());
//                if ((orderCount > 0) && (leadCount >= orderCount)) {
//                    $('td.views-field-product-id a', this).html(leadCount - orderCount);
//                }
//            });
            $('.view-id-order_listing #edit-combine').on("change", function () {
                $('#edit-field-lead-service-flight-pnr-value').val(this.value);
            });
        }
    };

    Drupal.behaviors.orderModifyAttachment = {
        attach: function (context, settings) {
            $('.order-remove-attachment:not(".processed")').addClass('processed').on('click', function (e) {
                var element = $(this).parent();
                e.preventDefault();
                var s = $('input[name="todelete_attachments"]').val();
                $('input[name="todelete_attachments"]').val(s + element.attr('data-fid') + ',');
                element.remove();
            });
            $('.attachment-addmore-btn:not(".processed")').addClass("processed").on("click", function (e) {
                e.preventDefault();
                $(this).addClass('element-hidden');
                var index = $(this).attr('data-next');
                index = (index * 1);
                //$('#edit-add-attachment-' + index + '-ajax-wrapper').find('.element-hidden').removeClass('element-hidden');
                $('.order-attachment-' + index).removeClass('element-hidden');
                $('a.attachment-addmore-btn[data-next="' + (index + 1) + '"]').removeClass('element-hidden');
            });
        }
    };

    Drupal.behaviors.orderEdit = {
        attach: function (context, settings) {

            if ($('input[name*=account_name]').length > 0) {
                $('input[name*=account_name]').attr('readonly', 'readonly');
            }

//            if ($('select[name*=order_status]').length > 0) {;
//                $('select[name*=order_status]').css('pointer-events', 'none');
//            }

            if ($('.order_internal_wrapper').length > 0) {

                var select_card_handler = function ($mode) {
                    var $select_card = $('.order_internal_wrapper select[name*=field_order_select_card]') || null;
// JOSEPH
                    if ($mode.length > 0 && ($mode.val() == "Credit Card" || $mode.val() == "Debit Card")) {
                        // JOSEPH
                        $select_card.closest('.form-wrapper').show();
                        $select_card.siblings('label')
                                .html('Select the Card <span class="form-required" title="This field is required.">*</span>');
                        //$select_card.attr('required', 'required');
                    } else {
                        $select_card.closest('.form-wrapper').hide();
                        $select_card.val($select_card.find('option:first-child').val());
                        $select_card.removeAttr('required');
                    }

                }
                var $mode = $('select[name*=field_order_purchase_mode]') || null;
                select_card_handler($mode);
                $mode.on('change', function (e) {
                    select_card_handler($(this));
                });
            }
        }
    };

    Drupal.behaviors.paymentForm = {
        attach: function (context, settings) {
            if ($('input[name=choose_payment_type]').length > 0) {
                var payment_from_action = function ($type, $payment_mode, $amount_paid, $order_table, $event) {
                    if ($type == 0) {
                        if ($event) {
                            $payment_mode.val('_none');
                            $amount_paid.val('');
                        }
                        $order_table.hide();
                        $payment_mode.closest('.form-wrapper').show();
                        $amount_paid.closest('.form-wrapper').show();
                        $payment_mode.find('option[value=Account]').hide();
                    } else {
                        $payment_mode.val('Account');
                        $payment_mode.closest('.form-wrapper').hide();
                        $amount_paid.val($('input[name=account_outstanding_bal]').val());
                        $amount_paid.closest('.form-wrapper').hide();
                        $order_table.show();
                        $payment_mode.find('option[value=Account]').show();
                    }
                }
                var $type = $('input[name=choose_payment_type]').val();
                var $payment_mode = $('select[name*=field_payment_mode]');
                var $amount_paid = $('input[name*=field_payment_amount_paid]');
                var $order_table = $('table.order-table-list');
                var $alert_class = "debit";
                if ($('input[name=account_outstanding_bal]').val() > 0) {
                    $alert_class = "credit";
                } else {
                    $('input[name=choose_payment_type]').attr('disabled', 'disabled');
                }
                if ($('#alert-payment-form-balance').length == 0) {
                    $("#payment_form_wrapper").before('<div id="alert-payment-form-balance" class="alert ' + $alert_class + '"><strong>Available Balance: </strong>' + $('input[name=account_outstanding_bal]').data('amount') + '</div>');
                }
                if ($('.form-item-choose-payment-type').length > 0) {
                    if ($('.form-item-choose-payment-type input[type=radio]').length == 1) {
                        $("#payment_form_wrapper").before('<div id="alert-payment-form-balance" class="alert debit"><strong>Orders to be paid: </strong>0</div>');
                    }
                }
                var $event = false;
                payment_from_action($type, $payment_mode, $amount_paid, $order_table, $event);
                $('input[name=choose_payment_type]').on('change', function (e) {
                    $type = $(this).val();
                    $event = true;
                    payment_from_action($type, $payment_mode, $amount_paid, $order_table, $event);
                });

            }

        }
    };

    Drupal.behaviors.invoiceSelectAction = {
        attach: function (context, settings) {

            $('ul.invoice-send-list li input[type="checkbox"]').on("change", function () {
                var fileList = new Array();
                var index = 0;
                $('ul.invoice-send-list li input[type="checkbox"]').each(function () {
                    if ($(this).prop('checked') == true) {
                        fileList[index++] = '/invoice/' + $(this).siblings('a').html();
                    }
                });
                $('input[name="invoice_pdf_path"][type="hidden"]').val(fileList.join(','));
            });
        }
    };

    /**
     * //===================== The END =====================/
     */

})(jQuery);
