﻿// APM Scripts

/**
 * NOTE: This function was taking from the ExtJs library.  I didn't want to pull in all of ExtJs just to define namespaces.
 * Creates namespaces to be used for scoping variables and classes so that they are not global.  Usage:
 * <pre><code>
        Ext.namespace('Company', 'Company.data');
        Company.Widget = function() { ... }
        Company.data.CustomStore = function(config) { ... }
   </code></pre>
 * @param {String} namespace1
 * @param {String} namespace2
 * @param {String} etc
 * @method namespace
 */
MakeNamespace = function(){
    var a=arguments, o=null, i, j, d, rt;
    for (i=0; i<a.length; ++i) {
        d=a[i].split(".");
        rt = d[0];
        eval('if (typeof ' + rt + ' == "undefined"){' + rt + ' = {};} o = ' + rt + ';');
        for (j=1; j<d.length; ++j) {
            o[d[j]]=o[d[j]] || {};
            o=o[d[j]];
        }
    }
},

MakeNamespace("SW", "SW.APM");


function $id(id) {
	return document.getElementById(id);
}

function ToggleVisibility(id, displayStyle)
{
	var item = $id(id);
    if (item.style.display == "none")
        item.style.display = displayStyle;
    else
        item.style.display = "none";
}

function show(id)
{
	var item = $id(id);
    item.style.display = "";
}

function hide(id)
{
    var item;
    if (id.style)
	    item = id;
    else
    	item = $id(id);
    item.style.display = "none";
}

function deleteMonitor(theButton, id) {
	var el = $id(id);
	if (el.className == "apm_Monitor_Deleted")
    {
        // Monitor is already deleted. Undo the delete
    	el.className = "apm_Monitor";
        theButton.value = "Delete";            
    }
    else
    {
        // Delete the monitor
    	el.className = "apm_Monitor_Deleted";
        theButton.value = "Undo Delete";
    }
}

function renameMonitor(theButton, spanLabel, spanEdit, id)
{
	var labelElement = $id(spanLabel + id);
	var editElement = $id(spanEdit + id);
    
    var editChildren = editElement.getElementsByTagName("INPUT");
    var editTextbox = (editChildren.length > 0) ? editChildren[0] : null;


    if (editElement.style.display == "none") 
    {
        // Edit is hidden.  Start the rename
        editElement.style.display = "";
        labelElement.style.display = "none";
        editTextbox.focus();
        theButton.src = "../images/SmallButton.Save.gif";
    }
    else 
    {
        var nm = editTextbox.value.replace(/^\s+|\s+$/, '');
        if (nm == '') 
        {
            alert('Component name could not be empty!');
        }
        else 
        {
            //
            // Edit is visible.  End the rename
            labelElement.innerHTML = nm;
            editElement.style.display = "none";
            labelElement.style.display = "";
            theButton.src = "../images/SmallButton.Rename.gif";
        }
    }
}

function toggleEditSetting(editControl, viewControl, stateControl, requiredControl, validateStateControl, theLink)
{
    ToggleVisibility(editControl, "");
    ToggleVisibility(viewControl, "block");

    var stateItem = $id(stateControl);
    var allowEdit = stateItem.value == "True";

    var editItem = $id(editControl);

    if (requiredControl && validateStateControl) {
        var requiredItem = $id(requiredControl);
        var required = requiredItem.value == "True";
        var validateItem = $id(validateStateControl);
        validateItem.value = ((editItem.style.display == "") && required) ? "True" : "False";
    }
    
    stateItem.value = allowEdit ? "False" : "True";
    theLink.innerHTML = allowEdit ? "Override Template" : "Inherit from Template";
    
    return false;
}


function UpdateImage(imgId)
{
	var img = $id(imgId);
    img.src = img.src;
}

var _apm_test_target_server;
var _apm_test_hid_node_id;
var _apm_test_hid_node_name;
var _apm_test_btn_test;
var _apm_test_lnk_set_node;
var _apm_test_popup;
var _apm_change_all_test_nodes;
var _apm_test_all_hid_node_id_top;
var _apm_test_all_hid_node_name_top;
var _apm_test_all_hid_node_id_bottom;
var _apm_test_all_hid_node_name_bottom;
var _apm_change_all_msg_id_top;
var _apm_change_all_msg_id_bottom;

function showNodeSelectionDialog(testAgainstLabel, testButton, changeAllTestNodes, setNodeLnk, nodeHiddenId, nodeHiddenName) {
    this._apm_change_all_test_nodes = changeAllTestNodes;
    this._apm_test_popup = $find('SelectNodeModalPopupDialog');
    this._apm_test_target_server = $get(testAgainstLabel);
    this._apm_test_hid_node_id = $get(nodeHiddenId);
    this._apm_test_hid_node_name = $get(nodeHiddenName);
    this._apm_test_btn_test = $get(testButton);
    this._apm_test_lnk_set_node = setNodeLnk;
    this._apm_test_popup.show();
    
    afterNodeSelectionChange(apm_SelectNodeOkBtn_Id);
}

var notPosted = false;
var postBackRef;

function showNodeSelectionDialogAndTest(testAgainstLabel, testButton, changeAllTestNodes, setNodeLnk, nodeHiddenId, nodeHiddenName, postBack) {
    //todo: seems there's no need in additional flag?
    if ($get(_apm_test_all_hid_node_name_top).value == "") {
        showNodeSelectionDialog(testAgainstLabel, testButton, changeAllTestNodes, $get(setNodeLnk), nodeHiddenId, nodeHiddenName);
        notPosted = true;

        postBackRef = postBack;

        return false;
    }
}

function nodeSelectionOkClick() {   
    this._apm_test_popup.hide();
    var theNode = selectTestNode_SelectedNodeInfo;

    if (theNode) {
        var isTopLevel = false;

        if (!isTopLevel) {
            var nodeId = theNode.nodeId;

            if (this._apm_change_all_test_nodes == "False") {
                this._apm_test_target_server.innerHTML = nodeId ? "Will test against " + theNode.text : "Test node not specified";
                this._apm_test_lnk_set_node.innerHTML = nodeId ? "Change test node" : "Set test node";
                this._apm_test_hid_node_id.value = nodeId;
                this._apm_test_hid_node_name.value = theNode.text;

                var inputTypeElements, testButton, testNodeNames, i, disableTestAllMonitorsButton = false;
                var testAllMonitorsButtonIDs = [];
                var testNodeIDs = [], testNodeNames = [];
                var stringItems, k, m;
                
                inputTypeElements = document.getElementsByTagName('input');
                for (i = 0; i < inputTypeElements.length; i++) {
                    if (/hidTestNodeId/.test(inputTypeElements[i].id)) {
                        stringItems = inputTypeElements[i].value.split(',');
                        if (stringItems.length == 1) {
                            if ((testNodeIDs.indexOf(stringItems[0]) < 0) && (stringItems[0] != "")) {
                                testNodeIDs.push(stringItems[0]);
                            }
                        }
                    }
                    if (/hidTestNodeName/.test(inputTypeElements[i].id)) {
                        stringItems = inputTypeElements[i].value.split(',');
                        if (stringItems.length == 1) {
                            if ((testNodeNames.indexOf(stringItems[0]) < 0) && (stringItems[0] != "")) {
                                testNodeNames.push(stringItems[0]);
                            }
                        }
                    }
                    if (/TestAllMonitorsButton/.test(inputTypeElements[i].className)) {
                        testAllMonitorsButtonIDs.push(inputTypeElements[i].id);
                    }
                }

                $get(_apm_test_all_hid_node_id_top).value = testNodeIDs.toString();
                $get(_apm_test_all_hid_node_name_top).value = testNodeNames.toString();
                $get(_apm_test_all_hid_node_id_bottom).value = testNodeIDs.toString();
                $get(_apm_test_all_hid_node_name_bottom).value = testNodeNames.toString();
                
                for (m = 0; m < testAllMonitorsButtonIDs.length; m++) {
                    var testAllMonitorsButton = $get(testAllMonitorsButtonIDs[m]);
                    testAllMonitorsButton.disabled = false;                
                }                
            }
            else {
				$("a[id^='href']").html(nodeId ? "Change test node" : "Set test node");
                var messageSpanElements, i;
                
                messageSpanElements = document.getElementsByTagName('span');
                for (i = 0; i < messageSpanElements.length; i++) {
                    if (/ChangeTestNodeMessage/.test(messageSpanElements[i].className)) {
                        messageSpanElements[i].innerHTML = nodeId ? "Will test against " + theNode.text : "Test node not specified";
                    }
                }

                var inputTypeElements, j;
                inputTypeElements = document.getElementsByTagName('input');
                for (j = 0; j < inputTypeElements.length; j++) {
                    if (/hidTestNodeId/.test(inputTypeElements[j].id)) {
                        inputTypeElements[j].value = nodeId;
                    }
                    if (/hidTestNodeName/.test(inputTypeElements[j].id)) {
                        inputTypeElements[j].value = theNode.text;
                    }
                    if (/TestSingleMonitorButton/.test(inputTypeElements[j].className)) {
                        if (nodeId) {
                            var testSingleMonitorButton = $get(inputTypeElements[j].id);
                            testSingleMonitorButton.disabled = false;
                        }
                    }
                    if (/TestAllMonitorsButton/.test(inputTypeElements[j].className)) {
                        var testAllMonitorsButton = $get(inputTypeElements[j].id);
                        testAllMonitorsButton.disabled = false;
                    }
                }
            }
            
            if (_apm_change_all_msg_id_top) {
                $get(_apm_change_all_msg_id_top).innerHTML = "";
            }
            if (_apm_change_all_msg_id_bottom) {
                $get(_apm_change_all_msg_id_bottom).innerHTML = "";
            }
        }
    }
    if (notPosted)
        setTimeout(postBackRef, 0);
}




function nodeSelectionCancelClick() {
	this._apm_test_popup.hide();
}

function afterNodeSelectionChange(okButtonId) {
    var theNode = selectTestNode_SelectedNodeInfo;

    if (theNode) {
        var okButton = $get(okButtonId);
        if (okButton)
            okButton.disabled = false;
    }
}


// Note:  This function requires JQuery
var APM_MakeZebraStripesCalled = false;
function APM_MakeZebraStripes() {
    if (APM_MakeZebraStripesCalled === false) {
        $('table.NeedsZebraStripes tbody tr:nth-child(even)')
            .addClass('apm_ZebraStripe')
            .find('.apm_HighlightedColumn')
                .removeClass('apm_HighlightedColumn')
                .addClass('apm_HighlightedColumnAlternate')
            .end();
            
        $('table.NeedsZebraStripes td').css('border-bottom-style', 'none');
        APM_MakeZebraStripesCalled = true;
    }
}

var apmUtility = {
	ChangeName: function(labelID, editID) {
		var callback = function(state, value) {
			if (state == 'ok' && $.trim(String(value)).length > 0) {
				$id(labelID).innerHTML = value;
				$id(editID).value = value;
			}
		};
		Ext.MessageBox.prompt('Component Name', 'Please enter Component name:', callback, null, false, $id(editID).value);
	},
	onDisplayDetails: function(obj){
		var tr = obj.parentNode.childNodes;
		for(var i in tr){
			if(tr[i].nodeName == 'TD'){
				var td = tr[i].childNodes;
				for(var j in td){
					if(td[j].nodeName == 'IMG' && td[j].style.display != 'none'){
						td[j].onclick();
						return false;
					}
				}
			}
		}
		return false;
	}
}

/*Copy Component and Component Template Dialog*/
if (typeof (SW) != "undefined" && typeof (SW.APM) != "undefined" && (typeof (SW.APM.components) != "undefined" || typeof (SW.APM.templates) != "undefined")) {

	SW.APM.CopyToApplicationDialog = function() {
		var mThis, mDefGroup, dlg, entityIDs, config, TreeLoader;
	}
	SW.APM.CopyToApplicationDialog.getInstance = function(config) {
		var obj = null;
		if (config.type == "app") { (obj = new SW.APM.CopyComponents()).init(config); }
		if (config.type == "tpl") { (obj = new SW.APM.CopyTemplates()).init(config); }
		return obj;
	}
	with($p = SW.APM.CopyToApplicationDialog.prototype) {

		$p.loadEntityGroupByValues = function() { 
			throw "Member Not Implement"; 
		}
		$p.copyEntity = function() { 
			throw "Member Not Implement"; 
		}
		$p.getGroupValues = function() { 
			throw "Member Not Implement"; 
		}
		$p.getConfig = function() {
			throw "Member Not Implement";
		}
		$p.getKey = function() {
			throw "Member Not Implement";
		}
		
		$p.onClose = function(){ 
			dlg.hide(); dlg.destroy(); dlg=null; 
		};
		$p.onSubmit = function() {
			var waitMsg = Ext.Msg.wait("Copying components...");
			var onSuccess = function(message) { waitMsg.hide(); Ext.Msg.alert('Status', message, function() { if (config.updateHandler) { config.updateHandler(); } }); };
			mThis.copyEntity(config.cmpIDs, config.tplIDs, entityIDs, onSuccess);
			mThis.onClose();
		};
		$p.onNodeExpand = function(node) {
			if (node.isExpanded()) { node.collapse(); } else { node.expand(); }
		}
		$p.onNodeClick = function(node) {
			var cb = node.ui.checkbox; cb.checked = !cb.checked; mThis.onNodeCheck(node);
		}
		$p.onNodeCheck = function(node) {
			var cb = node.ui.checkbox;
			if (cb.checked) { entityIDs.push(node.attributes.appID); } else { entityIDs.remove(node.attributes.appID); }
			dlg.buttons[0].setDisabled(entityIDs.length < 1);
		}
		$p.onGroupSelect = function(combo, record, index) {
			entityIDs = []; dlg.buttons[0].setDisabled(true);
			dlg.getComponent("tree").getLoader().load(record.data.groupBy);

			ORION.Prefs.save(mThis.getKey(), record.data.groupBy);
		}
		$p.onBind = function(groupBy, json) {
			eval("var nodes=" + json + ";");
			var tree = dlg.getComponent("tree"), root = tree.getRootNode(), loader = tree.getLoader();
			for (var i = root.childNodes.length - 1; i > -1; i--) { root.childNodes[i].remove(); }
			for (var i = 0, iLen = nodes.length; i < iLen; i++) {
				var parent = root, children = nodes[i].children;
				if (groupBy != "''") {
					parent = loader.createNode({
						text: nodes[i].text, icon: nodes[i].icon,
						nodeType: "node", iconCls: "apm_StatusIcon", draggable: false, leaf: false, listeners: { click: mThis.onNodeExpand }
					});
					root.appendChild(parent);
				}
				for (var j = 0, jLen = children.length; j < jLen; j++) {
					parent.appendChild(
						loader.createNode({
							appID: children[j].id, text: children[j].text, icon: children[j].icon,
							nodeType: "node", iconCls: "apm_StatusIcon", draggable: false, leaf: true, checked: false, listeners: { click: mThis.onNodeClick, checkchange: mThis.onNodeCheck }
						})
					);
				}
			}
			tree.render();
			root.expand();
		}
		$p.onLoad = function(groupBy) {
			var group = (groupBy && groupBy.constructor == String ? groupBy : mDefGroup);
			mThis.loadEntityGroupByValues(group, function(json) { mThis.onBind(group, json); });
		}

		$p.show = function() {
			var dlgConfig = {
				id: "apm_SelectAppDialog", title: "Select Entity", width: 400, minWidth: 400, height: 500, minHeight: 500, border: false, region: "center", layout: "fit", modal: true,
				tbar: [
					"Group By:&nbsp;&nbsp;&nbsp;",
					new Ext.form.ComboBox({
						id: "ctrCopyGroupBy", displayField: "displayText", mode: "local", triggerAction: "all", emptyText: "[No Grouping]", width: 200, typeAhead: true, editable: false, selectOnFocus: true,
						store: new Ext.data.SimpleStore({
							fields: ["groupBy", "displayText"],
							data: mThis.getGroupValues()
						}),
						listeners: { select: mThis.onGroupSelect }
					})
				],
				items: [
					new Ext.tree.TreePanel({
						id: "tree", autoScroll: true, animate: false, containerScroll: true, rootVisible: false, style: 'margin:3px 0px 3px 0px;',
						loader: new TreeLoader(), root: new Ext.tree.AsyncTreeNode({ id: "source", text: "text", draggable: false })
					})
				],
				buttons: [
					{ text: "Submit", disabled: true, handler: mThis.onSubmit },
					{ text: "Close", handler: mThis.onClose }
				]
			};
			Ext.apply(dlgConfig, mThis.getConfig());

			dlg = new Ext.Window(dlgConfig);
			dlg.show();
			for (var i = 0, items = mThis.getGroupValues(); i < items.length; i++) {
				if (items[i][0] == mDefGroup) {
					Ext.getCmp("ctrCopyGroupBy").setValue(items[i][1]);
				}
			}
		}

		$p.init = function(pConfig) {
			mThis = this;
			mDefGroup = ORION.Prefs.load(mThis.getKey(), "''");
			dlg = null; entityIDs = []; config = pConfig;
			TreeLoader = Ext.extend(Ext.tree.TreeLoader, { load: mThis.onLoad });
		}
	}

	SW.APM.CopyComponents = function(){}
	with(SW.APM.CopyComponents.prototype = new SW.APM.CopyToApplicationDialog, $p = SW.APM.CopyComponents.prototype){

		$p.loadEntityGroupByValues = function(groupBy, onSuccess) {
			ORION.callWebService("/Orion/APM/Services/Applications.asmx", "GetApplicationGroupByValues", { "groupBy": groupBy }, onSuccess);
		};
		$p.copyEntity = function(componentIDs, templateIDs, applicationIDs, onSuccess) {
			ORION.callWebService("/Orion/APM/Services/Components.asmx", "CopyToApplication", { "componentIDs": componentIDs, "templateIDs": templateIDs, "applicationIDs": applicationIDs }, onSuccess);
		};
		$p.getGroupValues = function() {
			return [
				["''", "[No Grouping]"],
				["at.Name", "Application Monitor Template"],
				["n.Caption", "Node Name"],
				["n.Vendor", "Node Vendor"],
				["n.MachineType", "Node Machine Type"],
				["n.Contact", "Node Contact"],
				["n.Location", "Node Location"],
				["n.ObjectSubType", "Node Object Sub-Type"],
				["n.SysObjectID", "Node System OID"]
			];
		};
		$p.getConfig = function() {
			return { title: "Select Application" };
		};
		$p.getKey = function() {
			return "CopyCMPGroupBy";
		};
	}

	SW.APM.CopyTemplates = function(){}
	with(SW.APM.CopyTemplates.prototype = new SW.APM.CopyToApplicationDialog, $p = SW.APM.CopyTemplates.prototype){

		$p.loadEntityGroupByValues = function(groupBy, onSuccess) {
			ORION.callWebService("/Orion/APM/Services/Applications.asmx", "GetApplicationTemplateGroupByValues", { "groupBy": groupBy }, onSuccess);
		};
		$p.copyEntity = function(componentIDs, templateIDs, applicationIDs, onSuccess) {
			ORION.callWebService("/Orion/APM/Services/Components.asmx", "CopyToApplicationTemplate", { "componentIDs": componentIDs, "templateIDs": templateIDs, "applicationIDs": applicationIDs }, onSuccess);
		};
		$p.getGroupValues = function() {
			return [
				["''", "[No Grouping]"],
				["t.TagName", "Tag"]
			];
		};
		$p.getConfig = function() {
			return { title: "Select Template" };
		};
		$p.getKey = function() {
			return "CopyTPLGroupBy";
		};
	}
}

function setEnabled(element, shouldEnable) {
    if (shouldEnable == true) {
        $(element).removeAttr("disabled");
    }
    else {
        $(element).attr("disabled","disabled");
    }
}


// Credentials Editor Combo Change Handler
function CredentialsEditor_OnSelectedIndexChanged(combo, credNameId, userNameId, passwordId, confirmPasswordId) {
    var credentialSetId = $(combo).val();

    var updateControls = function(credentialSet, enableControls) {
        $(credNameId).val(credentialSet.Name);
        $(userNameId).val(credentialSet.UserName);
        $(passwordId).val(credentialSet.Password);
        $(confirmPasswordId).val(credentialSet.Password);
        
        setEnabled(credNameId, enableControls);
        setEnabled(userNameId, enableControls);
        setEnabled(passwordId, enableControls);
        setEnabled(confirmPasswordId, enableControls);
    };



    if (credentialSetId == -1) {
        var creds = { Name: '', UserName: '', Password: ''};        
        updateControls(creds, true);
    }
    else {
        ORION.callWebService("/Orion/APM/Services/Credentials.asmx", 
                             "GetCredentialsById", { "credentialSetId": credentialSetId }, 
                             function(result){
                                updateControls(result, false);
                             });    
    }
    
}

function DemoModeMessage() {
    alert("This functionality is disabled in the demo.");
    return false;
}

function IsDemoMode() {
    return $("#isDemoMode").length > 0
}


SW.APM.highlightSearchText = function(selector, searchTerm) {

    var quoteForRegExp = function(str) {
        var toQuote = '\\/[](){}?+*|.^$'; // note: backslash must be first
        for (var i = 0; i < toQuote.length; ++i)
            str = str.replace(toQuote.charAt(i), '\\' + toQuote.charAt(i));
        return str;
    };
    
    // search term highlighting adapted from http://dossy.org/archives/000338.html
    var re = new RegExp().compile('(' + quoteForRegExp(searchTerm) + ')', 'ig');
    $(selector + " *").each(function() {
        if ($(this).children().size() > 0) return;
        var html = $(this).html();
        var newhtml = html.replace(re, '<span class="apm_searchterm">$1</span>');
        $(this).html(newhtml);
    });

};

SW.APM.logInToThwack = function(callback, params, showWarning) {
    function val(id) { return Ext.getCmp(id).getValue().trim(); }
    function onValidate(ctrIndex, text) { dlg.buttons[0].setDisabled(val("tliUN") == ""); return true; }
    function onLogIn() {
        ORION.callWebService(
				"/Orion/APM/Services/Thwack.asmx", "LogIn", { userName: val("tliUN"), password: val("tliPSW") },
				function(result) {
				    thwackUserInfo = { name: val("tliUN"), pass: val("tliPSW") };
				    onCancel(); if (callback) { callback(params); }
				}
			);
    }
    function onCancel() { dlg.hide(); dlg.destroy(); dlg = null; }

    var dlg = new Ext.Window({
        title: "thwack Log In Dialog", width: 300, height: showWarning ? 260 : 140, border: false, region: "center", layout: "fit", modal: true, resizable: false, bodyStyle: "padding:5px;",
        items: [
				new Ext.form.FormPanel({
				    frame: true, labelWidth: 100, defaultType: "textfield", labelAlign: "right",
				    items: showWarning ? [
				        { xtype: "label", html: "All community generated content on thwack is the sole responsibility of the originator of the content.  Solarwinds does not pre-screen or review Community generated content, however we will remove any Content, that we become aware of, that is of concern.  Please rely on the number of content downloads, comments and reputation of the content creator as a sign of the reliability.", style: "margin-left:20px;color:#666;" },
				        { xtype: "label", html: "<hr style='width:300px;color:#666;'/>" },
						{ id: "tliUN", fieldLabel: "User Name", anchor: "100%", selectOnFocus: true, validator: onValidate, value: thwackUserInfo.name },
						{ id: "tliPSW", inputType: "password", fieldLabel: "Password", anchor: "100%", selectOnFocus: true, validator: onValidate, value: thwackUserInfo.pass }
					] : [
						{ id: "tliUN", fieldLabel: "User Name", anchor: "100%", selectOnFocus: true, validator: onValidate, value: thwackUserInfo.name },
						{ id: "tliPSW", inputType: "password", fieldLabel: "Password", anchor: "100%", selectOnFocus: true, validator: onValidate, value: thwackUserInfo.pass }
				    ]
				})
			],
        buttons: [{ text: "Log In", disabled: true, handler: onLogIn }, { text: "Cancel", handler: onCancel}]
    });
    dlg.show();
}

/*Unmanage/Remanage Applications functionality*/
SW.APM.ManageApp = function(config) {
	var mDlg = null, mConfig = config;

	/*Helper Members*/
	function call(service, method, params, onSuccess) {
		var paramsStr = Ext.encode(params);
		if (paramsStr.length === 0) { paramsStr = "{}"; }
		$.ajax({
			type: "POST", url: (service + "/" + method), contentType: "application/json; charset=utf-8", dataType: "json", data: paramsStr,
			success: function(msg) { onSuccess(msg.d); },
			error: function(xhr, status, errorThrown) { onCancel(); onError(xhr, status, errorThrown); }
		});
	}
	function getIDs() {
		var ids = []; Ext.each(mConfig.selItems, function(rec) { ids.push(rec.id); });
		return ids;
	}

	/*Event Handlers*/
	function onError(xhr, status, errorThrown) {
		var error = eval("(" + xhr.responseText + ")");
		Ext.Msg.show({
			title: "Manage/Unmanage Application Error",
			msg: error.Message,
			icon: Ext.Msg.ERROR, buttons: Ext.Msg.OK
		});
	}
	function onValidate(ctrID) {
		var bCtr = Ext.getCmp("BeginDate"), eCtr = Ext.getCmp("EndDate"), okBtn = Ext.getCmp("UnmanageOkBtn");
		if (!bCtr || !eCtr || !okBtn) { return true; }
		var date = Ext.getCmp(ctrID).getValue(), bDate = bCtr.getValue(), eDate = eCtr.getValue();
		if (!bDate || !eDate) { okBtn.setDisabled(true); return true; }
		if (ctrID == "BeginDate") { eCtr.setMinValue(date); } else if (ctrID == "EndDate") { bCtr.setMaxValue(date); }
		okBtn.setDisabled(bDate.format("U") >= eDate.format("U") || new Date().format("U") >= eDate.format("U"));
		return true;
	}
	function onOk() {
		var params = {
			appIds: getIDs(), managed: false,
			unmanageFrom: Ext.getCmp("BeginDate").getValue().format("m/d/Y G:i"),
			unmanageUntil: Ext.getCmp("EndDate").getValue().format("m/d/Y G:i")
		};
		call(
			"/Orion/APM/Services/Applications.asmx", "ManageApplications",
			params,
			function() { onCancel(); $("#groupByProperty").change(); if (mConfig.onComplete) { mConfig.onComplete(); } }
		);
	}
	function onCancel() { if (mDlg) { mDlg.hide(); mDlg.destroy(); mDlg = null; } }

	/*Public Members*/
	this.unmanage = function() {
		var today = new Date(), tomorrow = new Date().add(Date.DAY, 1);
		var 
			topLabel = { xtype: "label", html: "Polling and Statistics collection will be suspended while the applications are Unmanaged.", style: "font-size:10pt;" },
			beginDate = {
				id: "BeginDate", xtype: "datefield", format: "m/d/Y g:i A", fieldLabel: "Unmanage this application beginning", anchor: "99%",
				invalidClass: "", validator: function() { return onValidate("BeginDate"); },
				minValue: today, value: today, maxValue: tomorrow
			},
			endDate = {
				id: "EndDate", xtype: "datefield", format: "m/d/Y g:i A", fieldLabel: "Unmanage this application until", anchor: "99%",
				invalidClass: "", validator: function() { return onValidate("EndDate"); },
				minValue: today, value: tomorrow
			},
			col1 = { columnWidth: 1, layout: "form", labelWidth: 270, border: false, items: [beginDate, endDate] },
			buttomLabel = { xtype: "label", html: "Polling and Statistics collection will automatically restart after this Date/Time.", style: "font-size:10pt;margin-left:50px;" };

		mDlg = new Ext.Window({
			title: String.format("Unmanage {0} Application{1}", mConfig.selItems.length, (mConfig.selItems.length > 1 ? "s" : " ")),
			width: 600, height: 170, border: false, region: "center", layout: "fit", modal: true, resizable: false, bodyStyle: "padding:5px;",
			items: [
				topLabel,
				new Ext.form.FormPanel({ frame: true, style: "margin-left:50px;", items: [{ layout: "column", border: false, items: [col1]}] }),
				buttomLabel
			],
			buttons: [{ id: "UnmanageOkBtn", text: "Ok", handler: onOk }, { text: "Cancel", handler: onCancel}]
		});
		mDlg.show();
		return false;
	}
	this.remanage = function() {
		var waitMsg = Ext.Msg.wait(String.format("Remanage Application{0}", mConfig.selItems.length > 1 ? "s" : ""));
		function onComplete(appIDs) {
			waitMsg.hide();
			if (appIDs.length > 0) {
				var nms = []; Ext.each(mConfig.selItems, function(rec) { if (appIDs.indexOf(d.ApplicationID) > -1) { nms.push(rec.Name); } });
				Ext.Msg.show({
					title: "Remanaged Information",
					msg: String.format("Following application{0} (<b>{1}</b>) assigned to currently unmanaged(or unreachable) nodes and should remain unmanaged also.<br/>They will be remanaged as soon as nodes are remanaged.", (nms.length > 1 ? "s" : ""), nms.join(", ")),
					icon: Ext.Msg.INFO, buttons: Ext.Msg.OK
				});
			}
			$("#groupByProperty").change(); if (mConfig.onComplete) { mConfig.onComplete(); }
		}
		var now = new Date().format("m/d/Y G:i");
		call(
			"/Orion/APM/Services/Applications.asmx", "ManageApplications",
			{ appIds: getIDs(), managed: true, unmanageFrom: now, unmanageUntil: now },
			onComplete
		);
		return false;
	}
}
SW.APM.ManageApp.manage = function(config) {
	if (config.mode == "unmanage") {
		return new SW.APM.ManageApp(config).unmanage();
	}
	if (config.mode == "remanage") {
		return new SW.APM.ManageApp(config).remanage();
	}
	return false;
}

SW.APM.UpdateLicenseMessage = function(moduleName, daysLeft) {
    var banner = $('#evalBanner')[0];
    if( !banner ) { 
        $('#moduleList').before("<div id='evalBanner' style='width: 100%;'></div>"); 
        banner = $('#evalBanner')[0]; 
    }
    if( !banner ) return;

    var t = $(banner).text();

    t = t.replace( /^\s*this /i, 'Orion ' );
    t += " " + moduleName + " Evaluation has " + daysLeft + " days left.";
    $(banner).text( t );
}

SW.APM.ShowSelectedItemList = function(selectedItems) {
    var items = selectedItems.split(",");
    
    var list = ["<ul style='list-style-type:square;margin-left:20px;'>"];
    Ext.each(items, function(item) { list.push("<li>" + item + "</li>"); });
    list.push("</ul>");  
    
    var listHtml = list.join('');
    

    var dlg = new Ext.Window({
        title:  String.format("All Selected Nodes ({0})", items.length),
        width: 500,
        height: 350,
        border: false, 
        region: "center", 
        layout: "fit", 
        modal: true, 
        resizable: false, 
        plain: true,
        
        items: new Ext.Panel({
            frame: true,
            autoScroll: true, 
            defaultType: "label", 
            html: listHtml            
        }),
    
        buttons: [ {
            text: "Close",
            handler: function() {
                dlg.hide();
                dlg.destroy();
                dlg = null;
            }
        }]
    });
    
    dlg.show();
    return false;
}
var settEditUtility = {
	onChange: function(sender, params) {
		var sel = $(sender), parent = sel.parent().parent(), table = parent.children("table.apm_SubItemContainer"); 
		var spanEdit = parent.children("span[id$='editContainer']"), spanView = parent.children("span[id$='viewContainer']");
		var isAct = ((spanEdit.css("display") != "none" && sel.val() == params) || (spanView.css("display") != "none" && $.trim(spanView.text()) == params));
		table.css("display", isAct ? "block" : "none");
	},
	update: function(info) {
		for (var i = 0; i < info.length; i++) {
			settEditUtility.onChange($id(info[i].id), info[i].cmd)
		}
	}
};

