// Init global namespace
var WPADVERTS = WPADVERTS || {};

// Init CF namespace
WPADVERTS.CF = WPADVERTS.CF || {};

WPADVERTS.CF.DateField = function(field) {
    this.field = field;
    this.full = field.find("input.wpadverts-cf-input-full");
    this.date = field.find("input.wpadverts-cf-input-date");
    this.hours = field.find("input.wpadverts-cf-input-hours");
    this.minutes = field.find("input.wpadverts-cf-input-minutes");
    
    var params = {
        //dateFormat: this.date.data("dateFormat"),
        //autoSize: true,
        changeMonth: false,
        changeYear: true,
        yearRange: "c-90:c+10",
        onSelect: jQuery.proxy(this.Sync, this)
    };
    
    jQuery.extend( params, this.date.data() );
    
    this.date.datepicker( params );
    
    this.date.on("change", jQuery.proxy(this.SyncBlur, this));
    this.hours.on("change", jQuery.proxy(this.Sync, this));
    this.minutes.on("change", jQuery.proxy(this.Sync, this));
    
};

WPADVERTS.CF.DateField.prototype.Sync = function() {
    
    var pc = this.date.datepicker( "getDate" );
    var full = "";
    
    if(pc === null) {
        return;
    }
    
    full  = pc.getFullYear().toString() + "-";
    full += (pc.getMonth()+1).toString().padStart(2, '0') + "-"
    full += pc.getDate().toString().padStart(2, '0');
    
    if(this.hours.length > 0 && this.minutes.length > 0 ) {
        full += " " + this.hours.val().padStart(2, '0') + ":" + this.minutes.val().padStart(2, '0') + ":00";
    } else {
        full += " 00:00:00"; 
    }

    this.full.val(full);
};

WPADVERTS.CF.DateField.prototype.SyncBlur = function() {
 
    if(this.date.val().length === 0) {
        this.full.val("");
        this.date.datepicker( "setDate", null );
        return;
    } else if(this.date.val().length === 10 ) {
        this.date.datepicker( "setDate", this.date.val() );
        this.Sync();
    } else {
        this.full.val("");
        this.date.datepicker( "setDate", null );
    }
    
};

jQuery(function($) {
    $(".wpadverts-cf-date-field").each(function(index, item) {
        new WPADVERTS.CF.DateField($(item));
    });
});