jQuery(document).ready(function(){
    jQuery('<div class="overlay"></div>').insertBefore(".content-wrapper");
});

function setImg(input,id) {
    if (input.files && input.files[0]) {
        var reader = new FileReader();

        reader.onload = function (e) {
            $('#'+id).attr('src', e.target.result);
        };
        reader.readAsDataURL(input.files[0]);
    }
}
function initPickUp() {
 var options = {componentRestrictions: {country: country_flag}};
 var input = document.getElementById('pickup_location');
 var autocomplete = new google.maps.places.Autocomplete(input, options);
}
google.maps.event.addDomListener(window, 'load', initPickUp);
function initDestination() {
	var options = {componentRestrictions: {country: country_flag}};
	var input = document.getElementById('drop_location');
	var autocomplete = new google.maps.places.Autocomplete(input, options);
}
google.maps.event.addDomListener(window, 'load', initDestination);

jQuery('[name="offer_type"]').click(function(){
    var offer = jQuery(this).val();
    if(offer == 2){
        jQuery('[id="input_discount"]').html(jQuery('[id="discount_input_html"]').html());
    } else {
        jQuery('[id="input_discount"]').html('');
    }
});

function checkChild(thisObj){
    var table = thisObj.attr('table');
    if(thisObj.prop("checked") == true){
        jQuery('[id^="table_'+table+'_"]').prop("checked", true);
    } else {
        jQuery('[id^="table_'+table+'_"]').prop("checked", false);
    }
    jQuery('[name^="TDLS.transport_id"],[name^="TDLS.medical_no"],[name^="TDLS.patient_name"],[name^="TDLS.age"],[name^="TDLS.phone"],[name^="APRES.reason"],[name^="TDLS.appointment_time"]').prop("checked", true).parent().closest('div').addClass('disable-block');
}

jQuery('[name="fieldType"]').click(function(){
    var action = jQuery(this).attr('action');
    if(action == 'show'){
        jQuery('[id="customFields"]').removeClass('hide');
    } else {
        jQuery('[id="customFields"]').addClass('hide');
    }
});

jQuery('[id="rGenerate"]').click(function(){
    event.preventDefault();
    var fields = '',
    action = jQuery(this).attr('action'),
    thisObj = jQuery(this);
    fieldType = jQuery('input[name="fieldType"]:checked').val(),
    where_cond = jQuery('[id="where_cond"]').serialize();

    if(thisObj.attr('dmclick') == 1){
        return false;
    }

    thisObj.attr('dmclick','1');
    if(fieldType == 'custom'){
        jQuery.each(jQuery('[id="field_list"]').serialize().split('&'), function (key,field) {
            var field_arr = field.split('=');
            fields += field_arr[1]+',';
        });
    }else{
        fields = jQuery('[id="all_fields"]').attr('all_fields');
    }
    jQuery.ajax({
        url  : base_url+"Report/rGenerate", 
        type : 'POST',
        data : {'action':action,'fields':fields,'where_cond':where_cond},
        success: function(resp){
            if(resp == '' || resp == undefined || resp == 'undefined' || resp == null || resp == 'null'){
                thisObj.attr('dmclick','0');
                return false;
            }
            var resp_data = jQuery.parseJSON(resp);
            if(resp_data['status'] == '2'){
                thisObj.attr('dmclick','0');
                setErrModal('Report status','No Data Found..!');
                return false;
            }
            if(resp_data['status'] == 0 || (action == 'view' && (resp_data['report_data'] == '' || resp_data['report_data'] == undefined || resp_data['report_data'] == 'undefined' || resp_data['report_data'] == null || resp_data['report_data'] == 'null'))){
                thisObj.attr('dmclick','0');
                setErrModal('Report status','Something Went Wrong, Please Try Again..!');
                return false;
            }
            if(action == 'view'){
                var table = jQuery('[id="report_table"]').DataTable();
                table.clear().draw();

                jQuery.each(resp_data['report_data'], function(key, data) {
                    report_data[key] = data;
                    var vBtn = '<a class="btn btn-sm btn-primary" id="report_view_pop_'+key+'" key="'+key+'"><i class="fa fa-fw fa-edit"></i>View</a>';
                    table.row.add([data['Order_ID'],data['Medical_Number'],data['Patient_Name'],
                     data['Patient_Age'],data['Patient_Phone'],data['Appointment_Reason'],
                     data['Appointment_Time'],vBtn]).draw();
                });
                jQuery('[id="report_table_html"]').removeClass('hide');
                slideTo('report_table_html');
                thisObj.attr('dmclick','0');
            }
            if(action == 'export'){
                thisObj.attr('dmclick','0');
                window.location.replace(base_url+'Report/downloadCSV');
            }
        }
    });
});

function setErrModal(header_msg,body_msg){
    jQuery('[id="modal_body_msg"]').html(body_msg);
    jQuery('[id="modal_header_msg"]').html(header_msg);
    jQuery('[id="errModal"]').modal('show');
}

function slideTo(id){
    jQuery('html, body').animate({
        scrollTop: jQuery('[id="'+id+'"]').offset().top
    }, 800);
}

jQuery('#report_table tbody').on('click','a',function() {
    var thisObj = jQuery(this),
    key = thisObj.attr('key');
    viewOrderDetails(key);
});

jQuery('[id="viewRideDetails"]').click(function(){
    console.log('sdrfg');
    var thisObj = jQuery(this),
    key = thisObj.attr('key');
    viewOrderDetails(key);
});

function viewOrderDetails(key){
    var body_html = rowHtml = '';

    var colCount = 1;
    body_html = '<div class="col-xs-12">';
    jQuery.each(report_data[key], function(field,value) {
        value = (value == null || value == 'null' || value == undefined || value == 'undefined')?'--':value;
        rowHtml += '<div class="col-xs-6"><div class="col-xs-12">'+
        '<div class="col-xs-6">'+field.replace(/_/g,' ')+'</div>'+
        '<div class="col-xs-1">:</div>'+
        '<div class="col-xs-5">'+value+'</div>'+
        '</div></div>';
        if(colCount == 2){
            body_html += rowHtml;
            rowHtml = '';
            colCount = 1;
        }else{
            colCount++;
        }
    });
    body_html += (rowHtml != '')?rowHtml+'</div>':'</div>';
    modalTrigger('Ride Details',body_html);
}

function getRideData(){
    jQuery('[id="getRideDataForm"]').submit();
}

function getCmpyPayDetls(){
    jQuery('[id="cmpyPayDetlsForm"]').submit();
}

function modalTrigger(header,body_html){
    jQuery('[id="modal_content"]').html(body_html);
    jQuery('[id="modal_header"]').html(header);

    jQuery('[id="popup_modal"]').modal('show');
}

function modalHide(){
    jQuery('[id="popup_modal"]').modal('hide');
}

function addModalLoader(){
    jQuery("[id='modal_content']").addClass('relative height_200');
    jQuery("[id='modal_content']").prepend("<div id='modal_loader_body' class='loader'></div>");
}

function remModalLoader(){
    jQuery("[id='modal_loader_body']").remove();
    jQuery("[id='modal_content']").removeClass('relative height_200');
}

function getBrokers(allBrokerFlag,phoneBookingFlag){
    var company_id = jQuery('[id="searchCompanyDrop"] option:selected').val();
    if(company_id == '' || company_id == undefined || company_id == 'undefined' || company_id == null || company_id == 'null'){
        jQuery('[id="searchBrokerBlock"]').addClass('disable-div');
    }

    jQuery.ajax({
        url  : base_url+"Broker/getBrokers", 
        type : 'POST',
        data : {'company_id':company_id},
        success: function(resp){
            if(resp == '' || resp == undefined || resp == null || resp == 'null' || resp == 'undefined'){
                return false;
            }
            var optionHtml = (allBrokerFlag == 1)?'<option selected value="">All Brokers</option>':'';
            resp = jQuery.parseJSON(resp);
            if(resp['status'] == 0){
                return false;
            }
            if(resp['status'] == 1){
                jQuery.each(resp['data'], function(index,value) {
                    optionHtml += '<option value="'+value['broker_id']+'">'+value['broker_name']+'</option>';
                });
            }
            optionHtml += (phoneBookingFlag == 1)?'<option value="0">Phone Bookings</option>':'';
            if(optionHtml == ''){
                jQuery('[id="searchBrokerDrop"]').addClass('prevent-click');
                optionHtml = '<option selected disabled>No Data Found</option>';
            }
            jQuery('[id="searchBrokerDrop"]').html(optionHtml);
            jQuery('[id="searchBrokerBlock"]').removeClass('disable-div');
        }
    });
}

jQuery('[id="selectAllDriver"]').click(function(){
    var thisObj = jQuery(this);
    if(thisObj.prop("checked") == true){
        jQuery('[id^="avlDriver_"]').prop("checked", true);
    } else {
        jQuery('[id^="avlDriver_"]').prop("checked", false);
    }
});

jQuery('[id="scheduleAll"]').click(function(){
    if(ride_ids==undefined || ride_ids=='undefined' || ride_ids==null || ride_ids=='null' || ride_ids==''){
        return false;
    }
    markAsScheduled(ride_ids,'0');
});

jQuery('[id^="markSchedule_"]').click(function(){
    var thisObj = jQuery(this),
    is_scheduled = thisObj.attr('is_scheduled'),
    transport_id = thisObj.attr('transport_id');

    if(transport_id == undefined || transport_id == 'undefined' || transport_id == null || transport_id == 'null' || transport_id == '' || 
     is_scheduled == undefined || is_scheduled == 'undefined' || is_scheduled == null || is_scheduled == 'null' || is_scheduled == ''){
        return false;
}

if(is_scheduled == 1){
    flag = confirm("Are you sure to continue with this action...?");
    if(flag != true) return false;
}
markAsScheduled(transport_id,is_scheduled);
});

function markAsScheduled(transport_id,is_scheduled){
    var drivers = [], no_driver = jQuery('[id="checkNoDriver"]:checked').val();
    jQuery.each(jQuery("input[name^='avlDrivers[]']:checked"), function() {
      drivers.push(jQuery(this).val());
    });
    no_driver = (no_driver == undefined || no_driver == 'undefined' || no_driver == null || no_driver == 'null' || no_driver == '')?'0':'1';
    
    if(is_scheduled == undefined || is_scheduled == 'undefined' || is_scheduled == null || is_scheduled == 'null' || is_scheduled == '' || 
       transport_id == undefined || transport_id == 'undefined' || transport_id == null || transport_id == 'null' || transport_id == ''){
        return false;
    }

    // if(is_scheduled == 0 && no_driver == 0 && (drivers == undefined || drivers == 'undefined' || drivers == null || drivers == 'null' || drivers == '')){
    //     slideTo('selectDriverBlock');
    //         jQuery('[id="driverRequired"]').fadeIn(500);
    //     setTimeout(function(){ 
    //         jQuery('[id="driverRequired"]').fadeOut(1000);
    //     }, 5000);
    //     return false;
    // }
 
    showFullScreenLoader();
    jQuery.ajax({
        url  : base_url+"Ride/changeSchuduleStatus", 
        type : 'POST',
        data : {'transport_id':transport_id,'is_scheduled':is_scheduled,'no_driver':no_driver,'drivers':drivers},
        success: function(resp){
            if(resp == '' || resp == undefined || resp == null || resp == 'null' || resp == 'undefined'){
                remFullScreenLoader();
                return false;
            }
            resp = jQuery.parseJSON(resp);
            if(resp['status'] == 1){
                var color = '';
                if(is_scheduled == 1){
                    color = 'red'
                    is_scheduled = 0;
                } else {
                    color = 'green'
                    is_scheduled = 1;
                }
                jQuery.each(resp['succArr'], function(index,value) {
                    jQuery('[id="markSchedule_'+value+'"]').attr('is_scheduled',is_scheduled);
                    jQuery(jQuery('[id="markSchedule_'+value+'"]')).children().css( "color", color );
                });
                remFullScreenLoader();
            } else {
                remFullScreenLoader();
                setErrModal('Error Scheduling Rides','Something went wrong, please try again..!');
            }
        },
        error: function (jqXHR, exception) {
            remFullScreenLoader();
        }
    });
}

function showFullScreenLoader(){
    var thisObj = jQuery('.overlay');
    thisObj.css("display",'block');

    thisObj.addClass('relative');
    thisObj.prepend("<div id='fullScreenLoaderBody' class='loader'></div>");
}

function remFullScreenLoader(){
    var thisObj = jQuery('.overlay');
    thisObj.css("display",'none');

    jQuery('[id="fullScreenLoaderBody"]').remove();
    thisObj.removeClass('relative');
}

function allowDropElement(ev) {
    if(ev.target.getAttribute('type') != 'parent' && ev.target.firstChild != null){
        return false;
    }
    ev.preventDefault();
}

function dragElement(ev) {
    ev.dataTransfer.setData("tmporderid", ev.target.getAttribute('id'));
}

function dropElement(ev) {
    ev.preventDefault();
    jQuery(event.target).css('border-color','#A8A8A8');
    var tmporderid = ev.dataTransfer.getData("tmporderid");
    ev.target.appendChild(document.getElementById(tmporderid));
}

jQuery('[id="upload_excell"]').click(function(){
    var thisObj = jQuery(this), childThisObj = '', headerOrder = [], fileType = jQuery('[name="fileType"]').val(),
        broker_id = jQuery('[name="broker_id"]').val(), company_id = jQuery('[name="company_id"]').val(),
        import_file = jQuery('[name="import_file"]').val(), childHead = '', errMsg = '', error = '0';
    
    if(thisObj.attr('dmclick') != 0){
        return false;
    }

    if(fileType == '' || fileType == undefined || fileType == null || fileType == 'null' || fileType == 'undefined' ||
       broker_id == '' || broker_id == undefined || broker_id == null || broker_id == 'null' || broker_id == 'undefined' ||
       company_id == '' || company_id == undefined || company_id == null || company_id == 'null' || company_id == 'undefined' ||
       import_file == '' || import_file == undefined || import_file == null || import_file == 'null' || import_file == 'undefined'){
        setErrModal('Error Uploading Excell','Please Map All the Fields to the corrospinding header..!');
        return false;
    }

    showFullScreenLoader();
    thisObj.attr('dmclick',1);

    jQuery('[id="mappedHeaders"] [required="yes"]').each(function(){
        childThisObj = jQuery(this);
        if (childThisObj.children().length <= 0) {
            remFullScreenLoader();
            thisObj.attr('dmclick',0);
            childThisObj.css('border-color','red');
            setErrModal('Error Uploading Excell','Map all required fields..!');
            error = '1';
        }
        childHead = childThisObj.children();
        headerOrder[childThisObj.attr('headOrder')] = childHead.attr('tmporder');
    });
    if(error == '1'){
        return false;
    }
    jQuery.ajax({
        url  : base_url+"Ride/import", 
        type : 'POST',
        data : {'broker_id':broker_id,'company_id':company_id,'header_order':headerOrder,'file_type':fileType,'import_file':import_file},
        success: function(resp){
            if(resp == '' || resp == undefined || resp == null || resp == 'null' || resp == 'undefined'){
                remFullScreenLoader();
                thisObj.attr('dmclick',0);
                setErrModal('Error Uploading Excell','Something went wrong, please try again..!');
                return false;
            }
            resp = jQuery.parseJSON(resp);
            if(resp['status'] == 1){
                window.location.replace(base_url+'Ride/view_rides');
            } else {
                if (resp['status'] == 0) {
                    errMsg = 'Something went wrong, please try again..!';
                } else if (resp['status'] == 2) {
                    errMsg = 'Invalid File given, please try again later..!';
                } else if (resp['status'] == 3) {
                    errMsg = 'No data found, please try again later..!';
                } else if (resp['status'] == 4) {
                    errMsg = 'Invalid header given, please try again later..!';
                } 
                remFullScreenLoader();
                thisObj.attr('dmclick',0);
                setErrModal('Error Uploading Excell',errMsg);
            }
            return false;
        },
        error: function (jqXHR, exception) {
            remFullScreenLoader();
            thisObj.attr('dmclick',0);
            setErrModal('Error Uploading Excell','Something went wrong, please try again..!');
            return false;
        }
    });
});


jQuery('[name="vehicle_id"]').on('change',function() {
    var vechileTypId = jQuery(this).find(":selected").val(); 
    if(vechileTypId == '' || vechileTypId == null || vechileTypId == 'null' || 
       vechileTypId == undefined || vechileTypId == 'undefined'){
        setErrModal('Vechile Type Error','Choose a valid vechile type..!');
        return false;
    }
    jQuery.ajax({
        url  : base_url+"Vehicle/getVehicleData", 
        type : 'POST',
        data : {'vehicle_type':vechileTypId},
        success: function(resp){
            if(resp == '' || resp == undefined || resp == null || resp == 'null' || resp == 'undefined'){
                remFullScreenLoader();
                return false;
            }
            resp = jQuery.parseJSON(resp);
            if(resp['status'] == 1){
              if(resp['data'] == undefined || resp['data'] == 'undefined' || 
                 resp['data'] == null || resp['data'] == 'null' || resp['data'] == ''){

                jQuery('[name="vehicle"]').html('<option selected disabled>'+
                                                  'Select Vehicle Model'+
                                                '</option>');
                setErrModal('Vechile Type Error','Choose a valid vechile type..!');
                return false;
              }
              var optHtml = '';
              jQuery.each(resp['data'], function(index,vehicleData){
                optHtml += '<option value="'+vehicleData['vehicle_id']+'" newOpt="1">'+
                              vehicleData['vehicle_model']+' - '+vehicleData['vehicle_reg_no']
                           '</option>'
              });
              jQuery('[name="vehicle"]').html(optHtml);
              jQuery('[id="vehicleModelCont"]').removeClass('hide');
            } else {
              setErrModal('Error','Something went wrong, please try again..!');
              return false;
            }
        },
        error: function (jqXHR, exception) {
          setErrModal('Server Error','Something went wrong, please try again..!');
          return false;
        }
    });
});

jQuery('[id^="updateBrkPayDate_"]').on('click',function() {
    var thisObj = jQuery(this), 
        broker_id = thisObj.attr('broker_id'),
        last_paid_date = jQuery('[name="payment_date_'+broker_id+'"]').datepicker({dateFormat:'yy-mm-dd'}).val();

    if(last_paid_date==''||last_paid_date==undefined||last_paid_date=='undefined'||last_paid_date==null||last_paid_date=='null'){
        setErrModal('Date Not Found','Choose a valid date and continue..!');
        return false;
    }

    if(broker_id==''||broker_id==undefined||broker_id=='undefined'||broker_id==null||broker_id=='null'){
        setErrModal('Error, Payment Date Update','Something went wrong, please try again..!');
        return false;
    }

    jQuery.ajax({
        url  : base_url+"Payment/updatePaymentDate", 
        type : 'POST',
        data : {'broker_id':broker_id,'last_paid_date':last_paid_date},
        success: function(resp){
            if(resp == '' || resp == undefined || resp == null || resp == 'null' || resp == 'undefined'){
                setErrModal('Issue Updating Date','Something went wrong, please try again..!');
                return false;
            }
            resp = jQuery.parseJSON(resp);
            if(resp['status'] == 1 && resp['data'] != '' && resp['data'] != undefined && resp['data'] != null && resp['data'] != 'null' && resp['data'] != 'undefined'){
                var data = resp['data'];

                jQuery('[id="all_trans_count_'+broker_id+'"]').html(data['all_trans_count']);
                jQuery('[id="pro_trans_count_'+broker_id+'"]').html(data['pro_trans_count']);
                jQuery('[id="tot_paid_booking_'+broker_id+'"]').html(data['pro_trans_count'] - data['pending_trans_count']);
                jQuery('[id="pending_trans_count_'+broker_id+'"]').html(data['pending_trans_count']);
                jQuery('[id="brkPayDate_'+broker_id+'"]').html(data['last_paid_date']);
            } else {
                setErrModal('Error','Something went wrong, please try again..!');
            }
            return false;
        },
        error: function (jqXHR, exception) {
            setErrModal('Server Error','Something went wrong, please try again..!');
            return false;
        }
    });
});