﻿var calendarId = "";
var calendar = new Object();
var calendarLabel = new Array();
var calendarDisplayMultipleLabel = [];
var calendarDisplayField = new Array();
var _entityDynamicFetch = "";

//var calendarDisplayLabel = new Array();
//var calendarDisplay = new Object();
var isFind = true;
var colors = Array();
var Valuecolors = "";
var attributeValues = Array();
function retieveCalendar() {
    calendarId = getQuerystring("data").replace("%7b","").replace("%7d","");
    //if (calendarId != "" && calendarId.indexOf("}") == -1) {
    //    calendarId = calendarId + "}";
    //}

    var CalendarFetchRequest = '<fetch distinct="false" mapping="logical" output-format="xml-platform" version="1.0">';
    CalendarFetchRequest += '<entity name="mtccup_calendar">';
    CalendarFetchRequest += '<attribute name="mtccup_calendarid"/>';
    CalendarFetchRequest += '<attribute name="mtccup_name"/>';
    CalendarFetchRequest += '<attribute name="mtccup_queryid"/>';
    CalendarFetchRequest += '<attribute name="mtccup_entity"/>';
    CalendarFetchRequest += '<attribute name="mtccup_startdate"/>';
    CalendarFetchRequest += '<attribute name="mtccup_enddate"/>';
    CalendarFetchRequest += '<attribute name="mtccup_filters"/>';
    CalendarFetchRequest += '<attribute name="mtccup_iscolor"/>';
    CalendarFetchRequest += '<attribute name="mtccup_display"/>';
    CalendarFetchRequest += '<attribute name="mtccup_labelfields"/>';

    CalendarFetchRequest += '<attribute name="mtccup_displaymultiplefields"/>';
    CalendarFetchRequest += '<attribute name="mtccup_organizationstarttime"/>';
    CalendarFetchRequest += '<attribute name="mtccup_organizationendtime"/>';
    CalendarFetchRequest += '<attribute name="mtccup_attributename"/>';
    CalendarFetchRequest += '<attribute name="mtccup_attributevalue"/>';
    CalendarFetchRequest += '<attribute name="mtccup_valuewithcolor"/>';
    CalendarFetchRequest += '<attribute name="mtccup_viewmode"/>';
    CalendarFetchRequest += '<attribute name="mtccup_viewtype"/>';
    CalendarFetchRequest += '<attribute name="mtccup_showsidebar"/>';
    CalendarFetchRequest += '<attribute name="mtccup_showtopbar"/>';
    CalendarFetchRequest += '<attribute name="mtccup_showfiltercolor"/>';
    CalendarFetchRequest += '<order descending="false" attribute="mtccup_name"/>';
    CalendarFetchRequest += '<filter type="and">';
    CalendarFetchRequest += '<condition attribute="mtccup_calendarid" operator="eq" value="' + calendarId + '" />';
    CalendarFetchRequest += '</filter>';
    CalendarFetchRequest += '</entity>';
    CalendarFetchRequest += '</fetch>';

    var CalendarObj = new Object();
    CalendarObj.fetchXml = CalendarFetchRequest;
    CalendarObj.successCallback = CalendarDataSuccess;
    CalendarObj.errorCallback = function (e) {
        alert(e.message);
    };
    CalendarObj.async = true;
    XrmSvcToolkit.fetch(CalendarObj);
}

function CalendarDataSuccess(opts) {
    //alert("success");
    //debugger;
    isFind = true;
    $("#validateDiv").remove();

    if (opts.entities.length > 0) {
        if (opts.entities[0].mtccup_name != null) {
            calendar.Name = opts.entities[0].mtccup_name;
            $("#CalendarName").text(opts.entities[0].mtccup_name);
        }
        if (opts.entities[0].mtccup_entity != undefined && opts.entities[0].mtccup_entity != null) {
            calendar.EntityLogicalName = opts.entities[0].mtccup_entity;
            entityName = opts.entities[0].mtccup_entity;
        } else {
            var validateDiv = $('<div/>', { text: 'You must provide value for EntityList.', id: 'validateDiv', style: 'height:50px;width:500px;font-family:Arial,Helvetica,Sans-serif;font-size:18px;color:#000000;text-align:center;' }).appendTo($("#validateingdiv"));
            isFind = false;
        }
        if (isFind == true) {
            if (opts.entities[0].mtccup_startdate != undefined && opts.entities[0].mtccup_startdate != null)
                calendar.StartDateLogicalName = opts.entities[0].mtccup_startdate;
            else {
                var validateDiv = $('<div/>', { text: 'You must provide value for StartDate.', id: 'validateDiv', style: 'height:50px;width:500px;font-family:Arial,Helvetica,Sans-serif;font-size:18px;color:#000000;text-align:center;' }).appendTo($("#validateingdiv"));
                isFind = false;
            }
        }
        if (isFind == true) {
            if (opts.entities[0].mtccup_enddate != undefined && opts.entities[0].mtccup_enddate != null)
                calendar.EndDateLogicalName = opts.entities[0].mtccup_enddate;
            else {
                var validateDiv = $('<div/>', { text: 'You must provide value for EndDate.', id: 'validateDiv', style: 'height:50px;width:500px;font-family:Arial,Helvetica,Sans-serif;font-size:18px;color:#000000;text-align:center;' }).appendTo($("#validateingdiv"));
                isFind = false;
            }
        }
        if (isFind == true) {
            if (opts.entities[0].mtccup_filters != undefined && opts.entities[0].mtccup_filters != null)
                calendar.FilterstLogicalName = opts.entities[0].mtccup_filters;
            else {
                var validateDiv = $('<div/>', { text: 'You must provide value for Filters.', id: 'validateDiv', style: 'height:50px;width:500px;font-family:Arial,Helvetica,Sans-serif;font-size:18px;color:#000000;text-align:center;' }).appendTo($("#validateingdiv"));
                isFind = false;
            }
        }
        if (isFind == true) {
            if (opts.entities[0].mtccup_iscolor != undefined && opts.entities[0].mtccup_iscolor != null)
                calendar.IsColorLogicalName = opts.entities[0].mtccup_iscolor;
            else {
                var validateDiv = $('<div/>', { text: 'You must provide value for Iscolor.', id: 'validateDiv', style: 'height:50px;width:500px;font-family:Arial,Helvetica,Sans-serif;font-size:18px;color:#000000;text-align:center;' }).appendTo($("#validateingdiv"));
                isFind = false;
            }
        }
        if (isFind == true) {
            if (opts.entities[0].mtccup_organizationstarttime != undefined && opts.entities[0].mtccup_organizationstarttime != null)
                calendar.organizationstarttime = opts.entities[0].mtccup_organizationstarttime;
            else
                calendar.organizationstarttime = "0:00 AM";
        }
        if (isFind == true) {
            if (opts.entities[0].mtccup_organizationendtime != undefined && opts.entities[0].mtccup_organizationendtime != null)
                calendar.organizationendtime = opts.entities[0].mtccup_organizationendtime;
            else
                calendar.organizationendtime = "11:59 PM";
        }

        if (isFind == true) {
            if (opts.entities[0].mtccup_attributename != undefined && opts.entities[0].mtccup_attributename != null)
                calendar.attributeLogicalname = opts.entities[0].mtccup_attributename;
            else
                picklistattribute = "empty";
        }

        if (isFind == true) {
            if (opts.entities[0].mtccup_viewmode != undefined && opts.entities[0].mtccup_viewmode != null) {
                if (opts.entities[0].mtccup_viewmode == true) {
                    _viewMode = "timeline";
                } else {
                    _viewMode = "calendar";
                }
            } else {
                _viewMode = "calendar";
            }
        }

        if (isFind == true) {
            if (opts.entities[0].mtccup_showsidebar != undefined && opts.entities[0].mtccup_showsidebar != null) {
                if (opts.entities[0].mtccup_showsidebar == true) {
                    _isSideBar = true;
                } else {
                    _isSideBar = false;
                }
            } else {
                _isSideBar = true;
            }
        }
        if (isFind == true) {
            if (opts.entities[0].mtccup_showtopbar != undefined && opts.entities[0].mtccup_showtopbar != null) {
                if (opts.entities[0].mtccup_showtopbar == true) {
                    _isTopBar = true;
                } else {
                    _isTopBar = false;
                }
            } else {
                _isTopBar = true;
            }
        }
        if (isFind == true) {
            if (opts.entities[0].mtccup_showfiltercolor != undefined && opts.entities[0].mtccup_showfiltercolor != null) {
                if (opts.entities[0].mtccup_showfiltercolor == true) {
                    _isFilterColor = true;
                } else {
                    _isFilterColor = false;
                }
            } else {
                _isFilterColor = false;
            }
        }

        if (isFind == true) {
            if (opts.entities[0].mtccup_viewtype != undefined && opts.entities[0].mtccup_viewtype != null) {
                if (opts.entities[0].mtccup_viewtype.Value == 1) {
                    _viewType = "day";
                } else if (opts.entities[0].mtccup_viewtype.Value == 2) {
                    _viewType = "week";
                } else if (opts.entities[0].mtccup_viewtype.Value == 3) {
                    _viewType = "month";
                }
            } else {
                _viewType = "day";
            }
        }
        if (opts.entities[0].mtccup_display != undefined && opts.entities[0].mtccup_display != null)
            calendar.DisplayLogicalName = opts.entities[0].mtccup_display;
        if (opts.entities[0].mtccup_displaymultiplefields != undefined && opts.entities[0].mtccup_displaymultiplefields != null) {
            var labelsFileds = opts.entities[0].mtccup_displaymultiplefields.split("$");
            for (var i = 0; i < labelsFileds.length - 1; i++) {
                calendarDisplayMultipleLabel[i] = new Object();
                calendarDisplayMultipleLabel[i].labelLogicalName = labelsFileds[i].split(",")[0];
                calendarDisplayMultipleLabel[i].labelType = labelsFileds[i].split(",")[1];
                calendarDisplayMultipleLabel[i].labelName = labelsFileds[i].split(",")[2];
            }
        }

        if (opts.entities[0].mtccup_labelfields != undefined && opts.entities[0].mtccup_labelfields != null) {
            var labelsFileds = opts.entities[0].mtccup_labelfields.split("$");
            for (var i = 0; i < labelsFileds.length - 1; i++) {
                calendarLabel[i] = new Object();
                calendarLabel[i].labelLogicalName = labelsFileds[i].split(",")[0];
                calendarLabel[i].labelType = labelsFileds[i].split(",")[1];
                calendarLabel[i].labelName = labelsFileds[i].split(",")[2];
            }
        }

        if (opts.entities[0].mtccup_queryid != undefined && opts.entities[0].mtccup_queryid != null) {
            calendar.QueryId = opts.entities[0].mtccup_queryid.Id;
            calendar.QueryLogicalName = opts.entities[0].mtccup_queryid.LogicalName;
        }

        if (opts.entities[0].mtccup_valuewithcolor != undefined && opts.entities[0].mtccup_valuewithcolor != null) {
            valuewithcolor = opts.entities[0].mtccup_valuewithcolor;
            Valuecolors = valuewithcolor.split(";");
            for (var i = 0; i < Valuecolors.length; i++) {
                colors[Valuecolors[i].split(":")[0]] = new Object();
                colors[Valuecolors[i].split(":")[0]]["BGColor"] = Valuecolors[i].split(":")[1];
                colors[Valuecolors[i].split(":")[0]]["FColor"] = Valuecolors[i].split(":")[2];
            }
        }

        if (opts.entities[0].mtccup_attributevalue != undefined && opts.entities[0].mtccup_attributevalue != null) {
            attributevalue = opts.entities[0].mtccup_attributevalue;
            calendar.attributeValues = attributevalue.split(";");
        }

        if (isFind == true) {
            SDK.Metadata.RetrieveEntity(SDK.Metadata.EntityFilters.All, calendar.EntityLogicalName, null, true, function (e) {
                var args = new Object();
                args.metadata = new Object();
                args.metadata[calendar.EntityLogicalName] = e;
                if (args.metadata[calendar.EntityLogicalName] != null)
                    entityObjectCode = args.metadata[calendar.EntityLogicalName].ObjectTypeCode;
                primaryIdAttribute = args.metadata[calendar.EntityLogicalName].PrimaryIdAttribute;
                retrieveRollUpQuery();
            }, function (e) {
                alert("error in retrieving mtc_calender metadata");
            }, true);

            //retrieveCalendarDisplay();
            //retrieveRollUpQuery();
            $("#example")[0].disabled = false;
            $("#calendar")[0].disabled = false;
            $("#filterSelectAllLabel")[0].disabled = false;
            $("#filterUnselectAllLabel")[0].disabled = false;
            $("#grouptable")[0].disabled = false;
            $("#refreshLoadBtn")[0].disabled = false;
        } else {
            //$("#example")[0].disabled = true;
            $("#calendar")[0].disabled = true;
            $("#filterSelectAllLabel")[0].disabled = true;
            $("#filterUnselectAllLabel")[0].disabled = true;
            $("#grouptable")[0].disabled = true;
            $("#refreshLoadBtn")[0].disabled = true;
            HideLoadingPanel();
            HideCalendarLoadingPanel();
        }
    } else {
        isFind = false;
        HideLoadingPanel();
        HideCalendarLoadingPanel();
    }
}

function retrieveRollUpQuery() {
    if (calendar.QueryId != null) {
        XrmSvcToolkit.retrieve({
            entityName: "GoalRollupQuery",
            id: calendar.QueryId,
            //select: null,
            expand: null,
            async: false,
            successCallback: retrieveQuerySuccess,
            errorCallback: function (e) {
                alert(e.message);
            }
        });
    } else {
        if (_viewType == "day") {
            retrieveRecords(new Date(), new Date());
        } else if (_viewType == "week") {
            var date = new Date();

            var day = date.getDay();
            if (day == 1) {
                var firstday = date;
                var lastday = new Date(date.getFullYear(), date.getMonth(), date.getDate() + 6);
            }
            if (day == 0) {
                var lastday = date;
                var firstday = new Date(date.getFullYear(), date.getMonth(), date.getDate() - 6);
            } else {
                var firstday = new Date(date.getFullYear(), date.getMonth(), date.getDate() - (day - 1));
                var lastday = new Date(date.getFullYear(), date.getMonth(), date.getDate() + 6);
            }

            //var firstday = new Date(date.setDate(date.getDate() - date.getDay()));
            //var lastday = new Date(date.setDate(date.getDate() - date.getDay() + 6));
            retrieveRecords(firstday, lastday);
        } else if (_viewType == "month") {
            var date = new Date();
            if (_viewMode == "timeline") {
                var monthfirstDay = new Date(date.getFullYear(), date.getMonth(), 1);
                var monthlastDay = new Date(date.getFullYear(), date.getMonth() + 1, 0);
                retrieveRecords(monthfirstDay, monthlastDay);
            } else {
                //if (StartDate.getDate() > 20) {
                //    selecteddate = new Date(StartDate.getFullYear(), StartDate.getMonth() + 1, 1);
                //}
                //else
                //    selecteddate = StartDate;
                var firstDay = $("tbody > tr:first > td:first > a", $("#calendar")).data("value").split("/");
                var lastDay = $("tbody > tr:last > td:last > a", $("#calendar")).data("value").split("/");
                var monthfirstDay = new Date(firstDay[0], firstDay[1], firstDay[2]);
                var monthlastDay = new Date(lastDay[0], lastDay[1], lastDay[2]);
                retrieveRecords(monthfirstDay, monthlastDay);
            }
        }
        //retrieveRecords(new Date(), new Date());
    }
}

function retrieveQuerySuccess(query) {
    //debugger;
    // alert("alert");
    var fetchXml = query.FetchXml;
    var queryfetchXml = $(fetchXml);
    var queryXML = "";
    var filter = "";

    //var Xml = "";
    if (calendar.DisplayLogicalName != null) {
        if (queryfetchXml.find('[name=' + calendar.DisplayLogicalName.split(",")[0] + ']').length == 0)
            $('<attribute name="' + calendar.DisplayLogicalName.split(",")[0] + '" />').appendTo(queryfetchXml.find("entity"));
    }

    if (calendarDisplayMultipleLabel != null) {
        if (calendarDisplayMultipleLabel.length > 0) {
            for (var i = 0; i < calendarDisplayMultipleLabel.length; i++) {
                if (calendarDisplayMultipleLabel[i].labelLogicalName != null) {
                    if (queryfetchXml.find('[name=' + calendarDisplayMultipleLabel[i].labelLogicalName + ']').length == 0)
                        $('<attribute name="' + calendarDisplayMultipleLabel[i].labelLogicalName + '" />').appendTo(queryfetchXml.find("entity"));
                }
            }
        }
        //else if (queryfetchXml.find('[name=' + calendarDisplayMultipleLabel.split(",")[0] + ']').length == 0)
        //    $('<attribute name="' + calendarDisplayMultipleLabel.split(",")[0] + '" />').appendTo(queryfetchXml.find("entity"));
    }

    if (queryfetchXml.find('[name=' + calendar.StartDateLogicalName + ']').length == 0)
        $('<attribute name="' + calendar.StartDateLogicalName + '" />').appendTo(queryfetchXml.find("entity"));

    if (queryfetchXml.find('[name=' + calendar.EndDateLogicalName + ']').length == 0)
        $('<attribute name="' + calendar.EndDateLogicalName + '" />').appendTo(queryfetchXml.find("entity"));

    if (calendar.FilterstLogicalName != null) {
        if (queryfetchXml.find('[name=' + calendar.FilterstLogicalName.split(",")[0] + ']').length == 0)
            $('<attribute name="' + calendar.FilterstLogicalName.split(",")[0] + '" />').appendTo(queryfetchXml.find("entity"));
    }
    for (var i = 0; i < calendarLabel.length; i++) {
        if (calendarLabel[i].labelLogicalName != null) {
            if (queryfetchXml.find('[name=' + calendarLabel[i].labelLogicalName + ']').length == 0)
                $('<attribute name="' + calendarLabel[i].labelLogicalName + '" />').appendTo(queryfetchXml.find("entity"));
        }
    }
    if (queryfetchXml.find('[name=' + calendar.EndDateLogicalName + ']').length == 0)
        $('<attribute name="' + calendar.EndDateLogicalName + '" />').appendTo(queryfetchXml.find("entity"));
    if (calendar.attributeLogicalname != undefined && calendar.attributeLogicalname != null) {
        if (queryfetchXml.find('[name=' + calendar.attributeLogicalname + ']').length == 0)
            $('<attribute name="' + calendar.attributeLogicalname + '" />').appendTo(queryfetchXml.find("entity"));
    }

    //if (queryfetchXml.find('[name=' + calendar.organizationstarttime + ']').length == 0)
    //    $('<attribute name="' + calendar.organizationstarttime + '" />').appendTo(queryfetchXml.find("entity"));
    //if (queryfetchXml.find('[name=' + calendar.organizationendtime + ']').length == 0)
    //    $('<attribute name="' + calendar.organizationendtime + '" />').appendTo(queryfetchXml.find("entity"));
    //for (var i = 0; i < calendar.Valuecolors.length; i++) {
    //    if (calendar.Valuecolors[i] != null) {
    //        if (queryfetchXml.find('[name=' + calendar.Valuecolors[i].split(":")[1] + ']').length == 0)
    //            $('<attribute name="' + calendar.Valuecolors[i].split(":")[1] + '" />').appendTo(queryfetchXml.find("entity"));
    //    }
    //}
    //for (var i = 0; i < calendar.attributeValues.length; i++) {
    //    if (calendar.attributeValues[i] != null) {
    //        if (queryfetchXml.find('[name=' + calendar.attributeValues[i] + ']').length == 0)
    //            $('<attribute name="' + calendar.attributeValues[i] + '" />').appendTo(queryfetchXml.find("entity"));
    //    }
    //}
    // filter = '<order attribute="name" descending="false" /><filter type="and"><filter type="and"><condition attribute="' + calendar.StartDateLogicalName + '" operator="on-or-after" value="' + DateFormatChangeingIntoCalenderFormat(new Date(), "activity") + '"/><condition attribute="' + calendar.EndDateLogicalName + '" operator="on-or-before" value="' + DateFormatChangeingIntoCalenderFormat(new Date(), "activity") + '" /></filter></filter>';
    //queryXML = queryfetchXml.find('entity');
    //$(Xml).appendTo(queryXML);
    // queryXML = queryfetchXml[0].outerHTML; //queryXML[0].innerHTML;
    _entityDynamicFetch = queryfetchXml[0].outerHTML; // "<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>" + queryXML + "</fetch>";
    if (entityObjectCode == null) {
        setTimeout(function () {
            retrieveRecordCalling();
        }, 100);
    } else {
        if (_viewType == "day") {
            retrieveRecords(new Date(), new Date());
        } else if (_viewType == "week") {
            var date = new Date();
            var firstday = new Date(date.setDate(date.getDate() - date.getDay()));
            var lastday = new Date(date.setDate(date.getDate() - date.getDay() + 6));
            retrieveRecords(firstday, lastday);
        } else if (_viewType == "month") {
            var date = new Date();
            var monthfirstDay = new Date(date.getFullYear(), date.getMonth(), 1);
            var monthlastDay = new Date(date.getFullYear(), date.getMonth() + 1, 0);
            retrieveRecords(monthfirstDay, monthlastDay);
        }
    }
}
function retrieveRecordCalling() {
    if (entityObjectCode == null) {
        setTimeout(function () {
            retrieveRecordCalling();
        }, 100);
    } else {
        if (_viewType == "day") {
            retrieveRecords(new Date(), new Date());
        } else if (_viewType == "week") {
            var date = new Date();
            var firstday = new Date(date.setDate(date.getDate() - date.getDay()));
            var lastday = new Date(date.setDate(date.getDate() - date.getDay() + 6));
            retrieveRecords(firstday, lastday);
        } else if (_viewType == "month") {
            var date = new Date();
            var monthfirstDay = new Date(date.getFullYear(), date.getMonth(), 1);
            var monthlastDay = new Date(date.getFullYear(), date.getMonth() + 1, 0);
            retrieveRecords(monthfirstDay, monthlastDay);
        }
        //retrieveRecords(new Date(), new Date());
    }
}
