var C_ADD     = "a" ;
var C_CHANGE  = "c" ;
var C_DELETE  = "d" ;
var C_EXPORT  = "e" ;
var C_GET     = "g";
var C_LIST    = "l" ;
var C_NEW     = "n";
var C_QUERY   = "q" ;
var C_REPORT  = "r" ;
var C_UPDATE  = "u" ;
var C_VIEW    = "v";
var C_LOGOUT  = "504";
var C_PWD   = "4";
var C_SORT = "so";

var C_OK    = "0";
var C_INFO    = "6" ;
var C_INVALID   = "7";
var C_CONFIRM   = "8" ;
var C_ERROR   = "9" ;

var C_LIST_CUSTOMER_VIEW = "510";

var record_obj = null;

$(document).ready(function () {
  //$("#cust_master").click();
  $('#btnChangePwd').click(function () {
		onChangePassword();
	});
});
function sortColumn(obj,column,order) {
    $(obj).attr("onclick",sortable(obj,column,order));
    record_obj = obj;
    // console.log(record_obj);

    var page_url = "", resp_func = "";
    var sort_name = $(obj).attr("name");
    // console.log(sort_name);
    switch(sort_name) {
        case "customer_sort_column":
            filterCustomer();
            break;
        case "contact_sort_column":
            filterContact();
            break;
        case "project_sort_column":
            filterProject();
            break;
        case "jobquotation_sort_column":
            filterJobQuotation();
            break;
        case "jobplan_sort_column":
            filterJobCentre();
            break;
        case "service_sort_column":
            filterActivity();
            break;
        case "jobbillingstatus_sort_column":
            filterReport(C_REPORT_JOB_BILLING_STATUS_FILTER);
            break;
        case "jobplanactual_sort_column":
            filterReport(C_REPORT_JOB_PLAN_ACTUAL_FILTER);
            break;
        case "planactualsummary_sort_column":
            filterReport(C_REPORT_PLAN_ACTUAL_SUMMARY_FILTER);
            break;
        case "salesquotationsummary_sort_column":
            filterSalesQuotationSummary();
            break;
        case "jobstatussummary_sort_column":
            filterReport(C_REPORT_JOB_STATUS_FILTER);
            break;
    }

    // var data = { 
    //     "type": type,
    //     "sorts" : sorts,
    // } ;
    // var url = "index.pzx?c=" + page_url + "&t=" + C_SORT  + "&d=" + new Date().getTime() ; 
    // callServer(url,"json",data,resp_func,record_obj) ;
}
function filterRow(filterRow, objBtn, stat) {
    if (stat) {
        $('#'+filterRow).show();
        $(objBtn).attr("onclick","filterRow('"+filterRow+"',this,false);");
    } else {
        $('#'+filterRow).hide();
        $(objBtn).attr("onclick","filterRow('"+filterRow+"',this,true);");
    }
}
function nextscreen() {
  screen_index++;
}
function prevscreen() {
  
  $('#screen'+(screen_index-1)+'a').html("");
  $('#screen'+(screen_index-1)+'a').hide();
  $('#screen'+(screen_index-1)+'').show();  
  screen_index--;
}
function showScreen(resp) {
    $("#subheader_title").html(resp.data.headTitle);
    /**fill the container at first index */
    // console.log("show screen home "+screen_index);
    // console.log(JSON.stringify(resp));
    if(screen_index == 0 ){
        $("#screen_container").html('');
        $("#screen_container").html(resp.data.htmlContent);
    }else{
        /**hide the previous index */
        $('#screen'+(screen_index-1)+'').hide();
        /**fill the index-1a or the next screen with HTML from controller */
        $('#screen'+(screen_index-1)+'a').html(resp.data.htmlContent);
        /**show the main power */
        $('#screen'+(screen_index-1)+'a').show();
    }
    window.scrollTo(0,0);
}
function gotoCustomerMasterPage() {
  var data = { "type": C_LIST_CUSTOMER_VIEW, "index": screen_index} ;
  var url = "index.pzx?c=" + customer_url + "&t=" + C_LIST_CUSTOMER_VIEW + "&d=" + new Date().getTime() ;
  alert(url);
  
  callServer(url,"json",data,onHomeResponse,null) ;
}
function showPage(page,desc,type) {
  screen_index = 0 ;
	showProgress("loading " + desc) ;
	var data = { "type": type , "index": screen_index } ;
	var url = "index.pzx?c=" + page + "&t=" + type  + "&d=" + new Date().getTime() ;
	
	callServer(url,"json",data,onHomeResponse,null) ;
}
function onHomeResponse(obj, resp) {
  /**fill the container at first index */

  // $("#subheader_title").html(resp.data.headTitle);
  // if(screen_index == 0 ){
  //   $("#screen_container").html(resp.data.htmlContent);
  // }else{
  //   showScreen(resp);
  // }
  showScreen(resp);
}
function onLogout() {
  screen_index = 0 ;
  var data = { "type": C_LOGOUT, "index": screen_index } ;
  var url = "request.pzx?c=" + home_url  +"&t=" + C_LOGOUT  + "&d=" + new Date().getTime() ;    
  callServer(url,"json",data,onLogoutResponse) ;
}
function onLogoutResponse(data) {
  openSite("index.pzx");
}
function showChangePassword(){
	$('#txtOldPwd').val("");
	$('#txtNewPwd1').val("");
	$('#txtNewPwd2').val("");
	$("#modalNewPassword").modal("show");
}
function showSettings(){

	$("#modalSettingsDashboard").modal("show");
}
function onChangePassword() {
	if($('#txtOldPwd').val() == ""){
		Swal.fire('Warning', "Please input your old password!", "warning");
		return;
	}
	if($('#txtNewPwd1').val() == ""){
		Swal.fire('Warning', "Please input your new password!", "warning");
		return;
	}
	if($('#txtNewPwd1').val() != $('#txtNewPwd2').val()){
		Swal.fire('Warning', "Confirm password does not match!", "warning");
		return;
	}
	if($('#txtNewPwd1').val() == $('#txtOldPwd').val()){
		Swal.fire('Warning', "Please use different password from your old password!", "warning");
		return;
	}
	var data = { "type": C_PWD,
                "oldPwd"	: $('#txtOldPwd').val(), 
                "newPwd"	: $('#txtNewPwd1').val()
              } ;
	var url = "request.pzx?c=" + home_url  +"&d=" + new Date().getTime() ;		
	callServer(url,"json",data,onChangePasswordResponse) ;
}
function onChangePasswordResponse(obj,resp) {
	if(resp.status != C_OK){
		Swal.fire('Error', resp.mesg, "error");
		return;
	}
	$("#modalNewPassword").modal('hide');
	Swal.fire('Success', "Password is changed!", "success");
}

function testing() {

  var data = { "type": "show_page_index", "index": screen_index} ;
  var url = "index.pzx?c=" + home_url + "&t=" + "show_page_index"  + "&d=" + new Date().getTime() ;
  
  callServer(url,"json",data,onHomeResponse,null) ;
}

function gotoinputscreen() {

  screen_index++;

  var data = { "type": "show_page_detail", "index": screen_index} ;
  var url = "index.pzx?c=" + home_url + "&t=" + "show_page_detail"  + "&d=" + new Date().getTime() ;
  // console.log(screen_index);
  callServer(url,"json",data,onHomeResponse,null) ;
}

function gotosubmitscreen() {

  screen_index++;
  
  var data = { "type": "show_page_submit", "index": screen_index} ;
  var url = "index.pzx?c=" + home_url + "&t=" + "show_page_submit"  + "&d=" + new Date().getTime() ;
  // console.log(screen_index);
  callServer(url,"json",data,onHomeResponse,null) ;
}
function showAgentScheduleDash(time_id) {
  var todayDate = new Date();
  var n_today = todayDate.getMonth();
  var y_today = todayDate.getFullYear();
  if (time_id==0) {
    n_today = n_today+1;
    
  } else if(time_id==1) {

    if(n_today+2 > 12){
      n_today = n_today + 2 - 12;

      y_today = y_today +1;
    }
    
  }else if(time_id==2) {

    if(n_today+2 > 12){
      n_today = n_today + 3 - 12;
      y_today = y_today +1;
    }
    
  }else{
    n_today = n_today+1;
  }

  // console.log(y_today);
  //   console.log(n_today);
  var data = { 
      "month"            : n_today,
     
      "year"             : y_today,
      "type"             : "C_AGENT_SCHEDULE_TABLE"
      };

  var url = "index.pzx?c=" + jobcentre_url + "&d=" + new Date().getTime() ;
  callServer(url,"json",data,onCalendarResponse,null) ;
  
}
function onCalendarResponse(obj,resp){

	if(resp.type == 'C_AGENT_SCHEDULE_TABLE'){
       
		$('#chartdiv5').html('');
        
        init_calendardash(
            resp.data.data,
            resp.data.start_time,
            resp.data.end_time,
            resp.data.date,
            resp.data.enddate
            );

			//$('.fc-timeGridWeek-button').trigger('click');   
        
    }else if (resp.type == "C_JOB_DETAIL_VIEW") {
        /*$('#jobDetailDashView').modal('show');
        $('#jobDetailDashViewViewContent').html(resp.data.htmlContent);
        
        $('#txtCentreCoyName').val(resp.data.coyname);
        $('#cobCentreCustCode').val(resp.data.cust);
        $('#cobCentreLocCode').val(resp.data.loc);
        $('#txtCentreLocContactName').val(resp.data.contactname);
        $('#txtCentreLocContactPhone').val(resp.data.contactphone);
        $('#txtCentreLocContactEmail').val(resp.data.contactemail);
        $('#txtCentreLocContactAddress').val(resp.data.address);
        $('#txtCentreJobNumber').val(resp.data.jobnumber);
        $('#txtCentreJobType').val(resp.data.jobtype);
        $('#txtCentreJobName').val(resp.data.jobname);
        $('#txtCentreJobConfirmDate').val(resp.data.jobconfirmdate);
        $('#txtCentreJobStartDate').val(resp.data.jobstartdate);
        $('#txtCentreTotalMandays').val(resp.data.totalmandays);
        $('#planEquipmentData-body').html(resp.data.jobcentre_list_equipment);*/

    }
}
function init_calendardash(data,start_time,end_time,start_date,end_date)  {
    
	var calendarEl = document.getElementById('chartdiv5');
	
    var todayDate = moment().startOf('day');
    var TODAY = todayDate.format('YYYY-MM-DD');
    var calendar = new FullCalendar.Calendar(calendarEl, {
      plugins: [ 'interaction', 'dayGrid', 'timeGrid', 'list' ],
      eventDrop: function(event) {
        saveEvent(event.event.start, event.event.end, event.event.id);
        },
        eventResize : function(event) {
            saveEvent(event.event.start, event.event.end, event.event.id);
        },
      header: {
        left: 'prev,next today',
        center: 'title',
        right: 'dayGridMonth'
      },
    
      validRange: {
        start: start_date,
        end: end_date
      },
     
      defaultDate: TODAY,
      navLinks: true, // can click day/week names to navigate views
      height: 700,
      contentHeight: 700,
      aspectRatio: 2,
      weekNumbers: true,
     // weekNumbersWithinDays: true,
      //weekNumberCalculation: 'ISO',

      nowIndicator: true,

      businessHours: [ // specify an array instead
        {
          daysOfWeek: [ 1, 2, 3, 4, 5 ,6], // Monday, Tuesday, Wednesday
          // startTime: start_time, // 8am
          // endTime: end_time // 6pm
        },
        // {
        //   daysOfWeek: [ 6 ], // Thursday, Friday
        //   startTime: '09:00', // 10am
        //   endTime: '13:00' // 4pm
        // }
      ],
     
        // minTime: '05:00',
        // maxTime: '20:00' ,
      editable: false,
      //eventLimit: true, // allow "more" link when too many events
      eventSources: [
            data
      ],
     //eventColor: '#378006',
      eventClick: function(info) {
        info.jsEvent.preventDefault(); // don't let the browser navigate
        //alert('Event: ' + info.event.groupId);
        //showJobDetailDash(info.event.groupId);
        
        if (info.event.url) {
          window.open(info.event.url);
        }
      },
      
    });
    
    calendar.render();
}
function convertTextToNumeric(value) {
  return value
    // Keep only digits and decimal points:
    .replace(/[^\d.]/g, "")
    // Remove duplicated decimal point, if one exists:
    .replace(/^(\d*\.)(.*)\.(.*)$/, '$1$2$3')
    // Keep only two digits past the decimal point:
    .replace(/\.(\d{2})\d+/, '.$1')
    // Add thousands separators:
    .replace(/\B(?=(\d{3})+(?!\d))/g, ",")
}
function removeCommas(value) {
  if(value != undefined) {
    if(value.includes(',')) {
      return value
        // Keep only digits and decimal points:
        .replace(/[^\d.]/g, "");
    } else {
      return value;
    }
  }
}