var userfavorates = [];
var navigate;

$(function () {
    $('#dialog_favorite').dialog(function () {
        showmaskbg(false);
        $('.maskbg').hide();
    });
});

function refreshFavorites() {
    getFavoriteItems(onInitFavorites);
}

function setFavoriteDisplay(isshow, mouduleid, name, type) {
    //$('#button_fav').removeClass('fav').removeClass('nofav').addClass('unfav');
    if (isshow)
        $('#button_fav').show();
    else
        $('#button_fav').hide();
    if (mouduleid)
        navigate = setAppMoudule(mouduleid, name, type);

    //if (!navigate)
    //    $('#button_fav').removeClass('fav').removeClass('unfav').addClass('nofav');

    getFavoriteItems();
}

function getFavoriteItems(oninit) {
    _network.mainpagequery("GetFavoriteItems", "", function (data) {
        if (typeof data === 'string') {
            _dialog.showAlert(data, GetTextByKey("P_FAV_GETFAVORITES", 'Get Favorites'));
        } else {
            userfavorates = data;
            if (navigate)
                setFavorateStyle();
            if (oninit)
                oninit();
            showFavoritesGridList(userfavorates);
            if (typeof showChartFavorite === "function")
                showChartFavorite(isUserFavorate(chartiid));
        }
    });
}


function setFavorateStyle(id, name) {
    if (id) {
        var navid = id.substring(1);
        if (navid === "nav_manageharshdriving") {
            navid = "600";
        }
        navigate = setNavigate(navid, name);
    }
    $('#divfavadd').hide();
    $('#divfav').hide();
    //$('#button_fav').removeClass('fav').removeClass('nofav').addClass('unfav');
    var isfav = false;
    if (userfavorates && navigate) {
        for (var i = 0; i < userfavorates.length; i++) {
            if (userfavorates[i].ID === navigate.ID) {
                //$('#button_fav').addClass('fav').removeClass('unfav').removeClass('nofav');
                $('#divfav').show();
                isfav = true;
                break;
            }
        }
        if (!isfav)
            $('#divfavadd').show();
    }
}

function isUserFavorate(id) {
    if (userfavorates && navigate) {
        for (var i = 0; i < userfavorates.length; i++) {
            if (userfavorates[i].ID === id) {
                return true;
            }
        }
    }
    return false;
}

function setFavorate(isdelete) {
    if (!navigate)
        return;
    if (navigate.ID === "nav_manageharshdriving")
        navigate = setNavigate("600", "OTR Config");

    if (isdelete) {
        isdelete = true;
        $('#divfavadd').show();
        $('#divfav').hide();
    }
    else {
        $('#divfavadd').hide();
        $('#divfav').show();
    }

    setFavoritesData(isdelete, navigate);
}

function setFavoritesData(isdelete, nav) {
    if (isdelete) {
        if (userfavorates) {
            for (var i = 0; i < userfavorates.length; i++) {
                if (userfavorates[i].ID === nav.ID) {
                    userfavorates.splice(i, 1);
                    break;
                }
            }
        }
    }
    else
        userfavorates.push(nav);

    saveFavorites(userfavorates);
}

function saveFavorites(data, issort) {
    _network.mainpagequery("SetFavorites", JSON.stringify(data), function (data) {
        if (data !== 'OK') {
            _dialog.showAlert(data, GetTextByKey("P_FAV_SETFAVORITES", 'Set Favorites'));
        }
        else {
            if (issort) {
                $('#dialog_favorite').hideDialog();
                showmaskbg(false);
            }
            refreshFavorites();
        }
    });
}


function onInitFavorites() {
    var ids = ['100', '250', '500', '550', '650', '700', '600'];
    var favdiv = $('#favorite_panel');
    favdiv.empty();
    if (userfavorates && userfavorates.length > 0) {
        var div = $('<div class="panel_favorites"></div>')
            .css("max-height", $(window).height() - 180).appendTo(favdiv);
        var ulFavorites = $('<ul class="lefttitlemenu_ul" style="line-height:32px;"></ul>');
        div.append(ulFavorites);
        for (var i = 0; i < userfavorates.length; i++) {
            var fav = userfavorates[i];
            if (!fav) continue;
            if (fav.FavoriteType == 10) {
                createChartFavorite(fav, ulFavorites);
                continue;
            }

            for (var j = 0; j < appmoudulesdata.length; j++) {
                var m = appmoudulesdata[j];
                if (m.ModuleType == 0)//Features
                {
                    if (ids.indexOf(fav.ID) >= 0) {
                        if (fav.ID.toLowerCase() === m.ID.toLowerCase()) {
                            createMenuItem(m, ulFavorites);
                            break;
                        }
                    }
                    else {
                        if (m.SubItems) {//有子项
                            for (var k = 0; k < m.SubItems.length; k++) {
                                var sub = m.SubItems[k];
                                if (sub.ID.toLowerCase() === fav.ID.toLowerCase()) {
                                    createMenuItem(m, ulFavorites, sub);
                                    break;
                                }
                            }
                        }
                    }
                }
                else if (m.ModuleType == 1) {//WSP 
                    var id = "wsp" + m.ID;
                    if (fav.ID.toLowerCase() === id.toLowerCase()) {
                        createMenuItem(m, ulFavorites);
                        break;
                    }
                }
            }
        }

        var editfav = $('<div class="viewall" style="height: 32px;text-align: center; margin-top: 10px;"><span class="sbutton iconedit">' + GetTextByKey("P_FAV_EDITFAVORITES", "Edit Favorites") + '</span</div>');
        favdiv.append(editfav);
        editfav.click(function () {
            openFavoriteDialog();
        });
        favdiv.append('<div class="trigle"></div>') // trigle
        favdiv.append('<div class="trigle white"></div>');
    }
}


function getFavoriteNavInfoByID(id, text, icon) {
    var title = text;
    $(icon).addClass("lefttitlemenu_icon");
    if (id === "nav_credential") {
        title = GetTextByKey("P_CREDENTIALS", title);
        $(icon).addClass("iconcredentail");
    }
    else if (id === "nav_jdlink") {
        title = GetTextByKey("P_JDLINK", title);
        $(icon).addClass("iconjdlink");
    }
    else if (id === "nav_jdnotification") {
        title = GetTextByKey("P_JOHNDEERENOTIFICATIONS", title);
        $(icon).addClass("iconjdnotification");
    }
    else if (id === "nav_apicredential") {
        title = GetTextByKey("P_APICREDENTIALS", title);
        $(icon).addClass("iconcredentail");
    }
    else if (id === "nav_users") {
        title = GetTextByKey("P_USERS", title);
        $(icon).addClass("iconusers");
    }
    else if (id === "nav_user_group") {
        title = GetTextByKey("P_USERSGROUP", title);
        $(icon).addClass("iconusergroup");
    }
    else if (id === "nav_dts") {
        title = GetTextByKey("P_DATATABLEPERMISSION", title);
        $(icon).addClass("icondatatablepermission");
    }
    else if (id === "nav_filters") {
        title = GetTextByKey("P_DASHBOARDFILTERS", title);
        $(icon).addClass("icondashboardfilters");
    }
    else if (id === "nav_curfew") {
        title = GetTextByKey("P_CURFEWCONFIGURATION", title);
        $(icon).addClass("iconcurfew");
    }
    else if (id === "nav_curfewmt") {
        title = GetTextByKey("P_CURFEWMOVEMENTTOLERANCE", title);
        $(icon).addClass("iconcurfewmt");
    }
    else if (id === "nav_usertocontractor") {
        title = GetTextByKey("P_USERTOCONTRACTOR", title);
        $(icon).addClass("iconusertocontractor");
    }
    else if (id === "nav_alertsmanagement") {
        title = GetTextByKey("P_ALERTSMANAGEMENTNEW", title);
        $(icon).addClass("iconmanagealerts");
    }
    else if (id === "nav_workorder") {
        title = GetTextByKey("P_WORKORDERNEW", title);
        $(icon).addClass("iconworkorder");
    }
    else if (id === "nav_workorderhis") {
        title = GetTextByKey("P_XXX", title);
        $(icon).addClass("iconhistory");
    }
    else if (id === "nav_maintenanceschedule") {
        title = GetTextByKey("P_PM_MAINTENANCESCHEDULES", title);
        $(icon).addClass("iconmaintenanceschedule");
    }
    else if (id === "nav_record") {
        title = GetTextByKey("P_MAINTENANCERECORDLEGACY", title);
        $(icon).addClass("iconrecord");
    }
    else if (id === "nav_fuelrecord") {
        title = GetTextByKey("P_FUELRECORDS", title);
        $(icon).addClass("iconfuelrecord");
    }
    else if (id === "nav_manageharshdriving") {
        title = GetTextByKey("P_MANAGEHARSHDRIVING", title);
        $(icon).addClass("iconotrconfig");
    }
    else if (id === "nav_managmachines") {
        title = GetTextByKey("P_MANAGEASSETS", title);
        $(icon).addClass("iconmanageasset");
    }
    else if (id === "nav_managrentals") {
        title = GetTextByKey("P_MANAGERENTALS", title);
        $(icon).addClass("iconmanagerentals");
    }
    else if (id === "nav_machinegroups") {
        title = GetTextByKey("P_ASSETGROUPS", title);
        $(icon).addClass("iconassetgroups");
    }
    else if (id === "nav_managegpsdevices") {
        title = GetTextByKey("P_MANAGEDEVICES", title);
        $(icon).addClass("iconmanagegpsdevices");
    }
    else if (id === "nav_managmodels") {
        title = GetTextByKey("P_MANAGEMODELS", title);
        $(icon).addClass("iconmanagmodels");
    }
    else if (id === "nav_managmodels") {
        title = GetTextByKey("P_MANAGEMODELS", title);
        $(icon).addClass("iconmanagmodels");
    }
    else if (id === "nav_managmodels") {
        title = GetTextByKey("P_MANAGEMODELS", title);
        $(icon).addClass("iconmanagmodels");
    }
    else if (id === "nav_jobsiterequirements") {
        title = GetTextByKey("P_JS_JOBSITEREQUIREMENTS", title);
    }
    else if (id === "nav_dispatchrequests") {
        title = GetTextByKey("P_JS_DISPATCHREQUESTS", title);
    }
    else if (id === "nav_jobsitemanage") {
        title = GetTextByKey("P_JOBSITES", title);
    }
    else if (id === "nav_scheduler") {
        title = GetTextByKey("P_JS_SCHEDULER", title);
    }
    return title;
}

function createMenuItem(m, ul, sub) {
    var name = m.ModuleType === 1 ? m.Name : m.CurrentName;
    var title = name;
    var sm = JSON.parse(JSON.stringify(m));
    if (sm.ID == '150' && sm.Url.indexOf("#") < 0)
        sm.Url += "#nav_jobsitemanage";

    var icon = $('<button class="lefttitlemenu_icon titleicon" style="line-height:normal;"></button>');
    if (sub) {
        name = sub.Title;
        title = getFavoriteNavInfoByID(sub.ID, name, icon);
        sm.Url = sub.Url;
        if (sm.ID === "350" && !sub.IconPath)
            sub.IconPath = 'img/none.png';
        sm.IconPath = sm.Url.split('/')[0] + "/" + sub.IconPath;

        if ([100, 120, 130, 140, 210, 235].indexOf(sub.FeatureID) >= 0) {//nav_jobsitemanage/nav_jobsiterequirements/nav_dispatchrequests/nav_scheduler/nav_workorder/nav_customerrecord
            icon = createMouduleIcon(sm, 1);
        }
    }
    else {
        icon = createMouduleIcon(sm, 1);
        title = getFavoriteNavInfoByID(sm.ID, name, icon);
    }
    var li = $('<li></li>').click(function () {
        onOpenSite(sm);
    });
    var a = $('<a style="padding-left:0;"></a>');
    li.append(a);
    a.append($('<div></div>').append(icon));
    a.append($('<span></span>').text(title));
    ul.append(li);
}

function createFullMenuSite(m, ul) {
    var name = m.ModuleType === 1 ? m.Name : m.CurrentName;
    var sm = JSON.parse(JSON.stringify(m));
    var icon = createMouduleIcon(sm, 1);
    var li = $('<li></li>').click(function () {
        onOpenSite(sm);
    });
    var a = $('<a style="padding-left:0;"></a>');
    li.append(a);
    a.append($('<div></div>').append(icon));
    a.append($('<span></span>').text(name));
    ul.append(li);
}

function createChartFavorite(fav, ulFavorites) {
    var li = $('<li></li>').click(function () {
        openFleetChart(fav.ID, fav.Name);
    });
    var fav_a = $('<a style="padding-left:0;"></a>');
    li.append(fav_a);
    icon = $('<img class="lefttitlemenu_icon"/>').attr('src', _network.root + "img/modules/chart.png");
    fav_a.append($('<div></div>').append(icon));
    fav_a.append($('<span></span>').text(fav.Name));
    ulFavorites.append(li);
}

function onOpenSite(m) {
    if (!m)
        return;

    //if (m.ModuleType === 1) //Workspace保存最近打开
    //    setRecentOpenedDashboard(m.ID);

    var url = m.Url.toLowerCase();
    if (url.length > 4 && url.substring(0, 4) == 'http') {
    } else if (url.length > 0 && url[0] == '/') {
    } else {
        url = _network.root + url;
    }
    if (m.OpenInNewWindow) {
        window.open(url, "_blank");
    } else {
        window.location = url;
    }
}

function setAppMoudule(mouduleid, name, type) {
    if (!name) {
        if (mouduleid === 100)
            name = "Map View";
        else if (mouduleid === 150)
            name = "Jobsites";
        else if (mouduleid === 250)
            name = "FilterQ";
        else if (mouduleid === 500)
            name = "M3";
        else if (mouduleid === 550)
            name = "Over/Under Trucking Alerts";
        else if (mouduleid === 650)
            name = "Inspection";
        else if (mouduleid === 700)
            name = "Team Intelligence";
    }

    return setNavigate(mouduleid + '', name, type);
}

function setNavigate(id, name, type) {
    var obj = { "ID": id, "Name": name };
    if (type != undefined)
        obj.FavoriteType = type;
    return obj;
}


/*****************************Edit*************************************/


function showFavConfirm(msg, title, fok, fcancel) {
    $('#favorites_mask_bg').show();
    _dialog.showConfirm(msg, title, function (e) {
        if (typeof fok === 'function') {
            $('#favorites_mask_bg').hide();
            fok(e);
        }
    }, function () {
        $('#favorites_mask_bg').hide();
    });
}

var grid_favoritedt;
function InitFavoriteGrid() {
    grid_favoritedt = new GridView('#favoritelist');
    grid_favoritedt.lang = {
        all: GetTextByKey("P_GRID_ALL", "(All)"),
        ok: GetTextByKey("P_GRID_OK", "OK"),
        reset: GetTextByKey("P_GRID_RESET", "Reset")
    };
    var list_columns = [
        { name: 'Name', caption: GetTextByKey("P_FAV_FAVORITE", "Favorite"), valueIndex: 'Name', css: { 'width': 400, 'text-align': 'left' } },
        { name: 'Delete', caption: "", css: { 'width': 32, 'text-align': 'center' } },
        { name: 'Up', caption: "", css: { 'width': 32, 'text-align': 'center' } },
        { name: 'Down', caption: "", css: { 'width': 32, 'text-align': 'center' } }
    ];
    var columns = [];
    // head
    for (var hd in list_columns) {
        var col = {};
        col.name = list_columns[hd].name;
        col.caption = list_columns[hd].caption;
        col.visible = true;
        col.sortable = true;
        col.width = list_columns[hd].css.width;
        col.align = list_columns[hd].css["text-align"]
        col.key = list_columns[hd].valueIndex;
        if (list_columns[hd].type) {
            col.type = list_columns[hd].type;
        }
        if (col.name === "Delete") {
            col.isurl = true;
            col.text = "\uf00d";
            col.events = {
                onclick: function () {
                    OnDeleteFavorite(this);
                }
            };
            col.classFilter = function (e) {
                return "icon-col";
            };
            col.attrs = { 'title': GetTextByKey("P_FAV_DELETE", 'Delete') };
        }
        else if (col.name === "Up") {
            col.isurl = true;
            col.text = "\uf062";
            col.events = {
                onclick: function () {
                    onSortFavorite(true, this);
                }
            };
            col.classFilter = function (e) {
                return "icon-col";
            };
            col.attrs = { 'title': GetTextByKey("P_FAV_UP", 'Up') };
        }
        else if (col.name === "Down") {
            col.isurl = true;
            col.text = "\uf063";
            col.events = {
                onclick: function () {
                    onSortFavorite(false, this);
                }
            };
            col.classFilter = function (e) {
                return "icon-col";
            };
            col.attrs = { 'title': GetTextByKey("P_FAV_DOWN", 'Down') };
        }
        columns.push(col);
    }
    grid_favoritedt.canMultiSelect = false;
    grid_favoritedt.columns = columns;
    grid_favoritedt.init();

    grid_favoritedt.selectedrowchanged = function (rowindex) {
        var rowdata = grid_favoritedt.source[rowindex];
        if (rowdata) {
        }
    };

    grid_favoritedt.rowdblclick = function (rowindex) {
        var rowdata = grid_favoritedt.source[rowindex];
        if (rowdata) {
        }
    };
}

var favgridinited = false;
function showFavoritesGridList(data) {
    if (!favgridinited) {
        favgridinited = true;
        InitFavoriteGrid();
    }
    grid_favoritedt.setData([]);
    if (!data || data.length === 0)
        return;
    var rows = [];
    for (var i = 0; i < data.length; i++) {
        var r = data[i];
        var fr = { Values: r };
        rows.push(fr);
    }

    grid_favoritedt.setData(rows);
}

function openFavoriteDialog() {
    showmaskbg(true);
    $('#dialog_favorite .dialog-title span.title').text(GetTextByKey("P_FAV_EDITFAVORITES", 'Edit Favorites'));

    $('#dialog_favorite')
        .attr('act', 'edit')
        .css({
            'width': 540,
            'top': (document.documentElement.clientHeight - $('#dialog_favorite').height()) / 4,
            'left': (document.documentElement.clientWidth - $('#dialog_favorite').width()) / 2
        }).showDialogfixed();
    $("#btnfavsave").focus();

    if (userfavorates)
        showFavoritesGridList(userfavorates);
}

function OnDeleteFavorite(fav) {
    if (!fav)
        return;

    showFavConfirm(GetTextByKey("P_FAV_DELETEFAVORITECONTINUE", 'Favorite {0} will be deleted.Do you want to continue?').replace('{0}', fav.Name), GetTextByKey("P_FAV_DELETEFAVORITE", 'Delete Favorite'), function () {
        setFavoritesData(true, fav);
    });
}

function onSortFavorite(isasc, fav) {
    if (!fav || !userfavorates)
        return;

    var index;
    var currentfavs = [];
    for (var i = 0; i < grid_favoritedt.source.length; i++) {
        var userfav = grid_favoritedt.source[i].Values;
        if (fav.ID === userfav.ID)
            index = i;
        else
            currentfavs.push(userfav);
    }
    if (isasc) {
        if (index == 0)
            index = currentfavs.length;
        else
            index = index - 1;
    }
    else {
        if (index == currentfavs.length)
            index = 0;
        else
            index = index + 1;
    }
    currentfavs.splice(index, 0, fav);
    showFavoritesGridList(currentfavs);
}

function onSaveFavoriteSort() {
    if (!grid_favoritedt)
        return;
    var data = [];
    for (var i = 0; i < grid_favoritedt.source.length; i++) {
        data.push(grid_favoritedt.source[i].Values);
    }

    saveFavorites(data, true);
}


/*****************************Title Sites**************************************/

function onInitTitleSites() {
    if (appmoudulesdata) {
        var menudiv = $("#divfavmenu");
        var syssetli = $("#lisyssetting");
        var liversion = $("#liVersion");

        menudiv.parent().find(".dynamicmenu").remove();
        syssetli.parent().find(".dynamicmenu").remove();

        var mids = ['150', '650', '200', '400', 'dashboards', '100'];
        var smids = ['350', '150', '350', '300', '600', '650', '700'];
        for (var i = 0; i < mids.length; i++) {
            var id = mids[i];
            if (id === "dashboards") {
                if (!isReadonlyUser)
                    createDashboardTitle(menudiv);
            }
            else {
                for (var j = 0; j < appmoudulesdata.length; j++) {
                    var m = appmoudulesdata[j];
                    if (!m.Visible) continue;
                    if (id == parseInt(m.ID)) {
                        if (id == '150') {
                            for (var k = 0; k < m.SubItems.length; k++) {
                                var sub = m.SubItems[k];
                                if (sub.ID == "nav_jobsiterequirements"
                                    || sub.ID == "nav_dispatchrequests"
                                    || sub.ID == "nav_scheduler") {
                                    m = $.extend(true, {}, m);
                                    m.CurrentName = GetTextByKey("P_JS_ASSETSCHEDULINGANDDISPATCHING", "Asset Scheduling and Dispatching");
                                    m.IconPath = m.Url.split('/')[0] + "/img/dispatch.png";
                                    createTitleSite(m, menudiv);
                                    break;
                                }
                            }
                        }
                        else
                            createTitleSite(m, menudiv);
                        break;
                    }
                }
            }
        }

        for (var i = 0; i < smids.length; i++) {
            var id = parseInt(smids[i]);
            for (var j = 0; j < appmoudulesdata.length; j++) {
                var m = appmoudulesdata[j];
                if (!m.Visible) continue;
                if (id == parseInt(m.ID)) {
                    if (id == 350 && i == 0 && m.SubItems) {
                        for (var k = 0; k < m.SubItems.length; k++) {
                            var sub = m.SubItems[k];
                            if (sub.ID === "nav_users") {
                                createSettingSite(m, syssetli, sub);
                                break;
                            }
                        }
                    }
                    else if (id == 350 && i == 2 && m.SubItems) {
                        for (var k = 0; k < m.SubItems.length; k++) {
                            var sub = m.SubItems[k];
                            if (sub.ID === "nav_curfew") {
                                createSettingSite(m, liversion, sub);
                                break;
                            }
                        }
                    } else if (id == 150) {
                        m = $.extend(true, {}, m);
                        m.Url += "#nav_jobsitemanage";
                        createSettingSite(m, syssetli);
                    } else {
                        createSettingSite(m, liversion);
                    }

                    break;
                }
            }
        }

    }
}

function createTitleSite(m, menudiv) {
    var name = m.CurrentName;
    var sm = JSON.parse(JSON.stringify(m));
    var mctrl = $("<div class='button dynamicmenu'></div>").click(function () {
        onOpenSite(sm);
    });

    var icon;
    icon = $('<div class="titleicon"></div>').append($('<img class="titleimgicon"/>').attr('src', _network.root + m.IconPath));

    mctrl.append(icon);

    mctrl.attr("title", name);
    menudiv.after(mctrl);
}

function createSettingSite(m, syssetli, sub) {
    var name = m.CurrentName;
    if (m.ID === "650")
        name = GetTextByKey("P_MODULE_INSPECTIONTEMPLATES", "Inspection Templates");
    var sm = JSON.parse(JSON.stringify(m));
    var icon = $('<button class="lefttitlemenu_icon"></button>');
    if (sub) {
        if (sub.ID === "nav_users")
            name = GetTextByKey("P_USERSETUP", "User Setup");
        else if (sub.ID === "nav_curfew")
            name = GetTextByKey("P_CURFEWCONFIGURATION", sub.Title);
        sm.Url = sub.Url;
        sm.IconPath = sm.Url.split('/')[0] + "/" + sub.IconPath;
    }
    icon = createMouduleIcon(sm, 1);

    var li = $('<li class="dynamicmenu"></li>').click(function () {
        onOpenSite(sm);
    });
    var fav_a = $('<a style="padding-left:0;"></a>');
    li.append(fav_a);
    fav_a.append($('<div></div>').append(icon));
    fav_a.append($('<span></span>').text(name));

    syssetli.before(li);
}

//*************************************Dashboards**********************************//
var dashboarddata;
var grid_dbdt;
function InitDBGridData() {
    grid_dbdt = new GridView('#dashboardslist');
    grid_dbdt.lang = {
        all: GetTextByKey("P_GRID_ALL", "(All)"),
        ok: GetTextByKey("P_GRID_OK", "OK"),
        reset: GetTextByKey("P_GRID_RESET", "Reset")
    };
    var list_columns = [
        { name: 'Name', caption: GetTextByKey("P_DASHBOARDS_NAME", "Name"), valueIndex: 'Name', css: { 'width': 240, 'text-align': 'left' } },
        { name: 'Type', caption: GetTextByKey("P_DASHBOARDS_CHARTTYPE", "Chart Type"), valueIndex: 'Type', css: { 'width': 140, 'text-align': 'left' } },
        { name: 'Notes', caption: GetTextByKey("P_DASHBOARDS_NOTES", "Notes"), valueIndex: 'NoteTag', css: { 'width': 80, 'text-align': 'left' } },
        { name: 'IsChart', caption: GetTextByKey("P_DASHBOARDS_TYPE", "Type"), valueIndex: 'IsChart', css: { 'width': 80, 'text-align': 'left' } }
    ];
    var columns = [];
    // head
    for (var hd in list_columns) {
        var col = {};
        col.name = list_columns[hd].name;
        col.caption = list_columns[hd].caption;
        col.visible = true;
        col.sortable = true;
        col.width = list_columns[hd].css.width;
        col.align = list_columns[hd].css["text-align"]
        col.key = list_columns[hd].valueIndex;
        col.allowFilter = list_columns[hd].allowFilter;
        if (list_columns[hd].type) {
            col.type = list_columns[hd].type;
        }
        if (col.name == "Notes") {
            col.css = { 'text-align': 'center' };
            col.styleFilter = function () {
                return {
                    color: 'blue', cursor: 'pointer', 'text-decoration': 'underline'
                };
            };
            col.events = {
                onclick: function () {
                    showChartNotes(this.ID, this.Notes);
                }
            }
        }
        columns.push(col);
    }
    grid_dbdt.canMultiSelect = false;
    grid_dbdt.columns = columns;
    grid_dbdt.init();
    grid_dbdt.rowdblclick = openDashboard;

    grid_dbdt.selectedrowchanged = function (rowindex) {
        var rowdata = grid_dbdt.source[rowindex];
        if (rowdata) {
        }
    }
}

function showChartNotes(iid, notes) {
    $("#prechartnotes").text(notes);
    $('#mask_bgcn').show();
    $('#dialog_chartnotes .dialog-title span.title').text(GetTextByKey("P_MAIN_CHARTNOTES", 'Chart Notes'));

    $('#dialog_chartnotes')
        .attr('act', 'edit')
        .css({
            'width': 400,
            'top': (document.documentElement.clientHeight - $('#dialog_chartnotes').height()) / 4,
            'left': (document.documentElement.clientWidth - $('#dialog_chartnotes').width()) / 2
        }).showDialogfixed();
    //_network.ficquery('GetChartNote', [iid], function (r) {
    //    if (r != null) {
    //        if (r.ErrorCode != 0) {
    //            $("#prechartnotes").text(r.ErrorMessage);
    //        } else {
    //            $("#prechartnotes").html(unescape(r.Result));
    //        }
    //    }
    //});
};

function requestFIC(service, method, param, callback, error) {
    $.ajax({
        url: _network.root + 'fic/fic/FICSvc.ashx?fmt=json&SN=' + Math.random(),
        type: 'POST',
        dataType: 'json',
        cache: false,
        data: encodeURIComponent(JSON.stringify({
            LanguageID: _fleet.currentLang,
            UtcOffset: new Date().getTimezoneOffset(),
            Flag: 0,
            AppName: '',
            ServiceType: service,
            MethodName: method,
            Parameters: param
        })),
        async: true,
        success: callback,
        error: error || function (e) {
            console.log(e);
            showmaskbg(false, true);
            showAlert(GetTextByKey('P_UM_PAGEERROR', 'An unknown error occurred.  Please refresh page.'), GetTextByKey('P_UM_QUERY', 'Query'));
        }
    });
}
_network.ficquery = function (method, param, callback, error) {
    requestFIC('FI.FIC.IFICQuery', method, param, callback, error);
};

function showDashboards(data) {
    var rows = [];
    for (var i = 0; i < data.length; i++) {
        var r = data[i];
        r.NoteTag = (r.Notes && r.Notes != "") ? "?" : "";
        for (var j in r) {
            if (j === "IsChart")
                r[j] = { DisplayValue: r["IsChart"] ? "Chart" : "Dashboard", Value: r[j] };
        }

        var fr = { Values: r };
        rows.push(fr);
    }

    grid_dbdt.setData(rows);
}

function createDashboardTitle(menudiv) {
    var mctrl = $("<div class='button dynamicmenu'></div>").click(function () {
        openDashboardsDialog();
    });
    //var icon = $('<button class="reportsdashboard"></button>');
    var icon = $('<div class="titleicon"></div>').append($('<img class="titleimgicon"/>').attr('src', _network.root + "img/modules/dashboards.png?t=7"));
    mctrl.append(icon);

    mctrl.attr("title", GetTextByKey("P_MAIN_REPORTSDASHBOARDS", "Reports & Dashboards"));
    menudiv.after(mctrl);
}

function openDashboardsDialog() {
    showmaskbg(true);
    $('#dialog_dashboards .dialog-title span.title').text(GetTextByKey("P_MAIN_REPORTSDASHBOARDS", 'Reports & Dashboards'));

    $('#dialog_dashboards')
        .attr('act', 'edit')
        .css({
            'width': 850,
            'top': (document.documentElement.clientHeight - $('#dialog_dashboards').height()) / 4,
            'left': (document.documentElement.clientWidth - $('#dialog_dashboards').width()) / 2
        }).showDialogfixed(false);//参数为了兼容inspection页面

    getDashboardList();
}

function openDashboard() {
    var index = grid_dbdt.selectedIndex;
    if (index < 0) {
        _dialog.showAlert(GetTextByKey("P_DASHBOARDS_SELECTWSPORCHART", "Please select a Workspace or Chart."), GetTextByKey("P_MAIN_DASHBOARDS", 'Dashboards'));
        return;
    }

    var dah = grid_dbdt.source[index].Values;
    if (dah.IsChart.Value) {
        setRecentOpenedDashboard(dah.ID);
        $('#dialog_dashboards').hideDialog();
        showmaskbg(false);
        openFleetChart(dah.ID, dah.Name);
    }
    else {
        var m = {
            'ID': dah.ID,
            'ModuleType': 1,
            'OpenInNewWindow': false,
            'Url': "fic/Workspace.aspx?IID=" + dah.ID
        };
        onOpenSite(m);
    }

}

function getDashboardList() {
    var flag;
    if ($('#ipt_charts_only').prop('checked')) {
        flag = '1';
    } else if ($('#ipt_notes_only').prop('checked')) {
        flag = '2';
    } else {
        flag = '0';
    }
    var filter = JSON.stringify({
        '$type': 'System.String[], mscorlib',
        '$values': [htmlencode($.trim($('#ipt_dashboardfilter').val())), flag]
    });
    _network.mainpagequery("GetDashboardList", filter, function (data) {
        if (typeof data === 'string') {
            _dialog.showAlert(data, GetTextByKey("P_MAIN_DASHBOARDS", 'Dashboards'));
        } else {
            dashboarddata = data;
            showDashboards(data);
        }
    });
}

function setRecentOpenedDashboard(id) {
    _network.mainpagequery("SetRecentOpenedDashboard", id, function (data) {
        if (typeof data === 'string') {
        }
    });
}


function createMouduleIcon(m, type) {//type 0.moudule;1.fav/settings
    var icon = $('<img/>').attr('src', _network.root + m.IconPath);
    //if (m.ID === "100")//Map View
    //    icon = $("<button class='iconmapview'></button>");
    //else if (m.ID === "150")//Jobsites
    //    icon = $("<button class='iconjobsite'></button>");
    //else if (m.ID === "200")//Asset Health
    //    icon = $("<button class='iconassethealth'></button>");
    //else if (m.ID === "250")//FilterQ
    //    icon = $("<button class='iconassethealth'></button>");
    //else if (m.ID === "300")//Credentials
    //    icon = $("<button class='iconcredentails'></button>");
    //if (m.ID === "350")//Security Setting
    //    icon = $("<button class='iconsecuritysetting'></button>");
    //if (m.ID === "400")//Manage Assets
    //    icon = $("<button class='iconmanageasset'></button>");
    //else if (m.ID === "450")//FIC Management
    //    icon = $("<button class='iconficmanagement'></button>");
    //else if (m.ID === "500")//M3
    //    icon = $("<button class='iconficmanagement'></button>");
    //else if (m.ID === "550")//Over/Under Trucking Alerts
    //    icon = $("<button class='icontruck'></button>");
    //else if (m.ID === "600")//OTR Config
    //    icon = $("<button class='iconotrconfig'></button>");
    //else if (m.ID === "650")//Inspection
    //    icon = $("<button class='iconinspection'></button>");
    //else if (m.ID === "700")//Team Intelligence
    //    icon = $("<button class='iconteamintelligence'></button>");

    //if (m.ModuleType == 1)
    //    //icon = $("<button class='iconworkspace'></button>");
    //    icon = $('<img/>').attr('src', _network.root + "img/modules/dashboard.png");

    if (type == 0)
        icon.addClass("moduleicon");
    else if (type == 1)
        icon.addClass("lefttitlemenu_icon");

    return icon;
}