var ALERT_TITLE = "Oops!";
var ALERT_BUTTON_TEXT = "Ok";

if (document.getElementById) {
    window.alert = function (txt) {
        createCustomAlert(txt);
    }
}

function createCustomAlert(txt) {
    d = document;

    if (d.getElementById("modalContainer")) return;

    mObj = d.getElementsByTagName("body")[0].appendChild(d.createElement("div"));
    mObj.id = "modalContainer";
    mObj.style.height = d.documentElement.scrollHeight + "px";

    alertObj = mObj.appendChild(d.createElement("div"));
    alertObj.id = "alertBox";
    if (d.all && !window.opera) alertObj.style.top = document.documentElement.scrollTop + "px";
    alertObj.style.left = (d.documentElement.scrollWidth - alertObj.offsetWidth) / 2 + "px";
    alertObj.style.visiblity = "visible";

    h1 = alertObj.appendChild(d.createElement("h1"));
    h1.appendChild(d.createTextNode(ALERT_TITLE));

    msg = alertObj.appendChild(d.createElement("p"));
    //msg.appendChild(d.createTextNode(txt));
    msg.innerHTML = txt;

    btn = alertObj.appendChild(d.createElement("a"));
    btn.id = "closeBtn";
    btn.appendChild(d.createTextNode(ALERT_BUTTON_TEXT));
    btn.href = "#";
    btn.focus();
    btn.onclick = function () {
        removeCustomAlert();
        return false;
    }

    alertObj.style.display = "block";

}

function removeCustomAlert() {
    document.getElementsByTagName("body")[0].removeChild(document.getElementById("modalContainer"));
}

function ful() {
    alert('Alert this pages');
}


// ADD EXCURSION DETAILS
function addExcursionDetails(url, addExcursionData) {
    $.ajax({
        url: url,
        method: 'POST',
        processData: false,
        contentType: false,
        cache: false,
        dataType: 'json',
        data: addExcursionData,
        success: function (data) {
            //alert('successfully inserted data');
            //location.reload();
            //createCustomAlert('are you sure');
            if (data === "1") {
                alert('successfully inserted data');
                btn.onclick = function () {
                    window.location.reload();
                    removeCustomAlert();
                    return false;
                }
            } else {
                alert('There is an error when inserting data');
            }
        },

        error: function () {

        }
    });
}


// SEARCH EXCURSIONS
function searchExcursions(url, ExcursionSearchData) {
    $.ajax({
        url: url,
        method: 'POST',
        processData: false,
        contentType: false,
        cache: false,
        dataType: 'json',
        data: ExcursionSearchData,
        success: function (data) {
            var excursionSearchDetails = '';

            if (data != "null") {
                if (data != "3") {
                    $.each(data, function (index, item) {
                        excursionSearchDetails = '';

                        if (item.agent_ref > 0) {

                            var today = new Date();
                            today.setHours(12, 0, 0, 0);

                            d = new Date(item.excursion_date);
                            d.setHours(0, 0, 0, 0);

                            if (item.company == "EHI") {
                                excursionSearchDetails += '<div class="col-lg-4 col-md-4 col-sm-6 col-xs-12">' +
                                '<div class="card">' +
                                '<div style="background-color: #F44336" class="header">' +
                                '<h2 style="color: #FFFFFF !important;">' +
                                item.ehi_no + " | " + item.agent_ref + '<small style="color: #FFFFFF !important;"> ' + item.name + '</small>' +
                                '</h2>';
                            } else if (item.company == "ANA") {
                                excursionSearchDetails += '<div class="col-lg-4 col-md-4 col-sm-6 col-xs-12">' +
                                '<div class="card">' +
                                '<div style="background-color: #3f51b5" class="header">' +
                                '<h2 style="color: #FFFFFF !important;">' +
                                item.ehi_no + " | " + item.agent_ref + '<small style="color: #FFFFFF !important;"> ' + item.name + '</small>' +
                                '</h2>';
                            }else if (item.company == "CMD") {
                                excursionSearchDetails += '<div class="col-lg-4 col-md-4 col-sm-6 col-xs-12">' +
                                '<div class="card">' +
                                '<div style="background-color: #3f51b5" class="header">' +
                                '<h2 style="color: #FFFFFF !important;">' +
                                item.ehi_no + " | " + item.agent_ref + '<small style="color: #FFFFFF !important;"> ' + item.name + '</small>' +
                                '</h2>';
                            }

                            if (d > today) {

                                excursionSearchDetails += '<ul class="header-dropdown m-r--5">' +
                                '<li class="dropdown">' +
                                '<a href="javascript:void(0);" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">' +
                                '<i class="material-icons">more_vert</i>' +
                                '</a>' +
                                '<ul class="dropdown-menu pull-right">' +
                                '<li><a id="btn_edit_excursion_' + item.ex_id + '">Edit</a></li>' +
                                '</ul>' +
                                '</li>' +
                                '</ul>';

                            }

                            excursionSearchDetails += '</div>' +
                            '<div style="padding: 10px !important;" class="body">' +
                            '<b>' + 'Excursion Date : ' + '</b>' + item.excursion_date + '<br>' +
                            '<b>' + 'Excursion : ' + '</b>' + item.excursion_name + '<br>' +
                            '<b>' + 'Hotel  : ' + '</b>' + item.hotel_name + '<br>' +
                            '<b>' + 'Ticket No : ' + '</b>' + item.ticket_no + '<br>' +
                            '<b>' + 'Room No : ' + '</b>' + item.room_no + '<br>' +
                                //'<b>' + 'EHI No : ' + '</b>' + item.ehi_no + '<br>' +
                                //'<b>' + 'Agent Reference No : ' + '</b>' + item.agent_ref + '<br>' +
                                //'<b>' + 'Client Name : ' + '</b>' + item.name + '<br>' +
                            '<b>' + 'Adult : ' + '</b>' + item.adult + ' / ' +
                            '<b>' + 'Child : ' + '</b>' + item.child + ' / ' +
                            '<b>' + 'Infant : ' + '</b>' + item.infant + '<br>' +
                            '<b>' + 'Amount : ' + '</b>' + item.rate + '<br>' +
                            '<b>' + 'Agent : ' + '</b>' + item.agent + '<br>' +
                            '<b>' + 'Pick Up time  : ' + '</b>' + item.pickup_time + '<br>' +
                            //'<b>' + 'Tour Guide  : ' + '</b>' + item.tour_guide_name + '<br>' +
                            '<b>' + 'Promoted Guide  : ' + '</b>' + item.promote_guide_name + '<br>' +
                            //'<b>' + 'Driver  : ' + '</b>' + item.driver + '<br>' +
                            '<b>' + 'Remark : ' + '</b>' + item.remark + '<br>' +
                               '<b>' + 'Created Date/Time : ' + '</b>' + item.created_at + '<br>' +
                            '</div>' +
                            '</div>' +
                            '</div>';
                            //x++;
                            $('#search_results').show().append(excursionSearchDetails).html();

                            $("#main").show();
                            $("#excursion_add_form").hide();
                            $("#search").hide();
                            $('.overlay').fadeOut();
                            $('body').removeClass('overlay-open');

                            $("#btn_edit_excursion_" + item.ex_id).on("click", function (event) {
                                var company = '';
                                if (item.company == "EHI") {
                                    company = 0;
                                } else if (item.company == "ANA") {
                                    company = 1;
                                }

                                $("#main").hide();
                                $('#search_results').hide();
                                $("#excursion_add_form").show();
                                $("#search").hide();
                                $('.overlay').fadeOut();
                                $('body').removeClass('overlay-open');

                                $("div#form_headar h2").html("Update Excursion");

                                $('#ref_no').val(item.agent_ref).attr("disabled", true);
                                $('#ehi_no').val(item.ehi_no).attr("disabled", true);
                                $('#name').val(item.name).attr("disabled", true);
                                $('#agent_name').val(item.agent).attr("disabled", true);
                                $('#company').val(company).change().selectpicker('refresh');
                                $('#adult').val(item.adult).change().selectpicker('refresh');
                                $('#child').val(item.child).change().selectpicker('refresh');
                                $('#infant').val(item.infant).change().selectpicker('refresh');
                                $('#ticket_no').val(item.ticket_no);
                                $('#room_no').val(item.room_no);
                                $('#excursion_date').val(item.excursion_date);
                                $("#hotel").val(item.hotel_id).change().selectpicker('refresh');
                                $('#excursion').val(item.excursion_id).change().selectpicker('refresh');
                                $('#transfer_type').val(item.transfer_type).change().selectpicker('refresh');
                                $('#pickup_time').val(item.pickup_time);
                                $('#amount').val(item.rate);
                                $('#remark').val(item.remark);
                                $('#add_excursion').val('update');

                                $('#btn_add_excursion').attr('id', 'btn_update_excursion');
                                $("#btn_update_excursion").html("Update Excursion");
                                $("#ex_head").html("Update Excursion");


                                $("#btn_update_excursion").on("click", function (event) {
                                    // console.log(item.company);
                                    var ref_no = $('#ref_no').val();
                                    var ehi_no = $('#ehi_no').val();
                                    var name = $('#name').val();
                                    var company = $('#company option:selected').text();
                                    var adult = $('#adult').val();
                                    var child = $('#child').val();
                                    var infant = $('#infant').val();
                                    var ticket_no = $('#ticket_no').val();
                                    var room_no = $('#room_no').val();
                                    var excursion_date = $('#excursion_date').val();
                                    var excursion = $('#excursion').val();
                                    var transfer_type = $('#transfer_type').val();
                                    var pickup_time = $('#pickup_time').val();
                                    var hotel = $('#hotel').val();
                                    var amount = $('#amount').val();
                                    var remark = $('#remark').val();
                                    var add_excursion = $('#add_excursion').val();
                                    var excursion_no = item.excursion_no;

                                    // alert(ref_no+'-/-'+ehi_no+'-/-'+name+'-/-'+adult+'-/-'+child+'-/-'+ticket_no+'-/-'+room_no+'-/-'+excursion_date+'-/-'+excursion+'-/-'+hotel+'-/-'+amount);

                                    var url = 'get_data.php';
                                    var updateExcursionData = new FormData();

                                    updateExcursionData.append('ref_no', ref_no);
                                    updateExcursionData.append('ehi_no', ehi_no);
                                    updateExcursionData.append('name', name);
                                    updateExcursionData.append('company', company);
                                    updateExcursionData.append('adult', adult);
                                    updateExcursionData.append('child', child);
                                    updateExcursionData.append('infant', infant);
                                    updateExcursionData.append('ticket_no', ticket_no);
                                    updateExcursionData.append('room_no', room_no);
                                    updateExcursionData.append('excursion_date', excursion_date);
                                    updateExcursionData.append('excursion', excursion);
                                    updateExcursionData.append('transfer_type', transfer_type);
                                    updateExcursionData.append('pickup_time', pickup_time);
                                    updateExcursionData.append('hotel', hotel);
                                    updateExcursionData.append('amount', amount);
                                    updateExcursionData.append('remark', remark);
                                    updateExcursionData.append('add_excursion', add_excursion);
                                    updateExcursionData.append('excursion_no', excursion_no);

                                    //if ((ref_no === '') || (ehi_no === '') || (ticket_no === '') || (excursion === '') || (hotel === '') || (adult === '') || (child === '') || (infant === '') || (amount === '')) {
                                    //    alert('Please check the form');
                                    //    removeCustomAlert();
                                    //    return false;
                                    //} else {
                                    //    updateExcursionDetails(url, updateExcursionData)
                                    //}

                                    var today = new Date();
                                    today.setHours(today.getHours(), today.getMinutes(), today.getSeconds());

                                    var today_1 = new Date();
                                    today_1.setHours(13, 0, 0, 0);

                                    var today_2 = new Date();
                                    today_2.setHours(0, 0, 0, 0);
                                    var tomorrow1 = moment(today_2).add('days', 1);
                                    var tomorrow = Date.parse(tomorrow1);

                                    var chk_date1 = new Date(excursion_date);
                                    chk_date1.setHours(0, 0, 0, 0);
                                    var chk_date = Date.parse(chk_date1);

                                    //document.write(tomorrow+'//////'+today_2+'//////'+chk_date);
                                    if ((ref_no === '') || (ehi_no === '') || (ticket_no === '') || (excursion_date === '') || (room_no === '') || (adult === '') || (child === '') || (infant === '') || (amount === '') || (excursion === '0') || (hotel === '0')) {
                                        alert('Please check the form');
                                    } else {
                                        if (today > today_1) {
                                            if (chk_date === tomorrow) {
                                                alert('You cannot update excursions for tomorrow after 12:00PM..!');
                                            } else {
                                                updateExcursionDetails(url, updateExcursionData)
                                            }
                                        } else {
                                            updateExcursionDetails(url, updateExcursionData)
                                        }
                                    }

                                });

                            });

                        } else {
                            //  alert('No data Found');
                        }

                    });
                } else {
                    alert("Sorry, No Results were Found!")
                }
            } else {
                alert("Sorry, There is an Error!")
            }
        },

        error: function (xhr, status, error) {
            // alert(error);
            location.reload();
        }

    });
}


// UPDATE EXCURSIONS
function updateExcursionDetails(url, updateExcursionData) {
    $.ajax({
        url: url,
        method: 'POST',
        processData: false,
        contentType: false,
        cache: false,
        dataType: 'json',
        data: updateExcursionData,
        success: function (data) {
            if (data != "null") {
                if (data === "1") {
                    alert('successfully updated data');
                    btn.onclick = function () {
                        window.location.reload();
                        removeCustomAlert();
                        return false;
                    }
                } else {
                    alert('There is an error when inserting data');
                }

            } else {
                alert('null');
            }
        },

        error: function () {

        }
    });
}

// GET EXCURSION HOTEL RATES
function GetExcursionHotelRate(url, ExcursionHotelRateData) {
    $.ajax({
        url: url,
        method: 'POST',
        processData: false,
        contentType: false,
        cache: false,
        dataType: 'json',
        data: ExcursionHotelRateData,
        success: function (data) {
            $('#amount').val(data);
            $('#amount').prop('disabled', true);
        },

        error: function () {

        }
    });
}

// GET EXCURSION LIST
function GetExcursionlist(url, HotelcityData) {
    $.ajax({
        url: url,
        method: 'POST',
        processData: false,
        contentType: false,
        cache: false,
        dataType: 'json',
        data: HotelcityData,
        success: function (data) {
            // $('select[name="excursion"]').empty();
            // $.each(data, function(key, value) {
            //     $('select[name="excursion"]').append('<option value="'+ $row_2['id'] +'">'+  $row_2['excursion_name']  +'</option>');
            //    // '<option value="' . $row_2['id'] . '">' . $row_2['excursion_name'] . '</option>'
            // });

            var items = "";
            $('#excursion').empty();
            items += "<option value='0'>Please select</option>";
            $.each(data, function(key, value) {
                items += '<option value="'+ key +'">'+ value +'</option>';
                // $('#excursion').append();
            });
            $('#excursion').append(items);
            $('#excursion').selectpicker('refresh');

        },

        error: function(XMLHttpRequest, textStatus, errorThrown) { 
            alert("Status: " + textStatus); alert("Error: " + errorThrown); 
        }
    });
}


