$(document).on("ifClicked", '.vertical-timeline-block input[type=checkbox]', function (event) {
    event.stopPropagation();
    var checkthis = this;
    var checked = 1;
    if ($(this).prop("checked"))
        checked = 0;
    $(this).prop('disabled',true);
    $.ajax({
        url: "crmAjax/updateActivityStatus",
        type: "POST",
        data: { activity_id: $(this).attr("data-check-id"),activity_checked: checked },
        success: function () {
            $("body").attr("style", "height:auto !important");
            if (checked == 1) {
                $($(checkthis).parents()[4]).fadeOut(function () {
                    $.when($($(checkthis).parents()[4]).remove()).then(checkeventsstate());
                    loadlog($(this).attr('data-origin'), $("#org_id").val(),$("#current_contact_id").val(),$("#current_deal_id").val());
                });
            } else {
                $($(checkthis).parents()[4]).fadeOut(function () {
                    $.when($($(checkthis).parents()[4]).remove()).then(checkeventsstate());
                    loadActivities($("#org_id").val(),$("#current_deal_id").val() || 0,$("#current_contact_id").val() || 0)
                });
            }
        }
    });
});
function savenote(url, id,dealId,contactId,callBack) {
    $.ajax({
        url: url,
        type: "POST",
        data: {
            contact_id:contactId,
            deal_id:dealId,
            organization_id: id,
            note_content: $("#overall_note").val()
        },
        success: function() {
            $("#overall_note").val('')
            if(callBack)
                callBack()
        }
    });
}
function loadActivities(orgId=0,dealId=0,contactId=0){
    $.ajax({
        type: "POST",
        dataType: "JSON",
        url: "crmAjax/getPlannedOverDueActivity",
        data: {
            organization_id: orgId,
            deal_id: dealId,
            contact_id: contactId,
            divided: 1
        },
        success: function (data) {
            fillactivity(data['main'], [$("span[data-type=plan] #vertical-timeline"), $("span[data-type=overdue] #vertical-timeline")]);
            //            parentThis.timestampcal();
            checkeventsstate();
        },
        error: function () {
            console.log("something wrong occured");
        }
    });
}
function fillactivity(data, selector) {
    var planned = [];
    var overdue = [];
    selector[0].html("");
    selector[1].html("");
    //	selector[0].removeClass("animated fadeInDown");
    //selector[1].removeClass("animated fadeInDown");
    selector[0].addClass("animated fadeOutUp");
    selector[1].addClass("animated fadeOutUp");
    //selector[0].css("display","none");
    //selector[1].css("display","none");
    $.each(data, function (index, element) {
        var content = fillContent([element["title"], element['activity_type_title'], element['activity_notes'], element["id"], element['start'], null, element['id'], element['deal_title'], element['deal_id'],element['contact_name'],element['contact_id'],element['action_type_name']]);
        var today = moment().format("YYYY-MM-DD HH:mm:ss");
        $('.timeago',content).timeago();
        if (element['end'] > today)
            planned.push(content);
        else {
            overdue.push(content);;
        }
    });
    selector[0].append(planned.join(""));
    selector[1].append(overdue.join(""));
    $("#planevent").hide();
    $("#over").hide();
    //    parentThis.timestampcal();
    checkthecheckbox();
    selector[0].removeClass("animated fadeOutUp");
    selector[1].removeClass("animated fadeOutUp");
    $("body").attr("style", "height:" + $(document).height() + "px !important");
    selector[0].fadeIn(500);
    selector[1].fadeIn(500);
    checkeventsstate();
    $("body").attr("style", "height:auto !important");
}
function fillContent(argument){
    var icon = createicon(argument[1]);
    if(argument[8] != null && argument[8] != 0){
        var stringform = "<i class='fa fa-money'></i> " + "<a style='text-decoration:none'  href="+site_link+"crm/dealDetails/" + argument[8] + ">" + argument[7] + " ";
    }else{
        var stringform  = "";
    }
    var strper = "";
    if (argument[9] && argument[9] != "") {
        if(argument[9].match(',')){
            var splitper = argument[9].split(',');
            var splitperid = argument[10].split(',');
            for (var i = 0; i < splitper.length; i++) {
                strper += "<a style='text-decoration:none'  href="+site_link+"crm/contactProfile/" + splitperid[i].trim() + ">" + splitper[i] + ",";
            }
            stringform += "<i class='fa fa-user'></i> " + strper.substr(0, strper.length - 1);
        }
        else {
            strper += "<a style='text-decoration:none'  href="+site_link+"crm/contactProfile/" + argument[10] + ">" + argument[9]+ ",";	
            stringform += "<i class='fa fa-user'></i> " + strper.substr(0, strper.length - 1);
        }
    }
    var content = "<div class='vertical-timeline-block'> <div class='vertical-timeline-icon navy-bg'> <i class='" + icon + "'></i> </div> <div class='event vertical-timeline-content'><h3><label > <input data-check-id='" + argument[3] + "' type='checkbox' class='i-checks' " + argument[5] + " data-origin='"+$('#current_origin').val()+"'>  </label> <span class='upper'>" + argument[0] +(argument[11] ? (' - Action Type: '+argument[11]) : '')+ "</span> </h3> " + argument[2] +" <div>"+stringform+"</div> <a  href='javascript:void(0);' class='btn delevent hidden' data-row-id='" + argument[3] + "' >Delete</a><a  href='#' class='btn add edit_activity' data-deal-id='" + argument[6] + "'  data-event-name=edit data-id=" + argument[3] + "  data-toggle='modal' data-target='#activity_modal' data-origin='"+$('#current_origin').val()+"'>Edit</a> <span class='vertical-date'> <small><time class='timeago' datetime='" + moment(argument[4]).format("YYYY-MM-DDTHH:mm:ssZ") + "'></time> "+moment(argument[4]).format("YYYY-MM-DD")+" </small></span></div></div>";
    return content;
}
function checkthecheckbox  () {
    $('.i-checks').iCheck({
        checkboxClass: 'icheckbox_square-blue'
    });
}
function checkeventsstate(){
    var plannedcount = $("span[data-type=plan] div.vertical-timeline-block").length;
    var overduecount = $("span[data-type=overdue] div.vertical-timeline-block").length;
    if (plannedcount == 0) {
        $("#planevent").fadeOut();
    } else {
        $("#planevent").fadeIn();
    }
    if (overduecount == 0){
        $("#over").fadeOut();
    } else{
        $("#over").fadeIn(); 
    }
}
function loadlog(origin, id,contactId,dealId, cb) {
    var oldheight;
    $.ajax({
        url: 'crmAjax/getProfileLog',
        type: "GET",
        dataType: "JSON",
        data: {
            organization_id: id,
            contact_id:contactId,
            deal_id:dealId,
        },
        beforeSend: function () {
            $("#logfilter a").addClass("disabled");
            $("#infoo").remove();
            oldheight = $("#past #vertical-timeline").height();
            $("#past .identify").attr("id", "");
            $("#past .identify").html("<h2>Loading <i class='fa fa-circle-o-notch fa-spin '></i><h2>");
            $("#past .identify").attr("style", "height:1000px !important");
        },
        success: function (data) {
            $("#past .identify").fadeOut("slow", function () {
                $(this).html("");
                if(filterlogtype == 'activity' || filterlogtype == 'All'){
                    $.each(data['activity'], function (index, element) {
                        logcontent($("#past .identify"), [element['deal_title'], element['activity_notes'], element['id'], element['start'], element['deal_id'], element['contact_name'], element['contact_id'],element['title'],element['action_type_name']], null,origin);
                        $(".timeago").timeago();
                    }) 
                } 
                if(filterlogtype == 'log' || filterlogtype == 'All'){
                    $.each(data['log'], function (index, element) {
                        if(element['old_stage_id'] == 0 && element['new_stage_id'] ==0){
                            logcontent($("#past  .identify"), [element['deal_title'], element['log_date']], "", null);
                        }else{
                            logcontent($("#past  .identify"), [element['deal_title'], element['log_date'], "deal", element['deal_id'],element['old_stage'],element['new_stage']], "", null);
                        }
                        $(".timeago").timeago();
                    }) 
                }
                if(filterlogtype == 'statelog' || filterlogtype == 'All'){
                    $.each(data['state_log'], function (index, element) {
                        logcontent($("#past  .identify"), ["state", element['deal_state'], element['state_log_date'], null, element['deal_title'], element['deal_id']], "",null);
                        $(".timeago").timeago();
                    }) 
                } 
                if(filterlogtype == 'notelog' || filterlogtype == 'All'){
                    $.each(data['notes'], function (index, element) {
                        logcontent($("#past  .identify"), [element['note_id'], element['note_content'], element['note_date'], null, element['deal_title'], element['deal_id'], element['contact_name'], element['contact_id']], "note", "others");
                        $(".timeago").timeago();
                    }) 
                }
                if(filterlogtype == 'inv_ret' || filterlogtype == 'All'){
                    $.each(data['inv_ret'], function (index, element) {
                        logcontent($("#past  .identify"), element, "inv_ret", null);
                        $(".timeago").timeago();
                    }) 
                }
                //                    parentThis.timestampcal();
                checkthecheckbox();
                $("#past .identify").attr("id", "vertical-timeline");
                $("#past .identify").css("height", "auto");
                if ($(this).html() == "")
                    $(this).before("<h1 id='infoo'style='height:100%''>No recent Activity</h1>");
                else {
                    $("#infoo").remove();
                }
                var newheight = $(document).height() + $(this).height() - oldheight;
                $("body").attr("style", "height:" + newheight + "px !important");
                $(this).fadeIn("slow", function () {
                    $("#logfilter a").removeClass("disabled");
                });
                $("body").attr("style", "height:auto !important");
                $("#past .identify").attr("style", "height:auto !important");
                if (cb != null)
                    cb();
            });
        },
        error: function (error) {
            console.log("something went wrong");
        }
    });
}
function logcontent(selector, argument, classname, icon,origin) {
    selector.css("display", "none");
    var eventicon = createicon(icon);
    var mainpanel = $("<div>", {
        "class": "vertical-timeline-block"
    });
    var panelbody = $("<div>", {
        "class": "event vertical-timeline-content"
    });
    var itemheader = $("<div>", {
        "class": "vertical-timeline-icon navy-bg"
    });
    var icon2 = $("<i>", {
        "class": eventicon
    });
    if(classname=="note"){
        var stringform = "";
        if (argument[4] && argument[4] != null)
            stringform += "<i class='fa fa-money'></i> " + "<a style='text-decoration:none'  href="+site_link+"/crm/dealDetails/" + argument[5] + ">" + argument[4] + " ";
        if (argument[6] && argument[6] != "")
            stringform += "<i class='fa fa-user'></i> " + "<a style='text-decoration:none'  href="+site_link+"/crm/customerProfile/" + argument[7] + ">" + argument[6] + " ";
        $(panelbody).append("<h3>Notes</h3><div class='editasnote  expanddiv' data-id='" + argument[0] + "'> " + argument[1] + "</div><div>"+stringform+"</div><a  href='javascript:void(0);' class='btn notedel hidden' data-row-id='" + argument[0] + "' >Delete</a><a  href='javascript:void(0);' class='btn noteedit  hidden' data-event-name='edit' data-id='" + argument[0] + "'>Edit</a><span class='vertical-date'><small><time class='timeago' datetime='" + moment(argument[2]).format("YYYY-MM-DDTHH:mm:ssZ") + "' ></time> "+moment(argument[2]).format("YYYY-MM-DD")+" </small></span>");
        $(panelbody).css("background","#feff99");
    }else if(classname =="inv_ret"){
         $(panelbody).append("<span>"+argument['current_type']+': '+argument['inv_ret_nb']+" ( "+argument['current_net_total']+' '+argument['Currency_Symbol']+")</span><span class='vertical-date pull-right'>\
<small> <time class='timeago' datetime='" + moment(argument['date_created']).format("YYYY-MM-DDTHH:mm:ssZ") + "' ></time> - " + moment(argument['date_created']).format("YYYY-MM-DD") + "</small></span>");
    }else {
        if (classname == null) {
            $(itemheader).append(icon2);
            var div = $("<div>").append(argument[1]);
            var text = "";
            if (argument[1] && argument[1] != "")
                var text = '<div class="editasnote expanddiv ">' + argument[1] + '</div>';
            if ($(text).text().trim() == "")
                text = "<br>";
            text=text.replace(/&amp;/g,'');
            var stringform = "";
            if (argument[0] && argument[0] != null && argument[0] != 0)
                stringform += "<i class='fa fa-money'></i> " + "<a style='text-decoration:none'  href="+site_link+"crm/dealDetails/" + argument[4] + ">" + argument[0] + " ";
            var strper = "";
            if (argument[5] && argument[5] != "") {
                var splitper = argument[5].split(',');
                var splitperid = argument[6].split(',');
                for (var i = 0; i < splitper.length; i++) {
                    strper += "<a style='text-decoration:none'  href="+site_link+"crm/customerProfile/" + splitperid[i].trim() + ">" + splitper[i] + ",";
                }
                stringform += "<i class='fa fa-user'></i> " + strper.substr(0, strper.length - 1);
            }
            $(panelbody).append("<h3>  <label ><input  checked data-check-id='" + argument[2] + "' type='checkbox' class='i-checks' data-origin='"+$('#current_origin').val()+"' ></label> <span class='upper'>" + argument[7] +(argument[8] ? (' - Action Type :'+argument[8]) : '')+ "</span> </h3>" + text + "<div>"+stringform+"</div>\
<a  href='javascript:void(0);' class='btn delevent hidden' data-row-id=" + argument[2] + " >Delete</a>\
<a  href='#' class='btn add  edit_activity' data-event-name=edit data-id='" + argument[2] + "' data-toggle='modal' data-target='#activity_modal' data-origin='"+$('#current_origin').val()+"'>Edit</a><span class='vertical-date'>\
<small><time class='timeago' datetime='" + moment(argument[3]).format("YYYY-MM-DDTHH:mm:ssZ") + "' ></time> " + moment(argument[3]).format("YYYY-MM-DD") + "</small>\
</span>");
        } else {
            if (argument[0] == "state") {
                if (argument[1] != "Lost")
                    $(panelbody).append("State changed to <span class='dealwon'>" + argument[1] + "</span> for <a style='color:black;' href="+site_link+"dealDetails/" + argument[5] + "> " + argument[4] + " </a>  : <br> <span class='vertical-date'>\
<small> <time class='timeago' datetime='" + moment(argument[2]).format("YYYY-MM-DDTHH:mm:ssZ") + "' ></time>  " + moment(argument[2]).format("YYYY-MM-DD") + "</small>\
</span>");
                else {
                    $(panelbody).append("State changed to <span class='deallost'>" + argument[1] + "</span> for <a href="+site_link+"dealDetails/" + argument[5] + ">" + argument[4] + "</a> : <br> <span class='vertical-date'>\
<small> <time class='timeago' datetime='" + moment(argument[2]).format("YYYY-MM-DDTHH:mm:ssZ") + "' ></time> " + moment(argument[2]).format("YYYY-MM-DD") + "</small>\
</span> <br>Reason " + argument[3]);
                }
            } else {
                var hyperlink = argument[0];
                if (argument[2] == "deal"){
                    var hyperlink = "Deal Changed from ("+argument[4]+") to ("+argument[5]+") <br>";
                }else{
                    hyperlink = "Created: <br>";
                }
                $(panelbody).append(hyperlink + " <span class='vertical-date'>\
<small> <time class='timeago' datetime=" + moment(argument[1]).format("YYYY-MM-DDTHH:mm:ssZ") + " ></time> " + moment(argument[1]).format("YYYY-MM-DD") + "</small>\
</span>");
            }
            $(panelbody).css({
                "background": "transparent",
                "padding": "0"
            });
            $(panelbody).removeClass("event");
        }
    }
    $(mainpanel).append(itemheader);
    $(mainpanel).append(panelbody);
    selector.append(mainpanel);
    checkeventsstate();
}
function createicon(icon){
    var icon2 = "fa ";
    switch (icon) {
        case 'Meeting':
            icon2 += " " + "fa-users"
            break;
        case 'Call':
            icon2 += " " + "fa-phone"
            break;
        case 'Deadline':
            icon2 += " " + "fa-flag"
            break;
        case 'Task':
            icon2 += " " + "fa-clock-o"
            break;
        default:
            icon2 += " " + "fa-file-o"
            break;
                }
    return icon2;
}