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 setModal(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);
}

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 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 viewImageModal(title,img_src){
	if(title=='' || title==undefined || title=='undefined' || title==null || title=='null'||
	   img_src=='' || img_src==undefined || img_src=='undefined' || img_src==null || img_src=='null'){
		return false;
	}
	body_html = '<div style="text-align:center">'+
				  '<img src="'+img_src+'" onerror="this.src=\''+base_url+'assets/images/no_image.png\';" height="400px" width="auto">'+
   		  		'</div>';
	modalTrigger(title,body_html);
}

function initLocSearch_1() {
 var input = document.getElementById('loc_search_1');
 var options = {componentRestrictions: {country: country_flag}};
 var autocomplete = new google.maps.places.Autocomplete(input, options);
}
google.maps.event.addDomListener(window,'load',initLocSearch_1);
function initLocSearch_2() {
 var input = document.getElementById('loc_search_2');
 var options = {componentRestrictions: {country: country_flag}};
 var autocomplete = new google.maps.places.Autocomplete(input, options);
}
google.maps.event.addDomListener(window,'load',initLocSearch_2);
function initLocSearch_3() {
 var input = document.getElementById('loc_search_3');
 var options = {componentRestrictions: {country: country_flag}};
 var autocomplete = new google.maps.places.Autocomplete(input, options);
}
google.maps.event.addDomListener(window,'load',initLocSearch_3);

function addLayoutPricing(thisObj){
  var count = thisObj.attr('count'),
      html = jQuery('[id="subIssueAdd"]').html();

  if(count == '' || count == null || count == 'null' || count == undefined || count == 'undefined' || html == '' || html == null || html == 'null' || html == undefined || html == 'undefined'){
    return false;
  }
  count = parseInt(count)+1;
  thisObj.attr('count',count);
  html = html.replace(/{:count}/g, count);
  jQuery('[id="subIssueCntr"]').append('<div class="col-md-12 dispInLine" id="newSubIssue_'+count+'">'+html+'</div>');
}

function remSubIssue(count){
  if(count == '' || count == null || count == 'null' || count == undefined || count == 'undefined'){
    return false;
  }
  jQuery('[id="newSubIssue_'+count+'"]').remove();
}

function setLayout(){
    var layoutFlag = jQuery('[name="host_cat_id"]').find(":selected").attr('haveLayout');
    
    if(layoutFlag == 1){
        jQuery('[id="layoutCntr"]').html(jQuery('[id="layoutCntrHtml"]').html());
    } else {
        jQuery('[id="layoutCntr"]').html('');
    }
}

jQuery('[id="viewVenueDetails"]').on('click',function() {
    var venue_id = jQuery(this).attr('venue_id');

    if(venue_id=='' || venue_id==undefined || venue_id=='undefined' || venue_id==null || venue_id=='null'){
        return true;
    }
    modalTrigger('Venue Details','');
    addModalLoader();
    jQuery.ajax({
        url  : base_url+"Venue/getVenueData", 
        type : 'POST',
        data : {'venue_id':venue_id},
        success: function(resp){
            if(resp == '' || resp == undefined || resp == 'undefined' || resp == null || resp == 'null'){
                remModalLoader();
                jQuery('[id="modal_content"]').html('Something went wrong, please try again later...!');
                return false;
            }
            var resp_data = jQuery.parseJSON(resp);
            if(resp_data['status'] == '0'){
                remModalLoader();
                jQuery('[id="modal_content"]').html('Something went wrong, please try again later...!');
                return false;
            }
            var venue_data = resp_data['data'];

            jQuery.each(venue_data, function (index, value) {
                if(venue_data[index] != 'layout' && venue_data[index] != 'layout_details' && (value == '' || value == null || value == undefined || value == 'null' || value == 'undefined')){
                    venue_data[index] = ' -- ';
                }
            });

            var layoutHtml = '', innerLyOut = '';
            if(venue_data['show_layout'] == '1'){
                layoutHtml =  '<div class="col-md-6">'+
                                '<div class="row"><label>Layout Details</label></div>'+
                                '<div class="row"> '+
                                  '<div class="col-md-6" style="text-align:center;"> '+
                                    '<img id="driverLicenceImg" src="'+base_url+venue_data['layout']+'"'+
                                      'style="margin-top:10px;width:auto;max-width:200px;height:200px;" />'+
                                  '</div>';

                jQuery.each(jQuery.parseJSON(venue_data['layout_details']), function (indexLayout, layoutValue) {
                    innerLyOut += '<div>'+
                                    '<div onclick="showLyDivDtls(jQuery(this))" show="0" class="cpoint">'+
                                      '<i class="fa fa-caret-square-o-down green" aria-hidden="true"></i>'+
                                      '<label class="padLeft10 cpoint">'+layoutValue['color']+'</label> Block'+
                                    '</div>'+
                                    '<div class="hide">'+
                                      '<div class="padLeft40"><label>'+layoutValue['price']+'</label> /Seat</div>'+
                                      '<div class="padLeft40"><label>150</label> Total Capacity</div>'+
                                    '</div>'+
                                  '</div>';
                });
                innerLyOut =  '<div class="col-md-6 layoutDivHead">'+
                                '<div class="row padLeft15"><label>Pricing Details</label></div><hr class="hrClass">'+
                                innerLyOut+
                              '</div>'+
                            '</div>'+
                          '</div>';

                layoutHtml = layoutHtml+innerLyOut;
            }
            var colSlot = (layoutHtml != '')?'6':'12';
            var html = '<div id="map-canvas-assign" style="width: 100%; height: 200px;"></div><br>'+
                        '<div class="col-xs-12">'+
                          '<div class="col-md-'+colSlot+'">'+
                            '<div class="row"><label>Venue Details</label></div>'+
                            '<div class="row">'+
                              '<div class="col-md-4">Venue Name</div>'+
                              '<div class="col-md-1">:</div>'+
                              '<div class="col-md-6"><label>'+ venue_data['venue_name']+'</label></div>'+
                            '</div> '+
                            '<div class="row">'+
                              '<div class="col-md-4">Venue Region</div>'+
                              '<div class="col-md-1">:</div>'+
                              '<div class="col-md-6"><label>'+venue_data['region_name']+'</label></div>'+
                            '</div> '+
                            '<div class="row">'+
                              '<div class="col-md-4">Host Type</div>'+
                              '<div class="col-md-1">:</div>'+
                              '<div class="col-md-6"><label>'+venue_data['host_category']+'</label></div>'+
                            '</div> '+
                            '<div class="row"> '+
                              '<div class="col-md-4">Venue Address</div>'+
                              '<div class="col-md-1">:</div>'+
                              '<div class="col-md-6"><label>'+venue_data['location']+'</label></div>'+
                            '</div> '+
                            '<div class="row">'+
                              '<div class="col-md-4">Venue Details</div>'+
                              '<div class="col-md-1">:</div>'+
                              '<div class="col-md-6"><p class="truncateText">'+ venue_data['venue_details']+'</p></div>'+
                            '</div> '+
                          '</div> '+
                          ''+
                              layoutHtml
                          '</div> '+
                        '</div>';

                remModalLoader();
                jQuery('[id="modal_content"]').html(html);

                jQuery('[id="driverLicenceImg"]').error(function() {
                    jQuery('[id="driverLicenceImg"]').attr('src',base_url+'assets/images/no_image.png');
                });
                var map, geocoder, marker, latlng, infowindow;
                var mapOptions = {center: new google.maps.LatLng(venue_data['location_lat'],venue_data['location_lng']),
                                  zoom: 15,
                                  mapTypeId: google.maps.MapTypeId.ROADMAP
                                 };
                map = new google.maps.Map(document.getElementById("map-canvas-assign"), mapOptions);
                geocoder = new google.maps.Geocoder();
                infowindow = new google.maps.InfoWindow();

                var lat = parseFloat(venue_data['location_lat']);
                var lng = parseFloat(venue_data['location_lng']);
                latlng = new google.maps.LatLng(lat,lng);
                marker = new google.maps.Marker({
                    position: latlng,
                    map: map,
                    html: venue_data['location']
                });
                google.maps.event.addListener(marker, 'click', function(event) {
                    infowindow.setContent(this.html);
                    infowindow.setPosition(event.latLng);
                    infowindow.open(map, this);
                });
            },
            fail: function(xhr, textStatus, errorThrown){
                remModalLoader();
                jQuery('[id="modal_content"]').html('Something went wrong, please try again later...!');
            },
            error: function (ajaxContext) {
                remModalLoader();
                jQuery('[id="modal_content"]').html('Something went wrong, please try again later...!');
        }
    });
});

function providerSubmitForm(){
  jQuery('[id="providerForm"]').submit();
}

function venueSubmitForm(){
  jQuery('[name="venueForm"]').submit();
}

jQuery('[name="fare_type"]').on('click',function() {
  var issue_id = '',
      fare_type = jQuery(this).val();

  if(fare_type == 1){
    jQuery('[id^="custFareInput_"]').addClass('required');
    jQuery('[id^="custFareInput_"]').prop("disabled",false);

    jQuery('[id="defaultFareSystem"]').addClass('hide');
    jQuery('[id="customFareSystem"]').removeClass('hide');
  } else if(fare_type == 0){
    jQuery('[id^="custFareInput_"]').prop("disabled",true);
    jQuery('[id^="custFareInput_"]').removeClass('required');

    jQuery('[id="customFareSystem"]').addClass('hide');
    jQuery('[id="defaultFareSystem"]').removeClass('hide');
  }
});

function manageTags(thisObj){
  var tagId = thisObj.attr('tag_id'),
      inHtm = '<input id="selTag_{:tag_id}" type="hidden" name="tags[]" value="{:tag_id}">';

  if(thisObj.attr('select') == 0){
    thisObj.attr('select','1');
    thisObj.addClass('tagSelected');
    jQuery('[id="selected_tags"]').append(inHtm.replace(/{:tag_id}/g,tagId));
  } else {
    thisObj.attr('select','0');
    thisObj.removeClass('tagSelected');
    jQuery('[id="selTag_'+tagId+'"]').remove();
  }

  if (jQuery('[id="selected_tags"]').children().length <= 0) {
    jQuery('[type="parent"]').css("background-color",'#F2DEDE');
  } else {
    jQuery('[type="parent"]').css("background-color",'#ffffff');
  }
}

function addTimePicker(thisObj){
  var count = thisObj.attr('count')+1,
      inputHtml = jQuery('[id="scheduleTimerHtml"]').html();

  thisObj.attr('count',count);
  jQuery('[id="scheduleTimerCntr"]').append(inputHtml.replace(/{:count}/g,count));

  jQuery('[id="timePickerEnable_'+count+'"]').clockpicker();
}

function remTimePicker(count){
  jQuery('[id="timePicker_'+count+'"]').remove();
}

jQuery('[name="schedule_type"]').on('click',function() {
  var issue_id = '',
      schedule_type = jQuery(this).val();

  if(schedule_type == 1){
    jQuery('[name="event_end_date"]').addClass('required');
    jQuery('[name="event_end_date"]').prop("disabled",false);

    jQuery('[id="eventEndDate"]').removeClass('hide');
  } else if(schedule_type == 0){
    jQuery('[name="event_end_date"]').prop("disabled",true);
    jQuery('[name="event_end_date"]').removeClass('required');

    jQuery('[id="eventEndDate"]').addClass('hide');
  }
});

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

    reader.onload = function (e) {
      var count = thisObj.attr('count');
      thisObj.attr('count',count+1);
      jQuery('[id="multipleImageInputCntr"]').append(jQuery('[id="multipleImageInput"]').html().replace(/{:count}/g,count+1));

      thisObj.addClass('prevent-click');
      jQuery('[id="multiImageClose_'+count+'"]').removeClass('hide');
      jQuery('[id="multiImageImg_'+count+'"]').attr('src', e.target.result);
      jQuery('[id^="multiImageImg_"]').removeClass('errorBorder');
    };
    reader.readAsDataURL(input.files[0]);
  }
}

function removeImage(count){
  jQuery('[id="multiImageCntr_'+count+'"]').remove();
}

jQuery('[id="addEventButton"]').on('click',function(event) {
  event.preventDefault();
  var validation = jQuery('[name="eventAddForm"]').parsley().validate();

  var error = 0;
  if(jQuery('[id="selected_tags"]').children().length <= 0) {
    error = 1;
    jQuery('[type="parent"]').css("background-color",'#F2DEDE');
  }
  var count = jQuery('[id="multipleImageInputCntr"]').children().first().attr('count');
  if(jQuery('[id="event_image_'+count+'"]').val() == ''){
    error = 1;
    jQuery('[id="multiImageImg_'+count+'"]').addClass('errorBorder');
  }

  if(validation && error == 0){
    jQuery('[name="eventAddForm"]').submit();
  }
});

jQuery('[id="viewProvider"]').on('click',function() {
    var provider_id = jQuery(this).attr('provider_id');

    if(provider_id=='' || provider_id==undefined || provider_id=='undefined' || provider_id==null || provider_id=='null'){
        return true;
    }
    modalTrigger('Provider Details','');
    addModalLoader();
    jQuery.ajax({
        url  : base_url+"Provider/getProviderData", 
        type : 'POST',
        data : {'provider_id':provider_id,'view_all':'1'},
        success: function(resp){
            if(resp == '' || resp == undefined || resp == 'undefined' || resp == null || resp == 'null'){
                remModalLoader();
                jQuery('[id="modal_content"]').html('Something went wrong, please try again later...!');
                return false;
            }
            var resp_data = jQuery.parseJSON(resp);
            if(resp_data['status'] == '0'){
                remModalLoader();
                jQuery('[id="modal_content"]').html('Something went wrong, please try again later...!');
                return false;
            }
            var provider_data = resp_data['data'];

            jQuery.each(provider_data, function (index, value) {
                if(value == '' || value == null || value == undefined || value == 'null' || value == 'undefined'){
                    provider_data[index] = ' -- ';
                }
            });

            var html =  '<div class="col-xs-12">'+
                          '<div class="col-md-2">'+
                            '<div class="row">'+
                              '<img  id="providerProfileImg" src="'+base_url+provider_data['profile_image']+'" height="100" width="100" />'+
                            '</div>'+
                          '</div> '+
                          '<div class="col-md-10">'+
                            '<div class="row"><label>Admin Panel Details</label></div>'+
                            '<div class="row">'+
                              '<div class="col-md-3">Display Name</div>'+
                              '<div class="col-md-1">:</div>'+
                              '<div class="col-md-6"><label>'+ provider_data['display_name']+'</label></div>'+
                            '</div> '+
                            '<div class="row">'+
                              '<div class="col-md-3">Provider Name</div>'+
                              '<div class="col-md-1">:</div>'+
                              '<div class="col-md-6"><label>'+provider_data['name']+'</label></div>'+
                            '</div> '+
                            '<br><div class="row"><label>User Details</label></div>'+
                            '<div class="row">'+
                              '<div class="col-md-3">Email ID</div>'+
                              '<div class="col-md-1">:</div>'+
                              '<div class="col-md-6"><label>'+ provider_data['email']+'</label></div>'+
                            '</div> '+
                            '<div class="row">'+
                              '<div class="col-md-3">Phone</div>'+
                              '<div class="col-md-1">:</div>'+
                              '<div class="col-md-6"><label>'+provider_data['phone']+'</label></div>'+
                            '</div> '+
                          '</div> '+
                        '</div>';

                remModalLoader();
                jQuery('[id="modal_content"]').html(html);

                jQuery('[id="providerProfileImg"]').error(function() {
                    jQuery('[id="providerProfileImg"]').attr('src',base_url+'assets/images/no_image.png');
                });
            },
            fail: function(xhr, textStatus, errorThrown){
                remModalLoader();
                jQuery('[id="modal_content"]').html('Something went wrong, please try again later...!');
            },
            error: function (ajaxContext) {
                remModalLoader();
                jQuery('[id="modal_content"]').html('Something went wrong, please try again later...!');
        }
    });
});

jQuery('[id="viewCustomer"]').on('click',function() {
    var customer_id = jQuery(this).attr('customer_id');

    if(customer_id=='' || customer_id==undefined || customer_id=='undefined' || customer_id==null || customer_id=='null'){
        return true;
    }
    modalTrigger('Customer Details','');
    addModalLoader();
    jQuery.ajax({
        url  : base_url+"Customer/getCustomerData", 
        type : 'POST',
        data : {'customer_id':customer_id,'view_all':'1'},
        success: function(resp){
            if(resp == '' || resp == undefined || resp == 'undefined' || resp == null || resp == 'null'){
                remModalLoader();
                jQuery('[id="modal_content"]').html('Something went wrong, please try again later...!');
                return false;
            }
            var resp_data = jQuery.parseJSON(resp);
            if(resp_data['status'] == '0'){
                remModalLoader();
                jQuery('[id="modal_content"]').html('Something went wrong, please try again later...!');
                return false;
            }
            var customer_data = resp_data['data'];

            jQuery.each(customer_data, function (index, value) {
                if(value == '' || value == null || value == undefined || value == 'null' || value == 'undefined'){
                    customer_data[index] = ' -- ';
                }
            });
            var gender = '';
            switch(customer_data['gender']){
              case '1': gender = 'Male';break;
              case '2': gender = 'Female';break;
              case '3': gender = 'Others';break;
            }

            var html =  '<div class="col-xs-12">'+
                          '<div class="col-md-2">'+
                            '<div class="row">'+
                              '<img  id="customerProfileImg" src="'+base_url+customer_data['profile_image']+'" height="100" width="100" />'+
                            '</div>'+
                          '</div> '+
                          '<div class="col-md-10">'+
                            '<div class="row"><label>Customer Details</label></div>'+
                            '<div class="row">'+
                              '<div class="col-md-3">Customer Name</div>'+
                              '<div class="col-md-1">:</div>'+
                              '<div class="col-md-6"><label>'+ customer_data['name']+'</label></div>'+
                            '</div> '+
                            '<div class="row">'+
                              '<div class="col-md-3">Phone</div>'+
                              '<div class="col-md-1">:</div>'+
                              '<div class="col-md-6"><label>'+customer_data['phone']+'</label></div>'+
                            '</div> '+
                            '<div class="row">'+
                              '<div class="col-md-3">Email ID</div>'+
                              '<div class="col-md-1">:</div>'+
                              '<div class="col-md-6"><label>'+ customer_data['email']+'</label></div>'+
                            '</div> '+
                            '<div class="row">'+
                              '<div class="col-md-3">Phone</div>'+
                              '<div class="col-md-1">:</div>'+
                              '<div class="col-md-6"><label>'+customer_data['phone']+'</label></div>'+
                            '</div> '+
                            '<div class="row">'+
                              '<div class="col-md-3">Gender</div>'+
                              '<div class="col-md-1">:</div>'+
                              '<div class="col-md-6"><label>'+gender+'</label></div>'+
                            '</div> '+
                            '<div class="row">'+
                              '<div class="col-md-3">Date Of Birth</div>'+
                              '<div class="col-md-1">:</div>'+
                              '<div class="col-md-6"><label>'+customer_data['dob']+'</label></div>'+
                            '</div> '+
                            '<div class="row">'+
                              '<div class="col-md-3">City</div>'+
                              '<div class="col-md-1">:</div>'+
                              '<div class="col-md-6"><label>'+customer_data['city']+'</label></div>'+
                            '</div> '+
                          '</div> '+
                        '</div>';

                remModalLoader();
                jQuery('[id="modal_content"]').html(html);

                jQuery('[id="customerProfileImg"]').error(function() {
                    jQuery('[id="customerProfileImg"]').attr('src',base_url+'assets/images/no_image.png');
                });
            },
            fail: function(xhr, textStatus, errorThrown){
                remModalLoader();
                jQuery('[id="modal_content"]').html('Something went wrong, please try again later...!');
            },
            error: function (ajaxContext) {
                remModalLoader();
                jQuery('[id="modal_content"]').html('Something went wrong, please try again later...!');
        }
    });
});

jQuery('[id="viewEventDetails"]').on('click',function(event) {
  var event_id = jQuery(this).attr('event_id');

  if(event_id=='' || event_id==undefined || event_id=='undefined' || event_id==null || event_id=='null'){
    return true;
  }
  modalTrigger('Event Details','');
  addModalLoader();
  jQuery.ajax({
    url  : base_url+"Event/getEventData", 
    type : 'POST',
    data : {'event_id':event_id},
    success: function(resp){
      if(resp == '' || resp == undefined || resp == 'undefined' || resp == null || resp == 'null'){
        remModalLoader();
        jQuery('[id="modal_content"]').html('Something went wrong, please try again later...!');
        return false;
      }
      jQuery('[id="modal_content"]').html(resp);
      remModalLoader();
    },
    fail: function(xhr, textStatus, errorThrown){
      remModalLoader();
      jQuery('[id="modal_content"]').html('Something went wrong, please try again later...!');
    },
    error: function (ajaxContext) {
      remModalLoader();
      jQuery('[id="modal_content"]').html('Something went wrong, please try again later...!');
    }
  });
});

function viewBooking(booking_id){
  if(booking_id=='' || booking_id==undefined || booking_id=='undefined' || booking_id==null || booking_id=='null'){
    return true;
  }
  modalTrigger('Booking Details','');
  addModalLoader();
  jQuery.ajax({
    url  : base_url+"Booking/getBookingData", 
    type : 'POST',
    data : {'booking_id':booking_id},
    success: function(resp){
      if(resp == '' || resp == undefined || resp == 'undefined' || resp == null || resp == 'null'){
        remModalLoader();
        jQuery('[id="modal_content"]').html('Something went wrong, please try again later...!');
        return false;
      }
      jQuery('[id="modal_content"]').html(resp);
      remModalLoader();
    },
    fail: function(xhr, textStatus, errorThrown){
      remModalLoader();
      jQuery('[id="modal_content"]').html('Something went wrong, please try again later...!');
    },
    error: function (ajaxContext) {
      remModalLoader();
      jQuery('[id="modal_content"]').html('Something went wrong, please try again later...!');
    }
  });
}

jQuery('[id="viewBooking"]').on('click',function(event) {
  var booking_id = jQuery(this).attr('booking_id');
  if(booking_id=='' || booking_id==undefined || booking_id=='undefined' || booking_id==null || booking_id=='null'){
    return true;
  }
  viewBooking(booking_id);
});

function showLyDivDtls(thisObj){
  if(thisObj.attr('show') == '0'){
    thisObj.attr('show','1');
    thisObj.next("div").removeClass('hide');
  } else {
    thisObj.attr('show','0');
    thisObj.next("div").addClass('hide');
  }
}

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(document).ready(function(){
    jQuery('[name^="BOK.bookId"],[name^="CONCAT(EDT.date,\' \',EDT.time)"],[name^="BOK.amount"],[name^="BOK.status"],[name^="EVT.event_name"],[name^="CUST.name"]').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+"Booking/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" onclick="viewBooking('+data['Booking_ID']+');"><i class="fa fa-fw fa-edit"></i>View</a>';
          table.row.add([data['Book_ID'],data['Event_Name'],data['Customer_Name'],data['Amount'],data['Show_Time'],data['Book_Status'],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+'Booking/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('[name="locality_type"]').on('click',function(event) {
  var type = jQuery(this).val();

  if(type == 0){
    jQuery('[id="useExist"]').removeClass('hide');
    jQuery('[name="locality_id"]').prop("disabled",false);
    jQuery('[name="locality_id"]').addClass("required");

    jQuery('[id="addNew"]').addClass('hide');
    jQuery('[name="locality"]').prop("disabled",true);
    jQuery('[name="locality"]').removeClass("required");
  } else {
    jQuery('[id="addNew"]').removeClass('hide');
    jQuery('[name="locality"]').prop("disabled",false);
    jQuery('[name="locality"]').addClass("required");

    jQuery('[id="useExist"]').addClass('hide');
    jQuery('[name="locality_id"]').prop("disabled",true);
    jQuery('[name="locality_id"]').removeClass("required");
  }
});

jQuery('[name="region_id"]').on('change',function(){
  var thisObj = jQuery(this),
      region_id = thisObj.val();

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

  jQuery.ajax({
    url  : base_url+"Venue/getLocalityData", 
    type : 'POST',
    data : {'region_id':region_id},
    success: function(resp){
      if(resp == '' || resp == undefined || resp == 'undefined' || resp == null || resp == 'null'){
        return false;
      }
      var resp_data = jQuery.parseJSON(resp);
      if(resp_data['status'] == 0){

        jQuery('[id="showType"]').addClass('hide');
        jQuery('[id="localityLabel"]').removeClass('hide');

        jQuery('[id="addNew"]').removeClass('hide');
        jQuery('[name="locality"]').prop("disabled",false);
        jQuery('[name="locality"]').addClass("required");

        jQuery('[id="useExist"]').addClass('hide');
        jQuery('[name="locality_id"]').prop("disabled",true);
        jQuery('[name="locality_id"]').removeClass("required");
      }

      if(resp_data['status'] == 1){
        jQuery('[id="addNew"]').addClass('hide');
        jQuery('[name="locality"]').prop("disabled",true);
        jQuery('[name="locality"]').removeClass("required");

        jQuery('[id="useExist"]').removeClass('hide');
        jQuery('[name="locality_id"]').prop("disabled",false);
        jQuery('[name="locality_id"]').addClass("required");

        jQuery('[id="showType"]').removeClass('hide');
        jQuery('[id="localityLabel"]').addClass('hide');

        jQuery('[name="locality_id"]').html('');
        jQuery('[name="locality_id"]').html('<option selected disabled>Choose Venue Locality</option>');
        jQuery.each(resp_data['data'], function(key, data) {
          jQuery('[name="locality_id"]').append(jQuery("<option></option>").attr("value",data['id']).text(data['locality'])); 
        });
      }
    }
  });
});