<div class="modal fade" id="activity_modal" role="dialog" aria-labelledby="ModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header text-left">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true"><i class="pg-close fs-20"></i>
                </button>
                <h5 class="add-label h-labels text-left bold hidden"><?php echo CommonLanguage::getMessage('add_activity'); ?></h5>
                <h5 class="edit-label h-labels text-left bold hidden"><?php echo CommonLanguage::getMessage('edit_activity'); ?></h5>
            </div>
            <div class="modal-body">
                <div class="row">
                    <?php echo Forms::AlertDiv('activity_alert'); ?>
                </div>
                <form id="activity_form" method="POST" onsubmit="return false">
                    <input type="hidden" name="activity_id" id="activity_id">
                    <div class="row">
                        <div class="col-md-4">
                            <div id="smallcal"></div>
                        </div>
                        <div class="col-md-8">
                            <div class="row form-group">
                                <div class="activityEditor__form">
                                    <div class="contentWrapper">
                                        <div class="types responsiveRadioList">
                                            <label class="widget-radio" data-title="call">
                                                <input type="radio" name="activity_type_id" value="1" data-icon="call" data-title="call" checked data-content="<?php print CommonLanguage::getMessage('call'); ?>">
                                                <i class="fa fa-phone" style="color:#4c0870 !important"></i>
                                                <span><?php print CommonLanguage::getMessage('call'); ?></span>
                                            </label>
                                            <label id="default" class="widget-radio" data-title="meeting">
                                                <input type="radio" name="activity_type_id" value="2" data-content="<?php print CommonLanguage::getMessage('meeting'); ?>" >
                                                <i class="fa fa-users" style="color:#4c0870 !important" ></i>
                                                <span><?php print CommonLanguage::getMessage('meeting'); ?></span>
                                            </label>
                                            <label id="default" class="widget-radio" data-title="deadline">
                                                <input type="radio" name="activity_type_id" value="3" data-content="<?php print CommonLanguage::getMessage('deadline'); ?>">
                                                <i class="fa fa-flag" style="color:#4c0870 !important" ></i>
                                                <span><?php print CommonLanguage::getMessage('deadline'); ?></span>
                                            </label>
                                            <label id="default" class="widget-radio" data-title="task">
                                                <input type="radio" name="activity_type_id" value="4" data-content="<?php print CommonLanguage::getMessage('task'); ?>" >
                                                <i class="fa fa-clock-o" style="color:#4c0870 !important" ></i>
                                                <span><?php print CommonLanguage::getMessage('task'); ?></span>
                                            </label>
                                        </div>
                                        <div class="clear"></div>
                                    </div>
                                </div>
                            </div>
                            <div class="row form-group">
                                <label for="type"><?php print CommonLanguage::getMessage('title'); ?></label>
                                <input type="text" value="" name="activity_title" id="activity_title" class="activityTitle form-control">
                            </div>
                            <div class="row form-group">
                                <label for="notes"><?php print CommonLanguage::getMessage('notes'); ?></label>
                                <textarea type="text" id="activity_notes" name="activity_notes" class="form-control" ></textarea>
                            </div>
                            <div class="row form-group">
                                <div class="col-md-4">
                                    <label for="end"><?php print CommonLanguage::getMessage('Date'); ?></label>
                                    <span class="red-star">*</span>
                                    <input type="text" id="end_date" name="end_date" class="date form-control" required/>
                                </div>
                                <div class="col-md-4">
                                    <label for="time"><?php print CommonLanguage::getMessage('time'); ?></label>
                                    <span class="red-star">*</span>
                                    <input type="text" id="current_time" name="current_time" class="form-control" required />
                                </div>
                                <div class="col-md-4">
                                    <label for="duration"><?php print CommonLanguage::getMessage('duration'); ?></label>
                                    <span class="red-star">*</span>
                                    <input type="text" id="activity_duration" name="activity_duration" class="form-control" placeholder="" required/>
                                </div>
                            </div>
                            <div class="row form-group ">
                                <div class="col-md-4">
                                    <label for="organization"><?php print CommonLanguage::getMessage('organization'); ?></label>
                                    <span class="red-star">*</span>
                                    <input class="customer_id full-width empty" id="activity_organization_id" name="activity_organization_id" type="hidden" value="" data-select-name='' required/>
                                </div>
                                <div class="col-md-4">
                                    <label for="contact"><?php print CommonLanguage::getMessage('contacts'); ?></label>
                                    <input class="activity_contact_id full-width empty" id="activity_contact_id" name="activity_contact_id" type="hidden" value="" data-select-name='' />
                                </div>
                                <div class="col-md-4">
                                    <label for="deals"><?php print CommonLanguage::getMessage('deal'); ?></label>
                                    <input class="activity_deal_id full-width empty" id="activity_deal_id" name="activity_deal_id" type="hidden" value="" data-select-name=''/>
                                </div>
                            </div>
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <input type="checkbox" name="activity_checked" id=eventcheckbox> 
                <span id=eventcheckboxtext><?php print CommonLanguage::getMessage('mark_done'); ?></span>
                <button type="button" class="btn btn-default" data-dismiss="modal"><?php print CommonLanguage::getMessage('cancel'); ?></button>
                <button style="color:white !important;" id="submit_data" class="btn bg-complete-dark"><?php print CommonLanguage::getMessage('Save'); ?></button>
            </div>
        </div>
        <?php echo Forms::ModalLoader('activity_loader'); ?>
    </div>
</div>
<script>
    var activity_type = 1,activity_origin,
        modal_calendar_small = document.getElementById('smallcal'),
        is_cal_loaded_first_time = 0;
    $(function(){
        build_select2($("#activity_organization_id"), "xhr/getOrganizations")
        build_select2($("#activity_contact_id"), "xhr/getContacts?organization_id="+$("#activity_organization_id").val())
        build_select2($("#activity_deal_id"), "xhr/getDealsContact?contact_id="+$("#activity_contact_id").val()+"&organization_id="+$("#activity_organization_id").val())
        $("input[name=activity_type_id]").on("click",function(){
            activity_type = $(this).val()
            $("#activity_title").val($(this).attr('data-content'))
        });
        $("#activity_organization_id").on('change',function(){
            $("#activity_contact_id").val('');
            $("#activity_contact_id").attr('data-select-name','');
            build_select2($("#activity_contact_id"), "xhr/getContacts?organization_id="+$("#activity_organization_id").val())
        });
        $("#activity_contact_id").on('change',function(){
            build_select2($("#activity_deal_id"), "xhr/getDealsContact?contact_id="+$("#activity_contact_id").val()+"&organization_id="+$("#activity_organization_id").val())
        });
        $(".panel-body").on("click",'#add_activity,.add_activity',function(){
            activity_origin = $(this).attr('data-origin');
            $("#activity_modal .add-label").removeClass('hidden');
            $("#activity_id").val(0);
            $("#activity_title").val($("input[name=activity_type_id]:checked").attr('data-content'));
            $("#activity_duration").val("00:15");
            $('#end_date').data("DateTimePicker").date(new Date());
//            $('#end_date').datepicker("setDate",new Date());
            $("#current_time").data("DateTimePicker").date(new Date());
            $('#eventcheckbox').prop('checked',false);
            if(activity_origin !='calendar'){
                $("#activity_organization_id").val($(this).attr('data-customer-id')).attr('data-select-name',$(this).attr('data-customer-name')).trigger('change');
                $("#activity_organization_id").prop('disabled',true);
            }
            if(activity_origin =='cont_prof' || activity_origin =='deal_prof' || activity_origin =='pipeline'){
                $("#activity_contact_id").val($(this).attr('data-contact-id')).attr('data-select-name',$(this).attr('data-contact-name'));
                build_select2($("#activity_contact_id"), "xhr/getContacts?organization_id="+$(this).attr('data-customer-id'));
                $("#activity_contact_id").prop('disabled',true);
            }
            if(activity_origin =='deal_prof' || activity_origin =='pipeline'){
                $("#activity_deal_id").val($(this).attr('data-deal-id')).attr('data-select-name',$(this).attr('data-deal-title'));
                build_select2($("#activity_deal_id"), "xhr/getDealsContact?organization_id="+$(this).attr('data-customer-id')+"&contact_id="+$(this).attr('data-contact-id'));
                $("#activity_deal_id").prop('disabled',true);
            }
        });
        $('#activity_modal').on('shown.bs.modal',function(){
            if(is_cal_loaded_first_time == 0){
                modal_calendar = new FullCalendar.Calendar(modal_calendar_small, {
                    plugins: ['interactionPlugin','timeGrid' ],
                    header: {
                        left: 'prev,next',
                        center: 'title',
                        right: ''
                    },
                    defaultView:'timeGridDay',
                    borderColor:'black',
                    editable: true,
                    height: 350,
                    formatDate:'YYYY-mm-dd',
                    selectHelper: true,
                    minTime: "06:00:00",
                    maxTime: "24:00:00",
                    droppable: true, 
                    eventTextColor: "#fff",
                    events: "crmAjax/getAllActivities?type=&status_id=",
                });
                modal_calendar.render();
                is_cal_loaded_first_time = 1;
            }
        })
        $(".panel-body,#main-wrapper").on("click",".edit_activity",function(){
            var activity_id = $(this).attr("data-id");
            activity_origin = $(this).attr('data-origin');
            edit_activity_trigger(activity_id);
        });
        $("#end_date").datetimepicker({'format': 'YYYY-MM-DD'});
        //        $("#end_date").on("changeDate", function () {
        //            createEvent();
        //        });
        $("#current_time").datetimepicker({'format': 'HH:mm'});
        //        $("#current_time").on('dp.change', function () {
        //            var dur = "00:15";
        //            if ($("#activity_duration").val() != "")
        //                dur = $("#activity_duration").val();
        //            if ($("#current_time").val()) {
        //                var start = moment(new Date(moment($("#end_date").val()).format("YYYY-MM-DD") + " " + $("#current_time").val())).format('YYYY-MM-DD hh:mm:ss a');
        //                var end = moment(new Date(moment($("#end_date").val()).format("YYYY-MM-DD") + " " + $("#current_time").val())).add(dur.split(':')[0], 'hours').add(dur.split(':')[1], 'minutes').format(' YYYY-MM-DD hh:mm:ss a');
        //                createEvent(end, start);
        //            }
        //        });
        $("#activity_duration").timepicker({
            showMeridian: false,maxHours: 8,
            defaultTime:'00:15',step: '15',
        });
        //        $("#activity_duration").on('change', function () {
        //            if ($("#current_time").val() && $("#end_date").val()) {
        //                var start = moment(new Date(moment($("#end_date").val()).format("YYYY-MM-DD") + " " + $("#current_time").val())).format('YYYY-MM-DD hh:mm:ss a');
        //                var end = moment(new Date(moment($("#end_date").val()).format("YYYY-MM-DD") + " " + $("#current_time").val())).add($(this).val().split(':')[0], 'hours').add($(this).val().split(':')[1], 'minutes').format(' YYYY-MM-DD hh:mm:ss a');
        //                createEvent(end, start);
        //            }
        //        });
        $("#submit_data").on("click", function () {
            if (!$("#activity_form").valid())
                return;
            var Data = new FormData(document.getElementById("activity_form"));
            Data.append('current_activity_type_id',activity_type);
            Data.append('activity_checked',$('#eventcheckbox').is(":checked") ? 1 : 0)
            Data.append('organization_id',$('#activity_organization_id').val());
            Data.append('contact_id',$('#activity_contact_id').val());
            Data.append('deal_id',$('#activity_deal_id').val());
            $("#activity_loader").removeClass('hidden');
            $.ajax({
                url: "crmAjax/submitActivity",
                method: "POST",
                data: Data,
                processData: false,
                contentType: false,
                dataType: "JSON",
                complete: function (jqXHR, status) {
                    if (status == 'success') {
                        if (jqXHR.responseJSON[1] == "success") {
                            if(activity_origin == 'calendar'){
                                RebuildDataTable($('.panel-heading .panel-title').html(),[0,1,2,3,4,5,6,7],'crmAjax/activityList',{activity_type_id:typeoffilter,current_date:current_date,action_type_id:$('#action_type_id').val(),status_id:$('#status_id').val()})
                                renderCalendarEvent();
                            }else if(activity_origin == 'pipeline'){
                                getPipelineData();
                            }else if(activity_origin == 'cust_prof'){
                                loadlog(activity_origin, $("#org_id").val());
                                loadActivities($("#org_id").val())
                            }else if(activity_origin == 'cont_prof'){
                                loadlog(activity_origin, $("#org_id").val(),$("#current_contact_id").val());
                                loadActivities(0,0,$("#current_contact_id").val())
                            }else if(activity_origin == 'deal_prof'){
                                loadlog(activity_origin, $("#org_id").val(),$("#current_contact_id").val(),$("#current_deal_id").val());
                                loadActivities(0,$("#current_deal_id").val(),0)
                            }
                            hideModalAlert('activity_modal', 'activity_alert');
                        }
                        AddAlert("#activity_alert", jqXHR.responseJSON[0], jqXHR.responseJSON[1]);
                    }
                    $("#activity_loader").addClass('hidden');
                }
            });
        });
    });
    function renderModalCalendarEvent(){
        var eventSources = modal_calendar.getEventSources(); 
        var len = eventSources.length;
        for (var i = 0; i < len; i++) { 
            eventSources[i].remove(); 
        } 
        modal_calendar.addEventSource("crmAjax/getAllActivities?type=&status_id=");
    }
    function createEvent(end,start){
        var specific_event = modal_calendar.getEventById('eventtest');
        if(specific_event){
            specific_event.remove();
        }
        var b = {
            id: "eventtest",
            title: 'new',
            start: moment(start).format('YYYY-MM-DD hh:mm:ss a'),
            end: moment(end).format('YYYY-MM-DD hh:mm:ss a')
        };
        modal_calendar.addEvent(b);
    }
    function edit_activity_trigger(activity_id){
        $("#activity_modal .edit-label").removeClass('hidden');
        $("#activity_id").val(activity_id)
        CommonViewById("xhr/getElement",{rowId:activity_id,rowEntry:'id',table:'all_activities'},'#activity_loader',function(response){
            $("#activity_title").val(response[0].title)
            if(response[0].activity_type_id.trim()!=""){
                $("input[type=radio][value="+response[0].activity_type_id.trim()+"]").prop('checked',true);
                $("label.widget-radio").removeClass('active');
                $("label[data-title="+response[0].activity_type_id+"]").addClass('active');
            }
            activity_type = response[0].activity_type_id
            //insert html using code
            $("#activity_duration").val(response[0].activity_duration);
            $("#activity_notes").val(response[0].activity_notes);
            $("#end_date").val(moment(response[0]["start"]).format('YYYY-MM-DD'));
            $("#current_time").val(moment(response[0]["start"]).format('HH:mm'));
            if (response[0]['activity_checked'] == 1) {
                $("#eventcheckbox").parent().addClass('checked');
                $("#eventcheckbox").prop('checked', true);
            }else{
                $("#eventcheckbox").parent().removeClass('checked');
                $("#eventcheckbox").prop('checked', false); 
            }
            $("#activity_organization_id").val(response[0].organization_id)
            $("#activity_organization_id").attr('data-select-name',response[0].organization_customer_name)
            build_select2($("#activity_organization_id"), "xhr/getOrganizations")
            $("#activity_contact_id").val(response[0].contact_id)
            $("#activity_contact_id").attr('data-select-name',response[0].contact_name)
            build_select2($("#activity_contact_id"), "xhr/getContacts?organization_id="+response[0].organization_id)
            if(response[0].deal_title){
                $("#activity_deal_id").val(response[0].deal_id)
                $("#activity_deal_id").attr('data-select-name',response[0].deal_title)
                build_select2($("#activity_deal_id"), "xhr/getDealsContact?organization_id="+response[0].organization_id+"&contact_id="+response[0].contact_id) 
            }
            $("#activity_organization_id,#activity_contact_id,#activity_deal_id").prop('disabled',false);
        });
    }
</script>
