List = null;
var windowList = null;

function getProcessList() {
    try {
        var windowJson = window.parent.iediag.getData("Window Information", true);
        var processJson = window.parent.iediag.getData("Process Information", true);
        processList = JSON.parse(processJson);
        windowList = JSON.parse(windowJson);

        redraw();
    }
    catch (e) {
    }
}
function attach(id) {
    iediag.attachToPid(id.toString())
}
function startTrace(id) {
    iediag.startTrace(id.toString())
}
function stopTrace(id) {
    iediag.stopTrace(id.toString())
}
function installDebugger() {
    iediag.installDebugger()
}
function isDebugToolsAvailable() {
    return iediag.isDebugToolsAvailable()
}

function windowHtml(wnd) {
    var procName = "";
    var pid = "";
    var proc;
    for (var y in processList) {
        proc = processList[y];
        if (wnd.ProcessID == proc.PID) {
            procName = proc.Command;
            pid = proc.PID;
            break;
        }
    }
    if (proc) {
        procName = (proc.Command.indexOf("iexplore") != -1) ? "IE" : procName;
        var html = procName + " --- " + wnd.Title + " HWND:" + wnd.HWND;
        if (isDebugToolsAvailable()) {
            html += "&nbsp;<a class='buttonLink' onclick=attach(" + pid + ")>Attach Debugger</a>&nbsp;|";
            html += "&nbsp;iDNA Tracing:&nbsp;";
            html += "&nbsp;<a class='buttonLink' onclick=startTrace(" + pid + ")>Start</a>&nbsp;|";
            html += "&nbsp;<a class='buttonLink' onclick=stopTrace(" + pid + ")>Stop</a>";
        }
    }
    return html;
}

function tabHtml(tab) {
    var pid = tab.ProcessID;
    var html = "<span> PID:<br/>" + pid + "</span><br/>";
    html += "<span> Title:<br/>" + tab.Title + "</span>"
    if (isDebugToolsAvailable()) {
        html += "<br/><a class='buttonLink' onclick=attach(" + pid + ")>Attach Debugger</a><br/>";
        html += "iDNA Tracing:&nbsp;";
        html += "<a class='buttonLink' onclick=startTrace(" + pid + ")>Start</a>&nbsp;|";
        html += "&nbsp;<a class='buttonLink' onclick=stopTrace(" + pid + ")>Stop</a>";
    }

    /*html += "<br/><a>Start Perf Trace</a>";
    html += "<br/><a>Start IDNA Trace</a>";*/
    return html;
}

function drawChildProcess(managerProc) {
    var html = "";
    for (var x in processList) {
        var proc = processList[x];
        if (proc.ManagerPID == managerProc.Id) {
            var pid = proc.Id;
            html += "<td class=\"procDetail\"><span>Content Process PID:<br/>" + pid + "</span><br/>";
            //html += "<span> Title:<br/>" + tab.Title + "</span>"
            if (isDebugToolsAvailable()) {
                html += "<br/><a class='buttonLink' onclick=attach(" + pid + ")>Attach Debugger</a><br/>";
                html += "iDNA Tracing:&nbsp;";
                html += "<a class='buttonLink' onclick=startTrace(" + pid + ")>Start</a>&nbsp;|";
                html += "&nbsp;<a class='buttonLink' onclick=stopTrace(" + pid + ")>Stop</a>";
            }
            html += "</td>";
        }
    }


    /*html += "<br/><a>Start Perf Trace</a>";
    html += "<br/><a>Start IDNA Trace</a>";*/
    return html;
}

function redrawProcessData() {
    var html;

    if (windowList.length != 0) {
        for (var x in windowList) {
            var tabs = windowList[x].Tabs;
            html += "<tr><td colspan=\"2\" class=\"frameDetail\" >" + windowHtml(windowList[x]) + "</td><tr>";
            for (var i in tabs) {
                var tab = tabs[i];
                html += '<td class="procDetail" >' + tabHtml(tab) + '</td>';
            }
            html += "</tr>";
        }
    }

    for (var x in processList) {
        var proc = processList[x];
        if (proc.Type == "Manager" && proc.Name == "Browser") {
            html += "<tr><td colspan=\"2\" class=\"frameDetail\" id=\"mgrProc\"" + proc.Id + ">Parent :" + proc.Id + "</td><tr>";
            html += "<tr>" + drawChildProcess(proc); "</tr>";

        }
    }

    $("#procTable").html(html);
}
/*********** Process Info Functions End *************/

/*********************   Add-ons Trouble shooting *********************/
function addOnsDisableNext() {
    var addonTS = new addOnsTroubleShooter();
    addonTS.disableNext(addonTS);
}

var addOnsTroubleShooter = function () {
    var procId = null;
    var origAddOnsList, currAddOnsList;
}

addOnsTroubleShooter.prototype =
{
    constructor: addOnsTroubleShooter,
    updateList: function () {
        var currAddOnsJson = iediag.enabledBHOs(32); // get 32 bit addons
        currAddOnsList = JSON.parse(currAddOnsJson);
        var count = currAddOnsList.length;
        var table = $('<table></table>');
        var prevClsid = "";
        var nameToDisable;
        var clsidToDisable;

        if (!origAddOnsList || origAddOnsList.length <= 0) {
            origAddOnsList = currAddOnsList;
        }

        $(currAddOnsList).each(function () {
            if (!nameToDisable) {
                prevClsid = $('#buttonAddOnsDisableNext').attr("CLSID");
                nameToDisable = this.name;
                $('#buttonAddOnsDisableNext').attr("name", nameToDisable);
                $('#buttonAddOnsDisableNext').html("Disable " + nameToDisable);
                $('#buttonAddOnsDisableNext').attr("CLSID", this.Clsid);
                $('#buttonAddOnsDisableNext').attr("prevCLSID", prevClsid);
            }
            table.append($("<tr><td><a class='buttonLink' id='button" + this.Clsid + "'>Disable </a> " + this.Name + "</td><tr>"));
        });
        $('#tblEnabledList').html("");
        $('#tblEnabledList').html(table.html());

        if (count == 0) {
            prevClsid = $('#buttonAddOnsDisableNext').attr("CLSID");
            $('#buttonAddOnsDisableNext').attr("name", "");
            $('#buttonAddOnsDisableNext').html("");
            $('#buttonAddOnsDisableNext').attr("CLSID", "");
            $('#buttonAddOnsDisableNext').attr("prevCLSID", prevClsid);
        }
    },
    enableAddon: function (clsid) {
        iediag.enableAddOn(clsid);
    },
    disableAddon: function (addOnTs, clsid) {
        iediag.disableAddOn(clsid);
        $('#buttonAddOnsDisableNext').hide();
        addOnTs["procId"] = iediag.launchIE();
    },
    enableAllAddonsExcept: function (clsid) {
        var me = this;
        var table = $('<table></table>');
        //$('#tblEnabledList').html(table.html());
        $(origAddOnsList).each(function () {
            if (this.Clsid != clsid) {
                me.enableAddon(this.Clsid);
                table.append($("<tr><td><div id='" + this.Clsid + "'>" + this.Name + "</div></td><tr>"));
            }
            else {
                table.append($("<tr><td><div id='" + this.Clsid + "' style='color:red'>" + this.Name + " &lt; -- seems to be the addon with the issue. It is now disabled</div></td><tr>"));
                iediag.logTroubleShootUsage("Problematic AddOn", this.Name + this.Clsid, true);
                resetTroubleShootUI();
            }
        });
        $('#tblEnabledList').html("");
        $('#tblEnabledList').html(table.html());
    },

    disableNext: function (addOnTs) {
        var me = this;
        var currClsid = $('#buttonAddOnsDisableNext').attr("CLSID");
        if (currClsid && (currClsid !== "")) {
            this.disableAddon(addOnTs, currClsid);
            var disabledAddOnName = $('#buttonAddOnsDisableNext').attr("name");
            this.updateList();
            if (iediag.isRunningSilent()) {
                if (iediag.IsProcessHungOrCrashed(this.processId)) {
                    this.disableNext(addOnTs);
                }
            }
            $('#buttonAddOnsDisableNext').hide();
            $("#divAddOnsAlert").dialog({
                resizable: false,
                modal: true,
                buttons: {
                    "Yes": function () {
                        iediag.closeIE(addOnTs["procId"]);
                        $(this).dialog("close");
                        $('#buttonAddOnsDisableNext').click();
                    },
                    "No": function () {
                        iediag.closeIE(addOnTs["procId"]);
                        me.enableAllAddonsExcept($('#buttonAddOnsDisableNext').attr("prevCLSID"));
                        $(this).dialog("close");
                    }
                }
            });
            var newMSG = "<p style='line-height:auto;margin:auto;'> Disabled " + disabledAddOnName + "<br/> Is the issue still reproducible in the launched IE?</p>";
            $("#divAddOnsAlert").html(newMSG);
        }
    },
    start: function (addOnTS) {
        this.updateList();
        $('#divAddOnsEnabledList').show();
        this.askForElimination(addOnTS);
    },
    askForElimination: function (addOnTs) {
        $("#divAddOnsAlert").dialog({
            resizable: false,
            modal: true,
            buttons: {
                "Yes": function () {
                    if (null != addOnTs["procId"]) {
                        iediag.closeIE(addOnTs["procId"]);
                    }
                    $(this).dialog("close");
                    $('#buttonAddOnsDisableNext').click();
                },
                "No": function () {
                    iediag.closeIE(addOnTs["procId"]);
                    $(this).enableAllAddonsExcept($('#buttonAddOnsDisableNext').attr("CLSID"));
                    $(this).dialog("close");
                }
            }
        });
        var newMSG = "<p style='line-height:auto;margin:auto;'>Based on your answer this is likely an issue with one of the enabled add-ons. Do you want to continue and disable the problematic add-on?</p>";
        $("#divAddOnsAlert").html(newMSG);
    }
}

function redrawAddOnsData() {
    logInfo(iediag.enabledBHOs(32));
    logInfo(iediag.enabledBHOs(64));
}

function drawEvent(evt) {

}

function redrawEventLogData() {
    try {
        var eventLogs = JSON.parse(iediag.eventLog());
        if (eventLogs && eventLogs.Entries) {
            for (var entry in eventLogs.Entries) {
                var event = eventLogs.Entries[entry];
                if (event) {
                    //event.
                }
            }
        }
    }
    catch (ex) {
        alert(ex);
    }
}

/************  Group Policy Data ********/

function redrawGroupPolicy() {
    gpAccordion.innerHTML = "";

    for (var i = 0 ; groupPolicyList.Policies.length > i; i++) {
        var policy = groupPolicyList.Policies[i];
        var h3Element = document.createElement("h3");
        var h3Text;

        if (policy.NameDescriptive) {
            h3Text = document.createTextNode(policy.NameDescriptive);
        }
        else {
            h3Text = document.createTextNode(policy.Name);
        }
        h3Element.appendChild(h3Text);
        var divElement = document.createElement("div");
        addKeyValuePairToHtml(divElement, "p", "Description", policy.Description);
        addKeyValuePairToHtml(divElement, "div", "Parent category", policy.ParentCategory);
        addKeyValuePairToHtml(divElement, "div", "Supported on", policy.SupportedOn);
        addKeyValuePairToHtml(divElement, "div", "Registry location", policy.ElementList[0].Key);

        for (var j = 0; policy.ElementList[0].ValueNamePairs.length > j; j++) {
            var valueNamePair = policy.ElementList[0].ValueNamePairs[j];
            addKeyValuePairToHtml(divElement, "div", "Key, Value", valueNamePair.Key + ", " + valueNamePair.Value);
        }

        gpAccordion.appendChild(h3Element);
        gpAccordion.appendChild(divElement);
    }

    $("#gpAccordion").accordion("refresh");
}

function addKeyValuePairToHtml(parentElement, elementType, key, value) {
    var pElement = document.createElement(elementType);
    var pText = document.createTextNode(key + " : " + value);
    pElement.appendChild(pText);
    parentElement.appendChild(pElement);
}

var groupPolicyList = null;
function getGroupPolicyData() {
    try {
        var groupPolicyJson = iediag.getData("Group policy Settings", false);
        if (groupPolicyJson && groupPolicyJson != "undefined") {
            groupPolicyList = JSON.parse(groupPolicyJson);
            redrawGroupPolicy();
        }
    }
    catch (e) {
        alert(e)
    }
}

/********  Event Log Data *************/
function redrawAddOnsData() {
    logInfo(iediag.addonData());
}
function redrawEventLogData() {
    try {
        var eventLogs = JSON.parse(iediag.eventLog());
        if (eventLogs && eventLogs.Entries) {
            for (var entry in eventLogs.Entries) {
                var event = eventLogs.Entries[entry];
                if (event) {
                    //event.
                }
            }
        }
    }
    catch (ex) {
        alert(ex);
    }
}
