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

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

  if(validation){
    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="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 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');
  }
}
