var Utils = new Object();
BARCHART_VIEW = 2;
TABLE_VIEW = 0;
DEFAULT_VIEW = BARCHART_VIEW;
DEFAULT_ADD_CHECK_TIMEOUT = 10000;
STATUS_OK="ok";
STATUS_UPGRADE = "upgrade";
STATUS_FREEZE = "freeze";
STATUS_DISABLED = "disabled";
STATUS_EXISTS="exists";
TEST_STATUS_OK_STRING="OK";
TEST_STATUS_NOK_STRING="NOK";
TEST_STATUS_NA_STRING="NA";
TEST_STATUS_WARNING_STRING="ERROR";
TEST_FAIL_POINT=10000;
TYPE_CURRENT=0;
TYPE_FIXED=1;
TYPE_PREVIOUS=2;
INTERVAL_MONTHLY=0;
INTERVAL_DAILY=1;
INTERVAL_HOURLY=2;
intervals=eval("("+"{'"+INTERVAL_MONTHLY+"':'monthly','"+INTERVAL_DAILY+"':'daily','"+INTERVAL_HOURLY+"':'hourly'}"+")");
AGENT_TYPE_PROCESS="1";
AGENT_TYPE_DRIVE="2";
AGENT_TYPE_MEMORY="3";
AGENT_TYPE_HTTP="4";
AGENT_TYPE_PING="5";
AGENT_TYPE_LOAD_AVERAGE="6";
AGENT_TYPE_CPU="7";
AGENT_TYPE_EVENT_LOG="12";
AGENT_TYPE_PROGRAMM="13";
AGENT_TYPE_SNMP_TRAP="15";
AGENT_TYPE_SNMP_OBJECT="11";
AGENT_TYPE_SNMP_TABLE="10";
AGENT_TYPE_DISCOVERY="17";
AGENT_TYPE_WALK="16";
CUSTOM_LOCATION = 111;

NETWORK_TEST_TYPES = [AGENT_TYPE_SNMP_TRAP, AGENT_TYPE_SNMP_OBJECT, AGENT_TYPE_SNMP_TABLE, AGENT_TYPE_DISCOVERY];

REPORT_TYPE_EXTERNAL=1;
REPORT_TYPE_PROCESS=2;
REPORT_TYPE_MEMORY=3;
REPORT_TYPE_DRIVE=4;
REPORT_TYPE_CPU=5;
REPORT_TYPE_LOAD_AVERAGE=6;

var REPORT_TYPES = ["External", "Process", "Memory", "Drive", "CPU", "Load Avg"];

AGENT_TYPE_NAMES={};
AGENT_TYPE_NAMES[AGENT_TYPE_PROCESS]="process"
AGENT_TYPE_NAMES[AGENT_TYPE_DRIVE]="drive";
AGENT_TYPE_NAMES[AGENT_TYPE_MEMORY]="memory";
AGENT_TYPE_NAMES[AGENT_TYPE_HTTP]="test";
AGENT_TYPE_NAMES[AGENT_TYPE_PING]="test";
AGENT_TYPE_NAMES[AGENT_TYPE_EVENT_LOG]="event log";
AGENT_TYPE_NAMES[AGENT_TYPE_PROGRAMM]="programm";
AGENT_MODULES={};
AGENT_MODULES[AGENT_TYPE_EVENT_LOG]={name:"EventLog"};
AGENT_MODULES[AGENT_TYPE_PROGRAMM]={name:"AgentProgram"};
AGENT_MODULES[AGENT_TYPE_SNMP_OBJECT]={name:"SnmpObject"};
AGENT_MODULES[AGENT_TYPE_SNMP_TABLE]={name:"SnmpTable"};
AGENT_MODULES[AGENT_TYPE_SNMP_TRAP]={name:"SnmpTrap"};
SORT_TYPE_ASC="asc";
SORT_TYPE_DESC="desc";
OS_WINDOWS=1;
OS_LINUX=2;
PLATFORM_32="32";
PLATFORM_64="64";

FREE_BSD_X86="FBSD32";
FREE_BSD_X64="FBSD64";

//agent policies types 
var AGENT_POLICY_SERVER_INFORMATION = 1;
var AGENT_POLICY_RESOURCE_MONITORS  = 2;
var AGENT_POLICY_BASIC_CONFIGURATION = 3;


//policy types
var POLICY_TYPE_AGENT = "agent";
var POLICY_TYPE_EC2 = "ec2";

//policy Types for EC2
//var EC2_POLICY_NEW_RESOURCE_MONITORS = 4;
var EC2_POLICY_OLD_RESOURCE_MONITORS = 5;
//var EC2_POLICY_NEW_EXTERNAL_MONITORS = 6;
var EC2_POLICY_OLD_EXTERNAL_MONITORS = 7;
//var EC2_POLICY_NEW_INSTALL_AGENT = 8;
var EC2_POLICY_OLD_INSTALL_AGENT = 9;
//policy monitor types with configs
var POLICY_EC2_MONITOR_TYPE_EXTERNAL_MONITORS_NEW_EC2_HTTP = 31;
var POLICY_EC2_MONITOR_TYPE_EXTERNAL_MONITORS_OLD_EC2_HTTP = 28;
var POLICY_EC2_MONITOR_TYPE_INTERNAL_MONITORS_OLD_EC2_PROCESS = 33;
//policy Types for Cloud
var CLOUD_POLICY_EXTERNAL_MONITORS = {"Rackspace":{"TYPE_ID":10,"HTTP":35}, "AmazonEC2":{"TYPE_ID":7,"HTTP":28},"GoGrid":{"TYPE_ID":11,"HTTP":37}};
var CLOUD_POLICY_RESOURCE_MONITORS = {"AmazonEC2":{"TYPE_ID":5,"PROCESS":33},"Rackspace":{},"GoGrid":{}};
var CLOUD_POLICY_INSTALL_AGENT = {"AmazonEC2":{"TYPE_ID":9},"Rackspace":{},"GoGrid":{}};

// notification data types
var NOTIFICATION_DATA_TYPE_TEST = 0;
var NOTIFICATION_DATA_TYPE_AGENT_PROCESS = 1;
var NOTIFICATION_DATA_TYPE_AGENT_DRIVE = 2;
var NOTIFICATION_DATA_TYPE_AGENT_MEMORY = 3;
var NOTIFICATION_DATA_TYPE_AGENT_HTTP = 4;
var NOTIFICATION_DATA_TYPE_AGENT_PING = 5;
var NOTIFICATION_DATA_TYPE_AGENT_LOAD = 6;
var NOTIFICATION_DATA_TYPE_AGENT_CPU = 7;
var NOTIFICATION_DATA_TYPE_TRANSACTION = 8;
var NOTIFICATION_DATA_TYPE_AGENT_EVENT_LOG = 12;
var NOTIFICATION_DATA_TYPE_AGENT_PROGRAM = 13;
var NOTIFICATION_DATA_TYPE_EC2 = 14;
var NOTIFICATION_DATA_TYPE_AGENT_SNMP_TRAP = 15;

var NOTIFICATION_RULE_MAX_LOAD_DEFAULT = 20;

var TEST_TYPES = {};
TEST_TYPES[NOTIFICATION_DATA_TYPE_TEST] = {dataId: ":dataId", moduleName: "Test"};
TEST_TYPES[NOTIFICATION_DATA_TYPE_AGENT_PROCESS] = {dataId: NOTIFICATION_DATA_TYPE_AGENT_PROCESS+":dataId", moduleName: "Agent"};
TEST_TYPES[NOTIFICATION_DATA_TYPE_AGENT_DRIVE] = {dataId: NOTIFICATION_DATA_TYPE_AGENT_DRIVE+":dataId", moduleName: "Agent"};
TEST_TYPES[NOTIFICATION_DATA_TYPE_AGENT_MEMORY] = {dataId: NOTIFICATION_DATA_TYPE_AGENT_MEMORY+":dataId", moduleName: "Agent"};
TEST_TYPES[NOTIFICATION_DATA_TYPE_AGENT_HTTP] = {dataId: NOTIFICATION_DATA_TYPE_AGENT_HTTP+":dataId", moduleName: "Agent"};
TEST_TYPES[NOTIFICATION_DATA_TYPE_AGENT_PING] = {dataId: NOTIFICATION_DATA_TYPE_AGENT_PING+":dataId", moduleName: "Agent"};
TEST_TYPES[NOTIFICATION_DATA_TYPE_AGENT_LOAD] = {dataId: NOTIFICATION_DATA_TYPE_AGENT_LOAD+":dataId", moduleName: "Agent"};
TEST_TYPES[NOTIFICATION_DATA_TYPE_AGENT_CPU] = {dataId: NOTIFICATION_DATA_TYPE_AGENT_CPU+":dataId", moduleName: "Agent"};
TEST_TYPES[NOTIFICATION_DATA_TYPE_TRANSACTION] = {dataId: ":dataId", moduleName: "Transaction"};
TEST_TYPES[NOTIFICATION_DATA_TYPE_AGENT_EVENT_LOG] = {dataId: ":dataId", moduleName: "EventLog"};
TEST_TYPES[NOTIFICATION_DATA_TYPE_AGENT_PROGRAM] = {dataId: ":dataId", moduleName: "AgentProgram"};
var sharedPageInd=false;
var getViewIdByView = function(viewDescr){
	var viewId = TABLE_VIEW;
	switch(viewDescr){
		case 'loadTable': viewId = TABLE_VIEW; break;
		case 'loadBarChart': 
		case 'loadBar': viewId = BAR_VIEW; break;
		case 'loadLineChart':
		case 'loadLine': viewId = LINE_VIEW; break;
		case 'loadAngleChart':
		case 'loadScatter':  viewId = ANGLE_VIEW; break;
		case 'loadMap': viewId = MAP_VIEW; break;
		case 'loadCalendar': viewId = CALENDAR_VIEW; break;
	}
	return viewId;
}


var getDataTypeId = function(agType){
	var agTypeId = 1;

	if(agType == AGENT_TYPE_PROCESS) agTypeId = parseInt(NOTIFICATION_DATA_TYPE_AGENT_PROCESS);
	else if(agType == AGENT_TYPE_DRIVE) agTypeId = parseInt(NOTIFICATION_DATA_TYPE_AGENT_DRIVE);
	else if(agType == AGENT_TYPE_MEMORY) agTypeId = parseInt(NOTIFICATION_DATA_TYPE_AGENT_MEMORY);
	else if(agType == AGENT_TYPE_HTTP) agTypeId = parseInt(NOTIFICATION_DATA_TYPE_AGENT_HTTP);
	else if(agType == AGENT_TYPE_PING) agTypeId = parseInt(NOTIFICATION_DATA_TYPE_AGENT_PING);
	else if(agType == AGENT_TYPE_CPU) agTypeId = parseInt(NOTIFICATION_DATA_TYPE_AGENT_CPU);
	else if(agType == AGENT_TYPE_LOAD_AVERAGE) agTypeId = parseInt(NOTIFICATION_DATA_TYPE_AGENT_LOAD);
	else if(agType == AGENT_TYPE_PROGRAMM) agTypeId = parseInt(NOTIFICATION_DATA_TYPE_AGENT_PROGRAM);
	else if(agType == AGENT_TYPE_EVENT_LOG) agTypeId = parseInt(NOTIFICATION_DATA_TYPE_AGENT_EVENT_LOG);
	return agTypeId;
	
}
var getDataTypeById = function(agTypeId){
	var agType = "Process";
	
	if(agTypeId == AGENT_TYPE_PROCESS) agType = Framework.Lang.AgentTestTypes.Processes;
	else if(agTypeId == AGENT_TYPE_DRIVE) agType = Framework.Lang.AgentTestTypes.Drive;
	else if(agTypeId == AGENT_TYPE_MEMORY) agType = Framework.Lang.AgentTestTypes.Memory;
	else if(agTypeId == AGENT_TYPE_HTTP) agType = Framework.Lang.AgentTestTypes.HTTP;
	else if(agTypeId == AGENT_TYPE_PING) agType = Framework.Lang.AgentTestTypes.PING;
	else if(agTypeId == AGENT_TYPE_LOAD_AVERAGE) agType = Framework.Lang.AgentTestTypes.LoadAverage;
	else if(agTypeId == AGENT_TYPE_CPU) agType = Framework.Lang.AgentTestTypes.CPU;
	else if(agTypeId == AGENT_TYPE_PROGRAMM) agType = Framework.Lang.AgentTestTypes.InstalledSoftware;
	else if(agTypeId == AGENT_TYPE_EVENT_LOG) agType = Framework.Lang.AgentTestTypes.SystemEvents;
	return agType;
	
}
function getDateFromString(dateStr){
	var datesArr = dateStr.split("-");
    var day = datesArr[2].substring(0, 2);
	var month = datesArr[1];
	var year = datesArr[0];
	var hoursArr = datesArr[2].substring(3).split(":");
	var hour = hoursArr[0];
	var minute = hoursArr[1];
	var second = hoursArr[2];
    if(!second) second='00'	;
	var dat = new Date(year, month-1, day, hour, minute, second);
	return dat;
}

var drawLocations = function(locations){
	if (typeof locations == "undefined") {
		locations = getLocations();
	}
	var tdContent = '<table cellpadding="0px" cellspacing="2px" class="text"><tbody><tr>';
	var ch = "checked";
	for(var i = 0; i < locations.length; i++){
			tdContent += '<td><input name="location" type="checkbox" value="'+locations[i].id+'" ';
			if(locations[i].id == 1 )tdContent += " checked";
			tdContent += '></td><td nowrap>'+locations[i].name+'</td>';
	
	}
	tdContent += '</tr></tbody></table>';
	return tdContent;
}

var drawLocationsForEdit = function(moduleId, intervals, selectedLocations, locations, moduleIntervals, minFrequency){
	var tdContent = '<table cellpadding="0px" cellspacing="2px" class="text"><tbody>';
	var locationNames = [];
	var num = 0;
	var ch = "checked";
	for(var i = 0; i < locations.length; i++){
			tdContent += '<tr><td><input '+(isReadonly() && !User.permissions['R_manage '+PortletLoader.getPortlet(moduleId).moduleName+'s']?' disabled=true ':'')+ ' name="location' + moduleId +'" type="checkbox" value="'+locations[i].id+'" ';
			//if(locations[i].id == 1)
			//	tdContent += " checked";
			//else
			locationNames[num] = locations[i].name;
			if(typeof intervals[locations[i].id] != 'undefined')
				tdContent += " checked";
				if(i == 0)
					tdContent += '></td><td>'+locations[i].name+'</td><td>'+ getIntervalsContent(moduleId, locations[i].id, intervals, moduleIntervals, minFrequency) +'</td>&nbsp;mins</tr>';
				else
					tdContent += '></td><td>'+locations[i].name+'</td><td>'+ getIntervalsContent(moduleId, locations[i].id, intervals, moduleIntervals, minFrequency) +'</td></tr>';
		num++;
	}
	
	for(var i = 0; typeof selectedLocations != "undefined" && i < selectedLocations.length; i++){
		if(locationNames.indexOf(selectedLocations[i].name) == -1){
			tdContent += '<tr><td><input name="location' + moduleId +'" type="checkbox" value="'+selectedLocations[i].id+'" ';
			//if(locations[i].id == 1)
			//	tdContent += " checked";
			//else
			if(typeof intervals[selectedLocations[i].id] != 'undefined')
				tdContent += " checked";
				if(i == 0)
					tdContent += '></td><td>'+selectedLocations[i].name+'</td><td>'+ getIntervalsContent(moduleId, selectedLocations[i].id, intervals, moduleIntervals, minFrequency) +'</td></tr>';
				else
					tdContent += '></td><td>'+selectedLocations[i].name+'</td><td>'+ getIntervalsContent(moduleId, selectedLocations[i].id, intervals, moduleIntervals, minFrequency) +'</td></tr>';
		}
	}
	tdContent += '</tbody></table>';
	return tdContent;
}

var getIntervalsContent = function(moduleId, locationId, intervals, moduleIntervals, minFrequency){
	var intervalsContent = '<select '+(isReadonly() && !User.permissions['R_manage '+PortletLoader.getPortlet(moduleId).moduleName+'s']?' disabled=true ':'')+ ' name="interval" id="interval' + moduleId + '_' + locationId + '" width=45>';
	if(locationId >= CUSTOM_LOCATION){
		intervalsContent += '<option value="'+intervals[locationId]+'" selected>' + intervals[locationId];
	}
	else
		for(var i=moduleIntervals.indexOf(minFrequency); i<moduleIntervals.length; i++){
			if(intervals[locationId] == moduleIntervals[i])
				intervalsContent += '<option value="'+moduleIntervals[i]+'" selected>' + moduleIntervals[i];
			else
				intervalsContent += '<option value="'+moduleIntervals[i]+'">' + moduleIntervals[i];
		}
	intervalsContent += '</select>';
	return intervalsContent;
}

var getLocationById=function(id){
	var locations = getLocations();
	for(var i=0; i<locations.length;i++){
		if(locations[i].id==id){
			return locations[i];
		}
	}
	return null;
}

var getTransactionLocationById=function(id){
	var locations = getTransactionLocations();
	for(var i=0; i<locations.length;i++){
		if(locations[i].id==id){
			return locations[i];
		}
	}
	return null;
}

LOAD_VIEW='9';
HTTP_GET=1;
HTTP_POST=2;
var WEEKDAYS_M = new Array("Sunday","Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday");
var WEEKDAYS = new Array("Sunday","Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday");
var MONTHS = new Array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");
PERSONALPLAN = 0;
BASICPLAN = 1;
PLUSPLAN = 2;
PLUS1MINUTEPLAN = 6;
FREEPLAN = 3;
PERSONALPLUSPLAN = 11;
BASICPLUSPLAN = 12;
TESTSPLUSPLAN = 8;
PERSONAL1PLAN=13;
SPECIALTEST1500=21;
READONLY = 35;
WEBPROPLAN = 7;
TRIALPLAN = 25;
// Major version of Flash required
var requiredMajorVersion = 9;
var requiredMinorVersion = 0;
var requiredRevision = 0;
//////////////////////////////////
HTTP_PUT=3;
HTTP_DELETE=4;
function isLocationAvailable(loc){
	return (User.permissions[loc] ? true : false); 
}

function isReadonly(){
	return (User.planName.indexOf("READONLY") != -1);
}
	
function getNotificationTimesheet(){
	var timesheet = [];
	timesheet[0]={};
	timesheet[0].name = Framework.Lang.NotificationState_always;
	timesheet[0].id = 1;
	
	timesheet[1]={};
	timesheet[1].name = Framework.Lang.NotificationState_everyday;
	timesheet[1].id = 2;
	
	timesheet[2]={};
	timesheet[2].name = Framework.Lang.NotificationState_specific;
	timesheet[2].id = 3;
	
	return timesheet;
}		
function getLocationById(idd){
	var locs = getLocations();
	var loc = null;
	for(var i = 0; i < locs.length; i++){
		if(locs[i].id == idd) loc = locs[i];
	}
	return loc;
}		
function getLocations(){
	var locationItem;
	var locations = [];
		
	if(isLocationAvailable(1)){
		locationItem={};
		locationItem.name="US-MID";
		locationItem.fullName="US-MID";
		locationItem.id=1;
		locationItem.active=true;
		locations.push(locationItem);
	}	
	if(isLocationAvailable(9)){
		locationItem={};
		locationItem.name="US-EST";
		locationItem.fullName="US-EST";
		locationItem.id=9;
		locationItem.active=true;
		locations.push(locationItem);
	}
	if(isLocationAvailable(10)){
		locationItem={};
		locationItem.name="US-WST";
		locationItem.fullName="US-WST";
		locationItem.id=10;
		locationItem.active=true;
		locations.push(locationItem);
	}	
	if(isLocationAvailable(4)){
		locationItem={};
		locationItem.name="UK";
		locationItem.fullName="UK";
		locationItem.id=4;
		locationItem.active=true;
		locations.push(locationItem);
	}
	if(isLocationAvailable(5)){
		locationItem={};
		locationItem.name="PA";
		locationItem.fullName="Panama";
		locationItem.id=5;
		locationItem.active=true;
		locations.push(locationItem);
	}
	if(isLocationAvailable(7)){
		locationItem={};
		locationItem.name="DE";
		locationItem.fullName="Germany";
		locationItem.id=7;
		locationItem.active=true;
		locations.push(locationItem);
	}
	if(isLocationAvailable(6)){
		locationItem={};
		locationItem.name="AU";
		locationItem.fullName="Australia";
		locationItem.id=6;
		locationItem.active=true;
		locations.push(locationItem);
	}
	if(isLocationAvailable(8)){
		locationItem={};
		locationItem.name="CN";
		locationItem.fullName="China";
		locationItem.id=8;
		locationItem.active=true;
		locations.push(locationItem);
	}
	if(isLocationAvailable(11)){
		locationItem={};
		locationItem.name="NL";
		locationItem.fullName="Netherlands";
		locationItem.id=11;
		locationItem.active=true;
		locations.push(locationItem);
	}	
	return locations;
}
function getTransactionLocationById(idd){
	var locs = getTransactionLocations();
	var loc = null;
	for(var i = 0; i < locs.length; i++){
		if(locs[i].id == idd) loc = locs[i];
	}
	return loc;
}	
function getTransactionLocations(){
	var locationItem;
	var locations = [];
		
	if(isLocationAvailable("1_US_L")){
		locationItem={};
		locationItem.name="US MID";
		locationItem.fullName="US MID";
		locationItem.id=1;
		locationItem.active=true;
		locations.push(locationItem);
	}	
	if(isLocationAvailable("2_DE_L")){
		locationItem={};
		locationItem.name="DE";
		locationItem.fullName="DE";
		locationItem.id=2;
		locationItem.active=true;
		locations.push(locationItem);
	}
	if(isLocationAvailable("3_US_W")){
		locationItem={};
		locationItem.name="US EAST";
		locationItem.fullName="US EAST";
		locationItem.id=3;
		locationItem.active=true;
		locations.push(locationItem);
	}
	if(isLocationAvailable("4_UK_W")){
		locationItem={};
		locationItem.name="UK";
		locationItem.fullName="UK";
		locationItem.id=4;
		locationItem.active=true;
		locations.push(locationItem);
	}
	if(isLocationAvailable("5_HK_W")){
		locationItem={};
		locationItem.name="HK";
		locationItem.fullName="HK";
		locationItem.id=5;
		locationItem.active=true;
		locations.push(locationItem);
	}
	if(isLocationAvailable("6_AU_L")){
		locationItem={};
		locationItem.name="AU";
		locationItem.fullName="AU";
		locationItem.id=6;
		locationItem.active=true;
		locations.push(locationItem);
	}
	if(isLocationAvailable("7_BR_W")){
		locationItem={};
		locationItem.name="BR";
		locationItem.fullName="BR";
		locationItem.id=7;
		locationItem.active=true;
		locations.push(locationItem);
	}
	if(isLocationAvailable("8_NL_L")){
		locationItem={};
		locationItem.name="NL";
		locationItem.fullName="NL";
		locationItem.id=8;
		locationItem.active=true;
		locations.push(locationItem);
	}
	return locations;
}

function checkStatus(response){
	var json_obj = eval("("+response.responseText+")");
	if (json_obj.status != STATUS_OK)
		alert(json_obj.status);
}

function getValidID( startId ){
	var obj = $id( startId );
	while( obj != null ){
		startId += String.fromCharCode(97 + Math.round(Math.random() * 25));;
		obj = $id( startId );
	}
	return startId;
}

function disableSelecting( event ){
	return false;
}

function changeStyle(newTheme){
		var links = document.getElementsByTagName("link");
		
		var newStylePath = '/themes/'+newTheme+'/'+newTheme+'.css';
		var currentStylePath = 'themes/'+OPTIONS.theme+'/'+OPTIONS.theme+'.css';
		for(var i = 0; i < links.length; i++){
			if( links[i].href.indexOf(currentStylePath) >= 0){
				links[i].href = (Framework.serverPath + newStylePath);
				break;
			}
		}

		var newExtStyle = 'ext-all-' + newTheme + '.css';
		var curExtStyle = 'ext-all-' + OPTIONS.theme + '.css';
		for(var i = 0; i < links.length; i++){
			if( links[i].href.indexOf(curExtStyle) >= 0){
				links[i].href = (Framework.serverPath + '/libs/EXT_JS_3/resources/css/' + newExtStyle);
				break;
			}
		}
		var tabOptionsAnchors = document.getElementsByName('tabOptionsAnchor');
		for(var i = 0; i < tabOptionsAnchors.length; i++)
			tabOptionsAnchors[i].style.backgroundImage = 'url(libs/EXT_JS_3/resources/images/' + newTheme + '/grid/sort_desc.gif)';

		THEME_IMG_ROOT = "themes/" + newTheme + "/";
		//PortletLoader.changePortletHeaderImg();
		//changeRadioCheckImg();
		$id(OPTIONS.theme + "_skin").className = "";
		$id(newTheme + "_skin").className = " selected";
		OPTIONS.theme = newTheme;
		RequestDispatcher.send(Framework.optionsURL + User.userId + "/update/theme/" + OPTIONS.theme, "PUT", "", checkStatus, null);
		
		for (var i=0; i<THEME_DEPENDENT_MODULES.length; i++){
			PortletLoader.refresh_modules(THEME_DEPENDENT_MODULES[i]);
		}
}

function changeStyle2( i, path ){
	if( changeStyle2.STEPS > 0){
		node = document.getElementsByTagName("link")[i];
		node.href = (Framework.serverPath + path);
		changeStyle2.STEPS --;
		if( Browser.isIE ){
			setTimeout( "changeStyle2( "+ i +", \""+ path +"\" )", 1000 );
		}
	}
}
changeStyle2.STEPS = 5;


function parseBool( str ){
	if( str == "false" || str == false)
		return false;
	else if( str == "true" || str == true)
		return true;
	return null;
}

function makeKeyValue( domNode , arr){
		if( arr == null  )arr = {};

		domNode = domNode.childNodes;
		for( var i=0; i<domNode.length; i++ ){
			if( domNode[i].nodeType != 1 )continue;
			var attrName  = domNode[i].nodeName;
			var attrValue = domNode[i].firstChild.nodeValue;
			var parsedBool = parseBool(attrValue);
			arr[ attrName ] = attrValue;
		}
		return arr;
}

function findPosXY( obj ){
	var curleft = 0;
	var curtop = 0;

	try{
		if (obj.offsetParent) {
			while (obj.offsetParent) {
				if(obj.offsetParent.offsetParent==null)		break;

				curleft += obj.offsetLeft;
				curtop  += obj.offsetTop;
				obj = obj.offsetParent;
			}
		}else{
			if (obj.x) curleft += obj.x;
			if (obj.y) curtop  += obj.y;
		}
	}catch(ex){}

	var retObj = new Object();
	retObj.left = curleft;
	retObj.top  = curtop;

	return retObj;
}

function findPosX(obj){
	var curleft = 0;
	try{
			if (obj.offsetParent) {
				while (obj.offsetParent) {
					if(obj.offsetParent.offsetParent==null)
						break;
					curleft += obj.offsetLeft;
					obj = obj.offsetParent;
				}
			} else if (obj.x) curleft += obj.x;
	}catch(ex){}

	return curleft;
}

function findPosY(obj) {
	var curtop = 0;
	try{
		if (obj.offsetParent) {
			while (obj.offsetParent) {
				if(obj.offsetParent.offsetParent.offsetParent==null)
						break;
				curtop += obj.offsetTop;
				obj = obj.offsetParent;
			}
		} else if (obj.y) curtop += obj.y;
	}catch(ex){}
	return curtop;
}
function parseStylePX( size ){
	if( typeof(size) == "string" ){
		if( size.charAt(size.length -2) + "" + size.charAt(size.length -1) == "px" )
			size = parseInt(size.substr( 0, size.length -2 ));
		else
			size = parseInt(size);
	}
	if( isNaN(size) ) size = 0;
	return 	size;
}

function createElementVsClassName( tagName, className , id ){
	var element = document.createElement( tagName );
	if( className != null ) element.className = className;
	if( id        != null ) element.setAttribute( "id", id );
	return element;
}


function getObjectRealPosition(object,topLeft){
	if(topLeft)value = object.offsetTop;
	else value = object.offsetLeft;

	while(object.offsetParent !=null){
		if(topLeft)value = value + object.offsetParent.offsetTop;
		else value = value + object.offsetParent.offsetLeft;
		object = object.offsetParent;
	}
	return value;
}


var Browser;
var OS = new Object();
	OS.isLinux = (navigator.platform.toLowerCase().indexOf("linux")!=-1);
	OS.isMac = (navigator.platform.toLowerCase().indexOf("mac")!=-1);
	OS.isWindows = (navigator.platform.toLowerCase().indexOf("win")!=-1);

modulesCount=6;
maxHeight = 0;
counter = 1;
modulesIds = new Array();

function checkBrowserVersion() {
		Browser = new Object();

		Browser.isMozilla = (typeof document.implementation != 'undefined') && (typeof document.implementation.createDocument != 'undefined') && (typeof HTMLDocument!='undefined');
		Browser.isIE 	  = window.ActiveXObject ? true : false;
		Browser.isIE6 = ( Browser.isIE&& /msie 6\.0/i.test(navigator.userAgent) );
		Browser.isFirefox = (navigator.userAgent.toLowerCase().indexOf("firefox")!=-1);
		Browser.isOpera   = (navigator.userAgent.toLowerCase().indexOf("opera")!=-1);
		Browser.isChrome = (navigator.userAgent.toLowerCase().indexOf("chrome")!=-1);
		Browser.isSafari = (!Browser.isChrome && navigator.userAgent.toLowerCase().indexOf("safari")!=-1);
		Browser.isMacFirefox = (OS.isMac && Browser.isFirefox);
		Browser.isWindowsSafari = (OS.isWindows && Browser.isSafari);
		
		var agt=navigator.userAgent.toLowerCase();
		var is_major = parseInt(navigator.appVersion);
		Browser.isIE6 =(Browser.isIE && (is_major == 4) && (agt.indexOf("msie 6.")!=-1) );
		Browser.isiPhone = (navigator.userAgent.match(/iPhone/i))||(navigator.userAgent.match(/iPod/i));
		return Browser;
}

browserVersion = checkBrowserVersion();


function setZIndex( obj, zIndex ){
	if( obj != null && obj.nodeType != 3)obj.style.zIndex = zIndex;
	for( var i=0; i<obj.childNodes.length; i++ )
		setZIndex( obj.childNodes[i], zIndex );
}
function parseXMLStr(stringToParse) {

		var Browser = checkBrowserVersion();
		var rootTag = null;
		if (Browser.isIE) {
			var xmlDocument = new ActiveXObject('Microsoft.XMLDOM');
			xmlDocument.async = false;
			xmlDocument.loadXML(stringToParse);
			var rootTag = xmlDocument.documentElement;
		}else if (Browser.isMozilla) {
			var domParser = new DOMParser();
			var xmlDocument = domParser.parseFromString(stringToParse,"text/xml");
			var rootTag = xmlDocument.documentElement;
		}else {
			var domParser = new DOMParser();
			var xmlDocument = domParser.parseFromString(stringToParse,"text/xml");
			var rootTag = xmlDocument.documentElement;
		}
		return rootTag;
}

function testForObject(Id){
  var o = $id(Id);
  if (o){
 	return true;
  }
  return false;
}


function setModCount(c){
	modulesCount = c;
}

function setXSizesLast(){
		counter++;
		if(counter==modulesCount){
			setXSizes();
		}
}

function setIsMax(id, qsize){
	var qmaxHeight = $id("maxHeight").value;
	modulesIds.push(id);
	if(qmaxHeight<qsize-40){
		$id("maxHeight").value = qsize-40;
	}
}

function setXSizes(){
	var xSize = $id("maxHeight").value
	var i=0;
	for(i=0; i < modulesIds.length; i++){
		if(testForObject(modulesIds[i]+"_table")){
				$id(modulesIds[i]+"_table").style.height= xSize + "px";
		}
	}

}

function resetXSizes(){
	var i=0;
	for(i=0; i < modulesIds.length; i++){
		if(testForObject(modulesIds[i]) && ($id(modulesIds[i]+"_table").offsetHeight > $id("maxHeight").value))	{
				$id("maxHeight").value = $id(modulesIds[i]+"_table").offsetHeight;
		}
	}
	downsize();
	setXSizes();
}

function downsize(){
	var i=0;
	var max=0;
	for(i=0; i < modulesIds.length; i++){
		var obj = $id( modulesIds[i] + '_table' );
		if( obj != null && max < obj.offsetHeight){
			max = obj.offsetHeight;
		}

	}

	max+=5;
	var maxHeightOBJ = $id("maxHeight");

	if( maxHeightOBJ == null ){
		maxHeightOBJ = document.createElement("INPUT");
		maxHeightOBJ.setAttribute( "id", "maxHeight" );
		maxHeightOBJ.setAttribute( "type", "hidden" );
		if(document.body )
			document.body.appendChild( maxHeightOBJ );
	}

	if(maxHeightOBJ.value > max){
		maxHeightOBJ.value = max;
	}

	for(i=0; i < modulesIds.length; i++){
		if(testForObject(modulesIds[i])){
			$id(modulesIds[i]+"_table").style.height= max + "px";
		}
	}
	var xSize = $id("maxHeight").value;
	for(i=0; i < modulesIds.length; i++){
		if(testForObject(modulesIds[i])){
			$id(modulesIds[i]+"_table").style.height= xSize + "px";
		}
	}
}

function execJS(node) {
  var st = node.getElementsByTagName('SCRIPT');
  var strExec;
  for(var i=0;i<st.length; i++) {
    if (Browser.isSafari) {
      strExec = st[i].innerHTML;
    }else if (Browser.isOpera) {
      strExec = st[i].text;
    }else if ((navigator.appName == 'Netscape')) {
      strExec = st[i].textContent;
    } else {
      strExec = st[i].text;
    }
    try {
      eval(strExec.split("<!--").join("").split("-->").join(""));
    } catch(e) {}
  }
}

function evalScripts( text ){
   var scripts = [];
   var script_sources = text.split(/<script.*?>/);
   counter = 0;
   for (var i=1; i < script_sources.length; i++)
      scripts[counter++] = script_sources[i].split(/<\/script>/)[0];

   for (var i=0; i < counter; i++)
   	eval( scripts[i] );
}
curWidth=0;
curHeight = 0;
function addWindowResizeFunctions(){
	window.onresize = function() {
		afterResize();
	}
	window.onresizeend = function(){
		afterResize();
		Controller.fixModuleSizes();
	}
} 
function removeWindowResizeFunctions(){
	window.onresize = function(){}
	window.onresizeend = function(){}
}


function afterResize(){
	try{
		var resized = false;
		newHeight = Layouter.getActiveTab().el.dom.offsetHeight;
		newWidth = $id( PortletLoader.getAvailableTabId()+"_body1").offsetWidth;
		if(Controller.tabWidth != newWidth){
			resized = true;
			Controller.tabWidth = newWidth;
			if(browserVersion.isIE){
				var newWidth = document.documentElement.clientWidth;
				if( newWidth - curWidth !=0){
					curWidth = newWidth;
					resetXSizes();
	
				}
			}else{
				resetXSizes();
			}
		}
	
		if(newHeight != Controller.tabHeight){
		 	resized = true;
			if(Layouter.getActiveTab().mode == "max"){
				for( var i=0; i<PORTLETS.length; i++ ){
					if(PORTLETS[i] == null  || PORTLETS[i].mode != "max")continue;
					PORTLETS[i].portlet_C_DOMOBJ.style.height=PORTLETS[i].portlet_FRAME.offsetHeight - 20 + "px";
					break;
				}
			}
	
			if(browserVersion.isIE){
				var newHeight = document.documentElement.clientHeight;
				if( newHeight - curHeight !=0){
					curHeight = newHeight;
					resetXSizes();
				}
			}else{
				resetXSizes();
			}
			Controller.tabHeight = newHeight;
		}
		if (!resized){
			setTimeout(afterResize, 500);
		}else{
			Controller.fixModuleSizes();
			Controller.callModulesListener( "onPageResize", true );
		}
	}catch(ex){}
}

try{
	Form.makeKeyValue = function(form){		
	    var elements = Form.getElements($id(form));
	    var queryComponents = new Array();
		var inputType;
		var queryComponentKey;
	    for (var i = 0; i < elements.length; i++) {
	      var queryComponent = Form.Element.serialize(elements[i]);		  
	      if (queryComponent) {
				var index = queryComponent.indexOf("=");
				queryComponentKey = queryComponent.substr(0, index);
				if("checkbox" == elements[i].type){					
					if(queryComponents[queryComponentKey] == null){
						queryComponents[queryComponentKey] = new Array();
					}
					queryComponents[queryComponentKey][queryComponents[queryComponentKey].length] = queryComponent.substr(index+1);					
				} else {
		  	    	queryComponents[queryComponentKey] = queryComponent.substr(index+1);
				}
		  }
	    }

	    return queryComponents;
	}
}catch(ex){}



function resize(size){
 	if (navigator.appName=="Netscape") {
  		$id("tablewidth").width=window.innerWidth;
 	}
 	if (navigator.appName.indexOf("Microsoft")!=-1) {
  		$id("tablewidth").style.width=document.documentElement.clientWidth;
 	}
}

function sleep( msec){
	var currentdate = new Date();
	document.getElementById("log").innerHTML += currentdate + "<br />";
	currentdate = Math.round(currentdate.getTime());
	if( !sleep.started  ){ sleep.start = currentdate; sleep.started =  true; }
	if( sleep.start + msec > currentdate ){
		sleep( msec);
	}else{
		sleep.started = false;
	}
}
sleep.start = null;
sleep.started = false;


function encode(str){
	if (!str || str=="") return str;
	var tokens = str.split("/");
	var result = encodeURIComponent(tokens[0]);
	for(var i=1; i< tokens.length; ++i){
		result += "/" + encodeURIComponent(tokens[i]) ;
	}
	return result;
}
function decode(str){
	 var tokens = str.split("/");
	 var result = decodeURIComponent(tokens[0]);
	 for(var i=1; i< tokens.length; ++i){
	  result += "/" + decodeURIComponent(tokens[i]) ;
	 }
	 return result;
}
function isEmailValid(e) {
	var ok = "1234567890qwertyuiop[]asdfghjklzxcvbnm.+@-_QWERTYUIOPASDFGHJKLZXCVBNM";
	for(var i=0; i<e.length; i++){
		if (ok.indexOf(e.charAt(i))<0) {
			return false;
		}
	}
	if (document.images) {
		var re = /(@.*@)|(\.\.)|(^\.)|(^@)|(@$)|(\.$)|(@\.)/;
		var re_two = /^.+\@(\[?)[a-zA-Z0-9\-\.]+\.([a-zA-Z]{2,8}|[0-9]{1,3})(\]?)$/;
		if (!e.match(re) && e.match(re_two)) {
			return -1;
		}
	}
}
function  checkName(str){
	if(str.indexOf("/") == -1)
	return true;
	return false;
}
validateContact=function(first, second, email, phone, key, im, accountType){
 	     if(first=='' || second=='')	return Framework.Lang.Contact_Empty_FLName;
    	 if(!checkName(first) || !checkName(second))	return Framework.Lang.Contact_NotValid_FLName;
		
         var filter  = /^([a-zA-Z0-9_\.\-\+])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
         var phoneFilter = /^([\+])?([0-9])+$/;
         
         if(accountType == undefined || accountType =='Email')
       	 	if (!filter.test(email))  return Framework.Lang.Contact_notValidEmail;
  		 
  		 if(accountType == undefined || accountType =='SMS')
		 	if (phone != "" && !phoneFilter.test(phone))  return Framework.Lang.Contact_notValidPhone;
		 	
		 if(accountType == undefined || accountType =='IM')
		 	if(im.trim() == '')	return Framework.Lang.Contact_notValidIM;

         if(key != undefined && key.trim()=='')   return Framework.Lang.Contact_imageTextRequired;
	 
  		return "success";

}
var validateMail = function(first, second, email){
	 if(first=='' || second=='')
	 	return Framework.Lang.Contact_Empty_FLName;
     if(!checkName(first) || !checkName(second))
     	return Framework.Lang.Contact_NotValid_FLName;
	 var filter  = /^([a-zA-Z0-9_\.\-\+])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
     if (!filter.test(email))  return Framework.Lang.Contact_notValidEmail;
  	 return "success";
}
var validateIM = function(first, second, im){
	 if(first=='' || second=='')
	 	return Framework.Lang.Contact_Empty_FLName;
     if(!checkName(first) || !checkName(second))
     	return Framework.Lang.Contact_NotValid_FLName;
	 if(im.trim() == '')
	 	return Framework.Lang.Contact_notValidIM;
  	 return "success";
}
var validateTwitter = function(first, second, account){
	 if(first=='' || second=='')
	 	return Framework.Lang.Contact_Empty_FLName;
     if(!checkName(first) || !checkName(second))
     	return Framework.Lang.Contact_NotValid_FLName;
	 if(account.trim() == '')
	 	return Framework.Lang.Contact_notValidTwitter;
  	 return "success";
}
var validateSMS = function(first, second, phone){
	 if(first=='' || second=='')
	 	return Framework.Lang.Contact_Empty_FLName;
     if(!checkName(first) || !checkName(second))
     	return Framework.Lang.Contact_NotValid_FLName;
	 var phoneFilter = /^([\+])?([0-9])+$/;
	 if (phone != "" && !phoneFilter.test(phone))
	 	return Framework.Lang.Contact_notValidPhone;
  	 return "success";
}

var isNumeric = function(num){
	 var filter = /^([0-9])+$/;
	 if (num != "" && !filter.test(num))
	 	return false;
  	 return true;
}
Array.prototype.consistOf = function(compare, thisObj) {
    for ( var i=0, j=this.length; i < j;   i++ ) {
        if (this[i] == compare) {
            return true;
        }
    }
    return false;
};

Array.prototype.specialFields = function(field, thisObj) {
	var newAr = [];
    for ( var i = 0; i < this.length; i++ ) {
        newAr[newAr.length] = this[i][field];
    }
    return newAr;
};

Array.prototype.unique = function( b ) {
	 var a = [], i, l = this.length;
	 for( i=0; i<l; i++ ) {
	  if( a.indexOf( this[i], 0, b ) < 0 ) { a.push( this[i] ); }
	 }
	 return a;
};
Array.prototype.withoutArr = function(arr, thisObj) {
	var a = [];
    for ( var i=0; i < this.length;   i++ ) {
    	if (!arr.consistOf(this[i])) {
	       a.push( this[i] );
	    }
    }
    return a;
};
Array.prototype.intersect = function(arr, thisObj) {
	var a = [];
	for ( var i=0; i < this.length;   i++ ) {
    	if (arr.consistOf(this[i])) {
	       a.push( this[i] );
	    }
    }
    return a;
};

Array.prototype.exclude = function(arr) {
	var a = [];
	for ( var i=0; i < this.length;   i++ ) {
    	if (!arr.consistOf(this[i])) {
	       a.push( this[i] );
	    }
    }
    return a;
};
Array.prototype.indexOf = function(obj) {
	for ( var i=0; i < this.length; i++ ) {
    	if (this[i] == obj) {
	       return i;
	    }
    }
    return -1;
};
Array.prototype.removeDuplicate = function()
{
	// Here we remove duplicate values from first array
	var array4 = new Array;
	for(var i=0; i<this.length; i++) 
	{
	      var xx = true;
		for(var j=i+1; j<this.length; j++)
		{
			if(this[i] == this[j])
				xx = false;		
		}	
		if(xx == true)
			array4.push(this[i]);
	}
	return array4;
}

String.prototype.trim = function() { return this.replace(/^\s+|\s+$/, ''); };
String.prototype.ellipse = function(maxLength){
    if(this.length > maxLength){
        return this.substr(0, maxLength-3) + '...';
    }
    return this;
}
String.prototype.escapeHTML= function() {
    var div = document.createElement('div');
    var text = document.createTextNode(this);
    div.appendChild(text);
    return div.innerHTML;
};

String.prototype.unescapeHTML = function() {
    var div = document.createElement('div');
    div.innerHTML = this.stripTags();
    return div.childNodes[0].nodeValue;
};
String.prototype.stripTags=function() {
    return this.replace(/<\/?[^>]+>/gi, '');
};
String.prototype.replaceAll= function(s1, s2) {
 	return this.split(s1).join(s2)
};
String.prototype.makeNBSP = function() {
  	var thisCopy = "";
	for( var i=0; i<this.length; i++ )
		thisCopy += ( this.charAt(i) == " ")?"&nbsp;":this.charAt(i);
	return thisCopy;
};
String.prototype.htmlEncode = function() {
	return encodeURIComponent(this).replaceAll("'", "%27")
};
String.prototype.htmlDecode = function() {
	return decodeURIComponent(this).replaceAll("%27", "'");
};
cleanWhitespace = function(node){
	for (var x=0; x<node.childNodes.length; x++) {
		var child = node.childNodes[x];
		if ((child.nodeType == 3) && (!notspace.test(child.nodeValue)))	{
			node.removeChild(node.childNodes[x]);
			x--;
		}
		if(child.nodeType == 1) {
			Utils.cleanWhitespace(child);
		}
	}
}

function clone(obj,deep){
	var objectClone = new obj.constructor();
  	for (var property in obj)
    	if (!deep)
      		objectClone[property] = obj[property];
    	else if (typeof obj[property] == 'object')
      		objectClone[property] = clone(obj[property],deep);
    	else
      		objectClone[property] = obj[property];
  	return objectClone;
}
function getRawObject(obj) {
    var theObj;
    if (typeof obj == "string") {
        if (isW3C) {
            theObj = document.getElementById(obj);
        } else if (isIE4) {
            theObj = document.all(obj);
        } else if (isNN4) {
            theObj = seekLayer(document, obj);
        }
    } else {
        theObj = obj;
    }
    return theObj;
}

function getObjectWidth(obj)  {
    var elem = getRawObject(obj);
    var result = 0;
    if (elem.offsetWidth) {
            result = elem.offsetWidth;
    } else if (elem.clip && elem.clip.width) {
        result = elem.clip.width;
    } else if (elem.style && elem.style.pixelWidth) {
        result = elem.style.pixelWidth;
    }
    return parseInt(result);
}
function getObjectHeight(obj)  {
    var elem = getRawObject(obj);
    var result = 0;
    if (elem.offsetHeight) {
        result = elem.offsetHeight;
    } else if (elem.clip && elem.clip.height) {
        result = elem.clip.height;
    } else if (elem.style && elem.style.pixelHeight) {
        result = elem.style.pixelHeight;
    }
    return parseInt(result);
}
function removeNode_( obj ){
	var objecttodestroy;
	if( typeof(obj) == "string" )
		objecttodestroy = document.getElementById( obj );
	else
		objecttodestroy = obj;

	if( objecttodestroy == null )return;
	objecttodestroy.parentNode.removeChild(objecttodestroy);
}

function fixModule( id ){
	try{
		if(!PortletLoader.headersPermanent && Layouter.getActiveTab().mode != "max"){
			PortletLoader.getPortlet(id).hideHeaderIcons();
		}
	}catch(ex){}
}

function setCookie(aName, aValue, aLifetime) {
	 var now = new Date();
	 var expiry = new Date(now.getTime() + aLifetime*24*60*60*1000);
	 if ((aValue != null) && (aValue != ""))
	 document.cookie=aName + "=" + escape(aValue) + "; expires=" + expiry.toGMTString() + "; path=/";
	 return getCookie(aName) != null;
}

function getCookie(aName) {
	 var aStart, anEnd;
	 if (document.cookie) {
	  	aStart = document.cookie.indexOf(aName+"=");
	  	if (aStart < 0) return null;
	  	aStart = document.cookie.indexOf("=", aStart) + 1;
	  	anEnd = document.cookie.indexOf(";", aStart);
	  	if (anEnd < 0) anEnd = document.cookie.length;
	  	return unescape(document.cookie.substring(aStart, anEnd));
	 }
	 else return null;
}

function deleteCookie(aName) {
	 var now = new Date();
	 var expired = new Date(now.getTime() - 2*24*60*60*1000);
	 document.cookie=aName + "=null; expires=" + expired.toGMTString();
}

function statusColumnRenderer(val){
	var retString;
	var imgUrl;
	switch(val){
		case TEST_STATUS_OK_STRING:
			imgUrl="images/snapshot/state-ok.gif";
		break;
		case TEST_STATUS_NA_STRING:
			imgUrl="images/snapshot/state-NA.gif";
		break;
		case TEST_STATUS_NOK_STRING:
			imgUrl="images/snapshot/state-notok.gif";
		break;
	}
	retString="<img title='"+val+"' src='"+imgUrl+"'</img>";
	return retString;
}


function Timer(){
	this.obj = (arguments.length)?arguments[0]:window;
	return this;
}
Timer.prototype.setInterval = function(func, msec){
	var i = Timer.getNew();
	var t = Timer.buildCall(this.obj, i, arguments);
	Timer.set[i].timer = window.setInterval(t,msec);
	return i;
}
Timer.prototype.setTimeout = function(func, msec){
	var i = Timer.getNew();
	Timer.buildCall(this.obj, i, arguments);
	Timer.set[i].timer = window.setTimeout("Timer.callOnce("+i+");",msec);
	return i;
}
Timer.prototype.clearInterval = function(i){
	if(!Timer.set[i]) return;
	window.clearInterval(Timer.set[i].timer);
	Timer.set[i] = null;
}
Timer.prototype.clearTimeout = function(i){
	if(!Timer.set[i]) return;
	window.clearTimeout(Timer.set[i].timer);
	Timer.set[i] = null;
}
Timer.set = new Array();
Timer.buildCall = function(obj, i, args){
	var t = "";
	Timer.set[i] = new Array();
	if(obj != window){
		Timer.set[i].obj = obj;
		t = "Timer.set["+i+"].obj.";
	}
	t += args[0]+"(";
	if(args.length > 2){
			Timer.set[i][0] = args[2];
			t += "Timer.set["+i+"][0]";
			for(var j=1; (j+2)<args.length; j++){
				Timer.set[i][j] = args[j+2];
				t += ", Timer.set["+i+"]["+j+"]";
			}
	}
	t += ");";
	Timer.set[i].call = t;
	return t;
}
Timer.callOnce = function(i){
	if(!Timer.set[i]) return;
	eval(Timer.set[i].call);
	Timer.set[i] = null;
}
Timer.getNew = function(){
	var i = 0;
	while(Timer.set[i]) i++;
	return i;
}


var compare=function(first, second , type){
	if(type==SORT_TYPE_ASC)   return first<second;
	else if(type==SORT_TYPE_DESC)  return first>second;
}
var heapSort=function(numbers, col, type){
 	var i, temp;
  	for (i = parseInt(numbers.length / 2)-1; i >= 0; i--)
    	siftDown(numbers, i, numbers.length-1, col, type);

  	for (i = numbers.length-1; i >= 1; i--){
    	temp = numbers[0];
    	numbers[0] = numbers[i];
    	numbers[i] = temp;
    	siftDown(numbers, 0, i-1, col, type);
  	}
}

var siftDown=function(numbers, root,  bottom, col, type){
  	var done, maxChild, temp;

  	done = 0;
  	while ((root*2 <= bottom) && (done==0)){
    	if (root*2 == bottom)	maxChild = root * 2;
    	else if (!compare(numbers[root * 2][col] , numbers[root * 2 + 1][col], type)) maxChild = root * 2;
    	else	maxChild = root * 2 + 1;
    	if (compare(numbers[root][col], numbers[maxChild][col], type)){
      			temp = numbers[root];
      			numbers[root] = numbers[maxChild];
      			numbers[maxChild] = temp;
      			root = maxChild;
    	}else	done = 1;
  	}
}

var YAHOO = {};
YAHOO.util = {};
var CN = YAHOO.util.Connect;

function ankapFunction( val ){
	alert("aaaaaaaaa");
}



function $id() {
//  for (var i = 0; i < arguments.length; i++){
    var element = arguments[0];
    if (typeof element == 'string')
      element = document.getElementById(element);

	if( !!arguments[1] ){
	  try{
			var obj = element._ext_object;
	  		if( obj != null) element = obj;
	  }catch(ex){}
	}
//    elements.push(element);
//  }
  return element;

}
function changeTestTrendData(portletId){
	var value;
	try{
		value = $id('dataChange_'+ portletId, true).getValue();
	}catch(ex){
		value = $id('dataChange_'+ portletId).value;
	}
	var portlet = PortletLoader.getPortlet(portletId);
	portlet.object.changeDataTime(parseInt(value));
}
function getGridFlashNode( id, data, config, height ){
	var hasProductInstall = DetectFlashVer(6, 0, 65);
	var hasRequestedVersion = DetectFlashVer(requiredMajorVersion, requiredMinorVersion, requiredRevision);
	var wmodeAttribute = (Browser.isMacFirefox)? "" : "transparent";
	if(typeof height == 'undefined')
		height = "100%";
	else 
		height += "px";
	// Check to see if a player with Flash Product Install is available and the version does not meet the requirements for playback
	if ( hasProductInstall && !hasRequestedVersion ) {
		var MMPlayerType = (isIE == true) ? "ActiveX" : "PlugIn";
		var MMredirectURL = window.location;
	    document.title = document.title.slice(0, 47) + " - Flash Player Installation";
	    var MMdoctitle = document.title;
	
	return AC_FL_RunContent(
		"src", "playerProductInstall",
		"FlashVars", "MMredirectURL="+MMredirectURL+'&MMplayerType='+MMPlayerType+'&MMdoctitle='+MMdoctitle+"",
		"width", "100%",
		"height", height,
		"align", "middle",
		"id", id,
		"quality", "high",
		"bgcolor", "#869ca7",
		"name", id,
		"allowScriptAccess","samedomain",
		"wmode",wmodeAttribute,
		"type", "application/x-shockwave-flash",
		"pluginspage", "http://www.adobe.com/go/getflashplayer"
	);
} else if (hasRequestedVersion) {
	// if we've detected an acceptable version
	// embed the Flash Content SWF when all tests are passed
	
	return AC_FL_RunContent(
			"src", Framework.serverPath+"/grid9",
			"width", "100%",
			"height", height,
			"align", "middle",
			"id", id,
			"quality", "high",
			"bgcolor", "#869ca7",
			"name", id,
			"flashvars",'data=' + encode(data) + '&config='+ encode(config),
			"allowScriptAccess","samedomain",
			"wmode",wmodeAttribute,
			"type", "application/x-shockwave-flash",
			"pluginspage", "http://www.adobe.com/go/getflashplayer"
	);
	  } else {  // flash is too old or we can't detect the plugin
	    var alternateContent = 'This content requires the Adobe Flash Player. <a href=http://www.adobe.com/go/getflash/>Get Flash</a>';
	    return alternateContent;
	  }
}
function flashCheckboxCallback(functionName, elId, index, checked){
	var el=$id(elId);
	var selfNot=el.self;
	eval("selfNot."+functionName+"("+index+","+checked+")");
}
function flashCheckboxHeaderCallback(functionName,elId, index, checked){
	var el=$id(elId);
	var selfNot=el.self;
	eval("selfNot."+functionName+"("+index+","+checked+")");
}
function flashImageCallback(functionName, elId, index){
	var el=$id(elId);
	var selfNot = el.self;
	eval("selfNot." + functionName + "(" + index + ")");
}
function flashCellCallback(functionName, elId, index, cell){
	var el=$id(elId);
	var selfNot=el.self;
	eval("selfNot." + functionName + "(" + index + ",'" + cell + "')");
}

function toFlexJSONArrayString(arr) {
	var data_ = "[";
	var dataItem;

	for (var i=0; i<arr.length; i++ ){
		var item_ = arr[i];
		dataItem = "";
		dataItem += '{';
		for( var key in item_ )	{
			if( typeof(item_[key]) == "function" )continue;
			if( typeof(item_[key]) == "object" )
				dataItem += '"'+ key +'": '+ toFlexJSONObjectString(item_[key]) +',';
			else
				dataItem += '"'+ key +'": "'+ item_[key] +'",';

		}
		dataItem = dataItem.substr(0, dataItem.length-1);

		dataItem += '}';
		if( i != arr.length -1 )dataItem += ',';
		data_ += dataItem;
	}
	data_ += "]";
	return data_;
}

function  toFlexJSONObjectString(obj) {
	var data_ = "{";
	var dataItem;
	for (var key in obj ){
		if( typeof(obj[key]) == "function" )continue;
		data_ += '"'+ key +'": "'+ obj[key] +'",';
	}
	data_ = data_.substr(0, data_.length-1);
	data_ += '}';
	return data_;
}

function preloadimages(){
	var myimages=new Array();
	for (i=0;i<preloadimages.arguments.length;i++){
		myimages[i]=new Image();
		myimages[i].src=preloadimages.arguments[i];
	}
}


Utils.url_validation = function(theurl) {
     var tomatch= /http:\/\/[A-Za-z0-9\.-]{3,}\.[A-Za-z]{3}/
     if (tomatch.test(theurl)) {
             return true;
     } else {
           return false; 
     }
}
Utils.sort =  function(array, col, type){
	if (type == null) type = SORT_TYPE_ASC;
	for (var i=0; i < array.length-1; i++){
		index = i;
		for (var j=i;j<array.length;j++)
			if (col){
				if ( compare(array[index][col], array[j][col], type) ) index = j;
			}else{
				if ( compare(array[index], array[j], type) ) index = j;
			}
		var a = array[i];
		array[i] = array[index];
		array[index] = a;
	}
}
Utils.appendZero = function(str, length){
	var zeroStr = "";
	for(var i=0; i < length - str.length; i++){
		zeroStr += "0" 
	}
	zeroStr += str;
	return zeroStr;
}
Utils.getWindowSize = function(){
	var width = 0, height = 0;
 	if( typeof( window.innerWidth ) == 'number' ) {
  		width = window.innerWidth;
  		height = window.innerHeight;
	} else if( document.documentElement && (document.documentElement.clientWidth ||document.documentElement.clientHeight ) ) {
		width = document.documentElement.clientWidth;
		height = document.documentElement.clientHeight;
	} else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
	  	width = document.body.clientWidth;
	  	height = document.body.clientHeight;
 	}
 	return {"width": width, "height": height};
}
Utils.getObjectArrayLength = function(obj){
	var len = 0;
	for( var item in obj ){
		len++;
	}
	return len;
}

function hideCharts(){
	var embeds = document.getElementsByTagName("EMBED");
	for(var i = 0; i < embeds.length; i++){
		embeds[i].style.visibility = "hidden";
	}
}
function showCharts(){
	var embeds = document.getElementsByTagName("EMBED");
	for(var i = 0; i < embeds.length; i++){
		embeds[i].style.visibility = "visible";
	}
}
function showChartsForMsgDialog(){
	var arr = ["datagrid_TagCloud","datagrid_MysWindow"];
	var embeds = document.getElementsByTagName("EMBED");
	for(var i = 0; i < embeds.length; i++){
		for(var j = 0; j < arr.length; j++){
			if(arr[j] == embeds[i].id){
				embeds[i].style.visibility = "visible";
			}
		}
	}
	if($id("cloudWindowBody"))$id("cloudWindowBody").style.overflow = "visible";
}
function attachScriptTagFromPath(path){
	 var oHead = document.getElementsByTagName("head")[0];
	 var oScript = document.createElement('script');
	 oScript.setAttribute('src', path );
	 oScript.setAttribute('type', 'text/javascript');
	 oHead.appendChild(oScript);
	 return oScript;
}
function attachLinkTagFromPath(path){
	 var oHead = document.getElementsByTagName("head")[0];
	 var oLink = document.createElement('link');
	 oLink.setAttribute('href', path );
	 oLink.setAttribute('rel', 'stylesheet' );
	 oLink.setAttribute('type', 'text/css');
	 oHead.appendChild(oLink);
	 return oLink;
}
function removeSWFFromMemoryInIE(id) { 
 	        var obj = $id(id); 
 	        if (obj) { 
 	            for (var i in obj) { 
 	                if (typeof obj[i] == "function") { 
 	                    obj[i] = null; 
 	                } 
 	           } 
 	           obj.parentNode.removeChild(obj); 
 	        } 
} 

function compareDateHours(fromDate, toDate){ // date format 12:08:55
	var fromDateArr = fromDate.split(":");
	var toDateArr = toDate.split(":");
	
	var from = new Date();
	from.setHours(fromDateArr[0]);
	from.setMinutes(fromDateArr[1]);
	from.setSeconds(fromDateArr[2]);
	
	var to = new Date();
	to.setHours(toDateArr[0]);
	to.setMinutes(toDateArr[1]);
	to.setSeconds(toDateArr[2]);
	
	return from <= to;
}

var MONTHS_SHORT = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" ];

var getDateStr = function(date){
	if (date == null) return "";
	var hr = ''+(date.getHours()+100);
	var mn = ''+(date.getMinutes()+100);
	var sc = ''+(date.getSeconds()+100);
	var day = ''+(date.getDate()+100);
	var dateStr = day.substring(1,3)+" "+MONTHS_SHORT[date.getMonth()]+
				" "+hr.substring(1,3)+":"+mn.substring(1,3)+":"+sc.substring(1,3);
	return dateStr;
}

var getDateString = function(date){
	if (date == null) return "";
	var month = ''+(date.getMonth()+101);
	var day = ''+(date.getDate()+100);
	var dateStr = date.getFullYear()+"-"+month.substring(1,3)+"-"+day.substring(1,3);
	return dateStr;
}

function getDate (strDate) {
   var parsedDate = strDate.split("-");
   if (parsedDate.length != 3) return null;
   var day, month, year;
   year = parsedDate[0];
   month = parsedDate[1]-1;
   day = parsedDate[2];
   
   if (isNaN(month) || isNaN(year) || isNaN(day)){
   		return null;
   }else{
	   var objDate = new Date ();
	   objDate.setDate(day);
	   objDate.setMonth(month);
	   objDate.setYear(year);
	   return objDate;
   }
   
}

var weekInMsecods = 7*24*60*60*1000;
var getSpecialDaysInMonth = function(year, month, dayOfWeek){
	var dt = new Date();
	dt.setDate(1);
	dt.setYear(year);
	dt.setMonth(month);
	var days = [];
	while(dt.getMonth() == month){
		if (dt.getDay() == dayOfWeek){
			days[days.length] = dt.getDate();
		}
		dt.setDate(dt.getDate()+1);
	}
	return days;
}

Date.prototype.setDay = function(day){
	var incdec = day > this.getDay() ? 1 : -1;
	while(day != this.getDay()){
		this.setTime(this.getTime()+incdec*24*60*60*1000);
	}
}

Date.prototype.getPreviousMonday = function(){
	this.setDay(1);
	this.setTime(this.getTime() - weekInMsecods);
	return this;
}

Date.prototype.addDays = function(days){
	this.setTime(this.getTime() + days*24*60*60*1000);
	return this;
}

Date.prototype.extractDays = function(days){
	this.setTime(this.getTime() - days*24*60*60*1000);
	return this;
}


var dateDif = function(date1, date2){
	if (date1 == null || date2 == null) return "";
	var sec = (date2.getTime()-date1.getTime())/1000;
	var h = parseInt(sec/60/60);
	var m = parseInt((sec-h*60*60)/60);
	var s = sec - h*60*60 - m*60;
	var str = (h<10 ? "0"+h : h)+":"+
		   (m<10 ? "0"+m : m)+":"+
		   (s<10 ? "0"+s : s);
	return str;
}
 Platform= {
	LINUX_32:"32",
	LINUX_32_:"linux32",
	LINUX_64:"64",
	LINUX_64_:"linux64",
	WINDOWS_32:"win32",
	WINDOWS_64:"win64",
	SUN_32:"Sun8632",
	SUN_64:"Sun8664",
	SPARC_32:"SunSparc32",
	SPARC_64:"SunSparc64",
	
	isLinux32:function(platform){
		return Platform.LINUX_32==(platform) || Platform.LINUX_32_==(platform);
	},
	isLinux64:function(platform){
		return Platform.LINUX_64==(platform) || Platform.LINUX_64_==(platform);
	},
	isWindows32:function(platform){
		return Platform.WINDOWS_32==(platform);
	},
	isWindows64:function(platform){
		return Platform.WINDOWS_64==(platform);
	},
	isSun32:function(platform){
		return Platform.SUN_32==(platform);
	},
	isSun64:function(platform){
		return Platform.SUN_64==(platform);
	},
	isSparc32:function(platform){
		return Platform.SPARC_32==(platform);
	},
	isSparc64:function(platform){
		return Platform.SPARC_64==(platform);
	},
	isWindows:function(platform){
		return Platform.isWindows32(platform) || Platform.isWindows64(platform);
	},
	isLinux:function(platform){
		return Platform.isLinux32(platform) || Platform.isLinux64(platform); 
	},
	isSolaris:function(platform){
		return Platform.isSparc32(platform) || Platform.isSparc64(platform) || Platform.isSun32(platform) || Platform.isSun64(platform);
	},
	
	isFreeBSD64:function(platform){
		return Platform.FREE_BSD_X64==platform;
	},
	
	isFreeBSD32:function(platform){
		return Platform.FREE_BSD_X86==platform;
	},
	
	isFreeBSD:function(platform){
		return Platform.isFreeBSD32(platform) || Platform.isFreeBSD64(platform);
	},
	
	getPlatformString: function(platform){
		if (Platform.isWindows(platform)){
			return "Windows";
		}
		else if (Platform.isLinux(platform)){
			return "Linux";
		}
		else if(Platform.isSolaris(platform)){
			return "OpenSolaris";
		}
		else if(Platform.isFreeBSD(platform)){
			return "FreeBSD";
		}
	}

}

var roundToDecimals = function(v, decimals, noCommas) { 
       if (decimals == null)
           decimals = 2;
       var x = Math.pow(10, decimals);
       var s = String(Math.round(v * x) / x); 
       var p = s.indexOf('.');
       if (p < 0) {
           p = s.length;
           s += '.';
       }
       for (var i = s.length - p - 1; i < decimals; i++)
           s += '0';
       if (noCommas == true) // Treats null as false.
           return s;
       var arr    = s.replace('-', '').split('.');
       var result = [];
       var first  = true;
       while (arr[0].length > 0) { // LHS of decimal point.
           if (!first)
               result.unshift(',');
           result.unshift(arr[0].slice(-3));
           arr[0] = arr[0].slice(0, -3);
           first = false;
       }
       if (decimals > 0) {
           result.push('.');
           var first = true;
           while (arr[1].length > 0) { // RHS of decimal point.
               if (!first)
                   result.push(',');
               result.push(arr[1].slice(0, 3));
               arr[1] = arr[1].slice(3);
               first = false;
           }
       }
       if (v < 0)
           return '-' + result.join('');
       return result.join('');
   }

   
function typeOf(value) {
    var s = typeof value;
    if (s === 'object') {
        if (value) {
            if (value instanceof Array) {
                s = 'array';
            }
        } else {
            s = 'null';
        }
    }
    return s;
}

String.prototype.quote = function () {
    var c, i, l = this.length, o = '"';
    for (i = 0; i < l; i += 1) {
        c = this.charAt(i);
        if (c >= ' ') {
            if (c === '\\' || c === '"') {
                o += '\\';
            }
            o += c;
        } else {
            switch (c) {
            case '\b':
                o += '\\b';
                break;
            case '\f':
                o += '\\f';
                break;
            case '\n':
                o += '\\n';
                break;
            case '\r':
                o += '\\r';
                break;
            case '\t':
                o += '\\t';
                break;
            default:
                c = c.charCodeAt();
                o += '\\u00' + Math.floor(c / 16).toString(16) +
                    (c % 16).toString(16);
            }
        }
    }
    return o + '"';
};


Object.exclude = function(obj, key) {
	var a = {};
	for ( var prop in obj ) {
    	if (prop != key) {
	       a[prop] = obj[prop];
	    }
    }
    return a;
};

Object.toJSON = function(object) {
    var type = typeOf(object);
    switch (type) {
      case 'undefined':
      case 'function':
      case 'unknown': return;
      case 'boolean': 
      case 'number': return object.toString();
      case 'string': return object.quote();
    }

    if (object === null) return 'null';

	if (type == 'array'){
		var results = [];
	    for (var property in object) {
	      var value = Object.toJSON(object[property]);
	      if (typeof value != "undefined")
	        results.push(value);
	    }
	
	    return '[' + results.join(', ') + ']';
	    
	}else{
	    var results = [];
	    for (var property in object) {
	      var value = Object.toJSON(object[property]);
	      if (typeof value != "undefined")
	        results.push(property.toString() + ': ' + value);
	    }
	
	    return '{' + results.join(', ') + '}';
    }
}

function getSelectedRadioByID(elId){
	var elements = $id(elId);
	if(elements.constructor === Array){
		for(var i = 0; i < elements.length; i++){
			if(elements[i].checked) return elements[i];
		}
	}else{
		return elements;
	}
	return null;
	
}
var mailfilter  = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
var numberFilter = /^[0-9]{1,}$/;
var oIdFilter = /^.*\.([a-zA-Z0-9]+)$/;

var validateElements = function(inputs){
	for(var i=0; i<inputs.length; i++){
		var value = inputs[i].value.trim();
		var type = inputs[i].getAttribute("dataType");
		if (value == "") {
			if (inputs[i].getAttribute("required") == "true" ||
				inputs[i].getAttribute("required") == true)
				return Framework.Lang.fillInRequiredFields;
		}else if ((type == "num" && !numberFilter.test(value)) ||
				  (type == "mail" && !mailfilter.test(value))
				 
				  ){
			return Framework.Lang.notValid + " "+inputs[i].getAttribute("label");
		}
	}
	return "success";
}

var validateParam = function(param, value){
	if (value == ""){
		if (param.required == true)
			return Framework.Lang.fillInRequiredFields;
	}
	else if ((param.dataType == "num" && !numberFilter.test(value)) ||
			 (param.dataType == "mail" && !mailfilter.test(value)) ||
			 (param.dataType == "oid" && !oIdFilter.test(value))
			 ){
		return Framework.Lang.notValid + " "+param.label;
	}
	return "success";
}

var getAddHTML = function(moduleName,moduleParams, rowName, hide){
	var str = "";
	for (var key in moduleParams){
		var param = moduleParams[key];
		
		if (param.hidden == true || param.active == false ||
			param.add == false || key == "agentKey" || key == "name") continue;
		var elem = "";
		if (param.uiElement == "select"){
			var onchange = "";
			if (param.onchange){
				onchange="onchange='"+param.onchange.callback+"(\""+param.onchange.param+"\")'";
			}
			elem = "<select "+onchange+" name='"+key+"_"+moduleName+"'"+(param.multi?" MULTIPLE ":"")+(param.size?" size="+param.size:"")+" style='width:"+INPUT_WIDTH+"'>";
			for(var j=0;j<param.valueList.length;j++){
				var val, label, 
					valObject = param.valueList[j];
				if (valObject.label){
					val = valObject.value;
					label = valObject.label;
				} else if (valObject.value){
					val = label = valObject.value;
				} else {
					val = label = valObject;
				}
				elem += "<option value='"+val+"'>"+label+"</option>";
			}
			elem += "</select>";
		}else if (param.uiElement == "input"){
			var val = param.defaultValue ? 'value="'+param.defaultValue+'"' : "";
			var vtype = param.dataType == "num" ? 'vtype=num' : "";
			var inputType = param.inputType ? 'type='+param.inputType : "";
			var browseImg='';
			
			if(param.browse){
				browseImg='<img class="browseImg" onclick="'+param.browse.callback+'" src="images/browse.png" />'
			}
			elem = '<input required="'+param.required+'" dataType="'+param.dataType+'" '+val+' '+vtype+' ' + inputType +' name="'+key+"_"+moduleName+'" style="width:'+INPUT_WIDTH+'" />'+browseImg;
		}
		str += '<tr name="'+rowName+'" '+(hide ? 'style="display:none;"' : "")+'>'+
					'<td colspan=2 class="formLabel">' + param.label + ':</td>'+
					'<td>'+elem+'</td>'+
					
					'<td>'+(param.required == true ? "*" : "")+'</td>'+
				'</tr>';
	}
	return str;
}

function snmpVersionChanged(moduleName){
	var version = DialogWindow.getFormData()["version_"+moduleName];
	var form = DialogWindow.getFormObject();
	var config = Framework.Modules[moduleName+"Widget"].moduleParams;
	for (param in config){
		var elem = form[param+"_"+moduleName];
		if (elem){
			var show = config[param].versions.consistOf(version);
			parentElement(elem, "tr").style.display = show ? "" : "none";
		}
	}
}

function parentElement(obj, parentType){
	var par = obj.parentNode;
	parentType = parentType.toLowerCase();
	var ind = 0;
	while (par.tagName.toLowerCase() != parentType && ind<1000){
		par = par.parentNode;
		ind++;
	}
	return ind<1000 ? par : null;
}

function loadScript(url, callback){

    var script = document.createElement("script")
    script.type = "text/javascript";

    if (script.readyState){  //IE
        script.onreadystatechange = function(){
            if (script.readyState == "loaded" ||
                    script.readyState == "complete"){
                script.onreadystatechange = null;
                callback();
            }
        };
    } else {  //Others
        script.onload = function(){
            callback();
        };
    }

    script.src = url;
    document.getElementsByTagName("head")[0].appendChild(script);
}
////////////////////////////////////////////////////////////JQUERY//////////////////////////////
var Tree = function(){
	this.addTree=function(cont){
		$(cont).treeview({
		control: "#treecontrol",
		persist: "cookie",
		cookieId: "treeview-black"
	});
	}
	
	this.addLazyLoadingTree=function(cont,url){
		$(cont).treeview({
		url: url,
		persist: "cookie",
		cookieId: "treeview-black"
	});
	}
	
	}



function getQueryString(params){
	var data = "";
	for (var key in params){
		data += encodeURIComponent(key)+"="+encodeURIComponent(params[key])+"&";
	}
	data = data.substr(0, data.length-1);
	return data;
}
//////////////////////////////////////////////////////////////////////////////////////////////

var getPermissionsContent = function( extraId, permsToCheck ){

	var permissions = [
				{
					title: Framework.Lang.monitorsList.ExternalMonitors,
					perms: [
						{ text: Framework.Lang.permissions.addRemove,       	id: "49", key:  "R_manage Tests"  },
						{ text: Framework.Lang.permissions.activateSuspend, 	id: "37", key:  "R_suspend_resume test"  },
						{ text: Framework.Lang.permissions.manageReports,   	id: "40", key:  "R_manage Reports" },
						{ text: Framework.Lang.permissions.manageNotifications, id: "50", key:  "R_notification test"  },
						{ text: Framework.Lang.permissions.manageMaintenance, 	id: "38", key:  "R_maintenance test" },
						{ text: Framework.Lang.permissions.manageContacts, 	id: "57", key:  "R_manage Notifications" } 
					]	
				},
				{
					title: Framework.Lang.monitorsList.InternalMonitors,
					perms: [
						{ text: Framework.Lang.permissions.addRemove, 			id: "51", key:  "R_manage Agents"  },
						{ text: Framework.Lang.permissions.manageReports, 		id: "52", key:  "R_manage AgentReports" },
						{ text: Framework.Lang.permissions.manageNotifications, id: "53", key:  "R_notification agent" }
					]	
				},	
				{
					title: Framework.Lang.transactions,
					perms: [
						{ text: Framework.Lang.permissions.addRemove, 			id: "54", key:  "R_manage Transactions"  },
						{ text: Framework.Lang.permissions.manageReports, 		id: "55", key:  "R_manage TransactionReports" },
						{ text: Framework.Lang.permissions.manageNotifications, id: "56", key:  "R_notification transaction" }
					]	
				}	
			];
				
	var extraPermissionsContent = "";
	var extraPlan = false;
	for(var i = 0; i < permissions.length; i++){
		extraPermissionsContent += "<fieldset style='padding:2px;margin:5px'><legend> " + permissions[i].title + "</legend>";
		var perms = permissions[i].perms;
		for(var j = 0; j < perms.length; j++)
			extraPermissionsContent += "<input disabledSpecString " + ( permsToCheck != null && permsToCheck[perms[j].key] && (extraPlan=true) ? 'checked' : '' ) + " type='checkbox' permId='" + perms[j].id + "'/> " + perms[j].text + "<br>";				
		extraPermissionsContent += "</fieldset>";
	}
	
	extraPermissionsContent = extraPermissionsContent.replaceAll("disabledSpecString",(!extraPlan? "disabled" : ""));
	var content = '';
	content = "<table width='" + ( isIE ? 97 : 100 ) + "%' class='text' cellspacing=4 id='" + extraId + "'><tbody>"+	
					"<tr>"+
						"<td style='padding-left:16px'><span style='width:7px'></span><input " + ( !extraPlan ? "checked" : "" ) + " onchange='for(var i = 2; i <= 13; i++){$id(\"" + extraId + "\").getElementsByTagName(\"input\")[i].changeDisabled(true);}'  type='radio' name='" + extraId + "'/> " + Framework.Lang.permissions.readonly + "<br></td>"+
					"</tr>"+
					"<tr>"+
						"<td><fieldset><legend><input " + ( extraPlan ? "checked" : "" ) + " onchange='for(var i = 2; i <= 13; i++){$id(\"" + extraId + "\").getElementsByTagName(\"input\")[i].changeDisabled(false);}' type='radio' name='" + extraId + "'/> " + Framework.Lang.permissions.extraPermissions + "</legend>";
	
	content += extraPermissionsContent + "</fieldset></td></tr></tbody></table>";
	return content;
}


/////////////////////////////////   security       /////////////////
//Paul Tero, July 2001
//http://www.tero.co.uk/des/
//
//Optimised for performance with large blocks by Michael Hayworth, November 2001
//http://www.netdealing.com
//
//THIS SOFTWARE IS PROVIDED "AS IS" AND
//ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
//IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
//ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
//FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
//DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
//OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
//HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
//LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
//OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
//SUCH DAMAGE.

//des
//this takes the key, the message, and whether to encrypt or decrypt
function des (key, message, encrypt, mode, iv, padding) {
  //declaring this locally speeds things up a bit
  var spfunction1 = new Array (0x1010400,0,0x10000,0x1010404,0x1010004,0x10404,0x4,0x10000,0x400,0x1010400,0x1010404,0x400,0x1000404,0x1010004,0x1000000,0x4,0x404,0x1000400,0x1000400,0x10400,0x10400,0x1010000,0x1010000,0x1000404,0x10004,0x1000004,0x1000004,0x10004,0,0x404,0x10404,0x1000000,0x10000,0x1010404,0x4,0x1010000,0x1010400,0x1000000,0x1000000,0x400,0x1010004,0x10000,0x10400,0x1000004,0x400,0x4,0x1000404,0x10404,0x1010404,0x10004,0x1010000,0x1000404,0x1000004,0x404,0x10404,0x1010400,0x404,0x1000400,0x1000400,0,0x10004,0x10400,0,0x1010004);
  var spfunction2 = new Array (-0x7fef7fe0,-0x7fff8000,0x8000,0x108020,0x100000,0x20,-0x7fefffe0,-0x7fff7fe0,-0x7fffffe0,-0x7fef7fe0,-0x7fef8000,-0x80000000,-0x7fff8000,0x100000,0x20,-0x7fefffe0,0x108000,0x100020,-0x7fff7fe0,0,-0x80000000,0x8000,0x108020,-0x7ff00000,0x100020,-0x7fffffe0,0,0x108000,0x8020,-0x7fef8000,-0x7ff00000,0x8020,0,0x108020,-0x7fefffe0,0x100000,-0x7fff7fe0,-0x7ff00000,-0x7fef8000,0x8000,-0x7ff00000,-0x7fff8000,0x20,-0x7fef7fe0,0x108020,0x20,0x8000,-0x80000000,0x8020,-0x7fef8000,0x100000,-0x7fffffe0,0x100020,-0x7fff7fe0,-0x7fffffe0,0x100020,0x108000,0,-0x7fff8000,0x8020,-0x80000000,-0x7fefffe0,-0x7fef7fe0,0x108000);
  var spfunction3 = new Array (0x208,0x8020200,0,0x8020008,0x8000200,0,0x20208,0x8000200,0x20008,0x8000008,0x8000008,0x20000,0x8020208,0x20008,0x8020000,0x208,0x8000000,0x8,0x8020200,0x200,0x20200,0x8020000,0x8020008,0x20208,0x8000208,0x20200,0x20000,0x8000208,0x8,0x8020208,0x200,0x8000000,0x8020200,0x8000000,0x20008,0x208,0x20000,0x8020200,0x8000200,0,0x200,0x20008,0x8020208,0x8000200,0x8000008,0x200,0,0x8020008,0x8000208,0x20000,0x8000000,0x8020208,0x8,0x20208,0x20200,0x8000008,0x8020000,0x8000208,0x208,0x8020000,0x20208,0x8,0x8020008,0x20200);
  var spfunction4 = new Array (0x802001,0x2081,0x2081,0x80,0x802080,0x800081,0x800001,0x2001,0,0x802000,0x802000,0x802081,0x81,0,0x800080,0x800001,0x1,0x2000,0x800000,0x802001,0x80,0x800000,0x2001,0x2080,0x800081,0x1,0x2080,0x800080,0x2000,0x802080,0x802081,0x81,0x800080,0x800001,0x802000,0x802081,0x81,0,0,0x802000,0x2080,0x800080,0x800081,0x1,0x802001,0x2081,0x2081,0x80,0x802081,0x81,0x1,0x2000,0x800001,0x2001,0x802080,0x800081,0x2001,0x2080,0x800000,0x802001,0x80,0x800000,0x2000,0x802080);
  var spfunction5 = new Array (0x100,0x2080100,0x2080000,0x42000100,0x80000,0x100,0x40000000,0x2080000,0x40080100,0x80000,0x2000100,0x40080100,0x42000100,0x42080000,0x80100,0x40000000,0x2000000,0x40080000,0x40080000,0,0x40000100,0x42080100,0x42080100,0x2000100,0x42080000,0x40000100,0,0x42000000,0x2080100,0x2000000,0x42000000,0x80100,0x80000,0x42000100,0x100,0x2000000,0x40000000,0x2080000,0x42000100,0x40080100,0x2000100,0x40000000,0x42080000,0x2080100,0x40080100,0x100,0x2000000,0x42080000,0x42080100,0x80100,0x42000000,0x42080100,0x2080000,0,0x40080000,0x42000000,0x80100,0x2000100,0x40000100,0x80000,0,0x40080000,0x2080100,0x40000100);
  var spfunction6 = new Array (0x20000010,0x20400000,0x4000,0x20404010,0x20400000,0x10,0x20404010,0x400000,0x20004000,0x404010,0x400000,0x20000010,0x400010,0x20004000,0x20000000,0x4010,0,0x400010,0x20004010,0x4000,0x404000,0x20004010,0x10,0x20400010,0x20400010,0,0x404010,0x20404000,0x4010,0x404000,0x20404000,0x20000000,0x20004000,0x10,0x20400010,0x404000,0x20404010,0x400000,0x4010,0x20000010,0x400000,0x20004000,0x20000000,0x4010,0x20000010,0x20404010,0x404000,0x20400000,0x404010,0x20404000,0,0x20400010,0x10,0x4000,0x20400000,0x404010,0x4000,0x400010,0x20004010,0,0x20404000,0x20000000,0x400010,0x20004010);
  var spfunction7 = new Array (0x200000,0x4200002,0x4000802,0,0x800,0x4000802,0x200802,0x4200800,0x4200802,0x200000,0,0x4000002,0x2,0x4000000,0x4200002,0x802,0x4000800,0x200802,0x200002,0x4000800,0x4000002,0x4200000,0x4200800,0x200002,0x4200000,0x800,0x802,0x4200802,0x200800,0x2,0x4000000,0x200800,0x4000000,0x200800,0x200000,0x4000802,0x4000802,0x4200002,0x4200002,0x2,0x200002,0x4000000,0x4000800,0x200000,0x4200800,0x802,0x200802,0x4200800,0x802,0x4000002,0x4200802,0x4200000,0x200800,0,0x2,0x4200802,0,0x200802,0x4200000,0x800,0x4000002,0x4000800,0x800,0x200002);
  var spfunction8 = new Array (0x10001040,0x1000,0x40000,0x10041040,0x10000000,0x10001040,0x40,0x10000000,0x40040,0x10040000,0x10041040,0x41000,0x10041000,0x41040,0x1000,0x40,0x10040000,0x10000040,0x10001000,0x1040,0x41000,0x40040,0x10040040,0x10041000,0x1040,0,0,0x10040040,0x10000040,0x10001000,0x41040,0x40000,0x41040,0x40000,0x10041000,0x1000,0x40,0x10040040,0x1000,0x41040,0x10001000,0x40,0x10000040,0x10040000,0x10040040,0x10000000,0x40000,0x10001040,0,0x10041040,0x40040,0x10000040,0x10040000,0x10001000,0x10001040,0,0x10041040,0x41000,0x41000,0x1040,0x1040,0x40040,0x10000000,0x10041000);

  //create the 16 or 48 subkeys we will need
  var keys = des_createKeys (key);
  var m=0, i, j, temp, temp2, right1, right2, left, right, looping;
  var cbcleft, cbcleft2, cbcright, cbcright2
  var endloop, loopinc;
  var len = message.length;
  var chunk = 0;
  //set up the loops for single and triple des
  var iterations = keys.length == 32 ? 3 : 9; //single or triple des
  if (iterations == 3) {looping = encrypt ? new Array (0, 32, 2) : new Array (30, -2, -2);}
  else {looping = encrypt ? new Array (0, 32, 2, 62, 30, -2, 64, 96, 2) : new Array (94, 62, -2, 32, 64, 2, 30, -2, -2);}

  //pad the message depending on the padding parameter
  if (padding == 2) message += "        "; //pad the message with spaces
  else if (padding == 1) {temp = 8-(len%8); message += String.fromCharCode (temp,temp,temp,temp,temp,temp,temp,temp); if (temp==8) len+=8;} //PKCS7 padding
  else if (!padding) message += "\0\0\0\0\0\0\0\0"; //pad the message out with null bytes

  //store the result here
  result = "";
  tempresult = "";

  if (mode == 1) { //CBC mode
    cbcleft = (iv.charCodeAt(m++) << 24) | (iv.charCodeAt(m++) << 16) | (iv.charCodeAt(m++) << 8) | iv.charCodeAt(m++);
    cbcright = (iv.charCodeAt(m++) << 24) | (iv.charCodeAt(m++) << 16) | (iv.charCodeAt(m++) << 8) | iv.charCodeAt(m++);
    m=0;
  }

  //loop through each 64 bit chunk of the message
  while (m < len) {
    left = (message.charCodeAt(m++) << 24) | (message.charCodeAt(m++) << 16) | (message.charCodeAt(m++) << 8) | message.charCodeAt(m++);
    right = (message.charCodeAt(m++) << 24) | (message.charCodeAt(m++) << 16) | (message.charCodeAt(m++) << 8) | message.charCodeAt(m++);

    //for Cipher Block Chaining mode, xor the message with the previous result
    if (mode == 1) {if (encrypt) {left ^= cbcleft; right ^= cbcright;} else {cbcleft2 = cbcleft; cbcright2 = cbcright; cbcleft = left; cbcright = right;}}

    //first each 64 but chunk of the message must be permuted according to IP
    temp = ((left >>> 4) ^ right) & 0x0f0f0f0f; right ^= temp; left ^= (temp << 4);
    temp = ((left >>> 16) ^ right) & 0x0000ffff; right ^= temp; left ^= (temp << 16);
    temp = ((right >>> 2) ^ left) & 0x33333333; left ^= temp; right ^= (temp << 2);
    temp = ((right >>> 8) ^ left) & 0x00ff00ff; left ^= temp; right ^= (temp << 8);
    temp = ((left >>> 1) ^ right) & 0x55555555; right ^= temp; left ^= (temp << 1);

    left = ((left << 1) | (left >>> 31)); 
    right = ((right << 1) | (right >>> 31)); 

    //do this either 1 or 3 times for each chunk of the message
    for (j=0; j<iterations; j+=3) {
      endloop = looping[j+1];
      loopinc = looping[j+2];
      //now go through and perform the encryption or decryption  
      for (i=looping[j]; i!=endloop; i+=loopinc) { //for efficiency
        right1 = right ^ keys[i]; 
        right2 = ((right >>> 4) | (right << 28)) ^ keys[i+1];
        //the result is attained by passing these bytes through the S selection functions
        temp = left;
        left = right;
        right = temp ^ (spfunction2[(right1 >>> 24) & 0x3f] | spfunction4[(right1 >>> 16) & 0x3f]
              | spfunction6[(right1 >>>  8) & 0x3f] | spfunction8[right1 & 0x3f]
              | spfunction1[(right2 >>> 24) & 0x3f] | spfunction3[(right2 >>> 16) & 0x3f]
              | spfunction5[(right2 >>>  8) & 0x3f] | spfunction7[right2 & 0x3f]);
      }
      temp = left; left = right; right = temp; //unreverse left and right
    } //for either 1 or 3 iterations

    //move then each one bit to the right
    left = ((left >>> 1) | (left << 31)); 
    right = ((right >>> 1) | (right << 31)); 

    //now perform IP-1, which is IP in the opposite direction
    temp = ((left >>> 1) ^ right) & 0x55555555; right ^= temp; left ^= (temp << 1);
    temp = ((right >>> 8) ^ left) & 0x00ff00ff; left ^= temp; right ^= (temp << 8);
    temp = ((right >>> 2) ^ left) & 0x33333333; left ^= temp; right ^= (temp << 2);
    temp = ((left >>> 16) ^ right) & 0x0000ffff; right ^= temp; left ^= (temp << 16);
    temp = ((left >>> 4) ^ right) & 0x0f0f0f0f; right ^= temp; left ^= (temp << 4);

    //for Cipher Block Chaining mode, xor the message with the previous result
    if (mode == 1) {if (encrypt) {cbcleft = left; cbcright = right;} else {left ^= cbcleft2; right ^= cbcright2;}}
    tempresult += String.fromCharCode ((left>>>24), ((left>>>16) & 0xff), ((left>>>8) & 0xff), (left & 0xff), (right>>>24), ((right>>>16) & 0xff), ((right>>>8) & 0xff), (right & 0xff));

    chunk += 8;
    if (chunk == 512) {result += tempresult; tempresult = ""; chunk = 0;}
  } //for every 8 characters, or 64 bits in the message

  //return the result as an array
  var encStr = stringToHex(result + tempresult);
  return encStr;
} //end of des



//des_createKeys
//this takes as input a 64 bit key (even though only 56 bits are used)
//as an array of 2 integers, and returns 16 48 bit keys
function des_createKeys (key) {
  //declaring this locally speeds things up a bit
  pc2bytes0  = new Array (0,0x4,0x20000000,0x20000004,0x10000,0x10004,0x20010000,0x20010004,0x200,0x204,0x20000200,0x20000204,0x10200,0x10204,0x20010200,0x20010204);
  pc2bytes1  = new Array (0,0x1,0x100000,0x100001,0x4000000,0x4000001,0x4100000,0x4100001,0x100,0x101,0x100100,0x100101,0x4000100,0x4000101,0x4100100,0x4100101);
  pc2bytes2  = new Array (0,0x8,0x800,0x808,0x1000000,0x1000008,0x1000800,0x1000808,0,0x8,0x800,0x808,0x1000000,0x1000008,0x1000800,0x1000808);
  pc2bytes3  = new Array (0,0x200000,0x8000000,0x8200000,0x2000,0x202000,0x8002000,0x8202000,0x20000,0x220000,0x8020000,0x8220000,0x22000,0x222000,0x8022000,0x8222000);
  pc2bytes4  = new Array (0,0x40000,0x10,0x40010,0,0x40000,0x10,0x40010,0x1000,0x41000,0x1010,0x41010,0x1000,0x41000,0x1010,0x41010);
  pc2bytes5  = new Array (0,0x400,0x20,0x420,0,0x400,0x20,0x420,0x2000000,0x2000400,0x2000020,0x2000420,0x2000000,0x2000400,0x2000020,0x2000420);
  pc2bytes6  = new Array (0,0x10000000,0x80000,0x10080000,0x2,0x10000002,0x80002,0x10080002,0,0x10000000,0x80000,0x10080000,0x2,0x10000002,0x80002,0x10080002);
  pc2bytes7  = new Array (0,0x10000,0x800,0x10800,0x20000000,0x20010000,0x20000800,0x20010800,0x20000,0x30000,0x20800,0x30800,0x20020000,0x20030000,0x20020800,0x20030800);
  pc2bytes8  = new Array (0,0x40000,0,0x40000,0x2,0x40002,0x2,0x40002,0x2000000,0x2040000,0x2000000,0x2040000,0x2000002,0x2040002,0x2000002,0x2040002);
  pc2bytes9  = new Array (0,0x10000000,0x8,0x10000008,0,0x10000000,0x8,0x10000008,0x400,0x10000400,0x408,0x10000408,0x400,0x10000400,0x408,0x10000408);
  pc2bytes10 = new Array (0,0x20,0,0x20,0x100000,0x100020,0x100000,0x100020,0x2000,0x2020,0x2000,0x2020,0x102000,0x102020,0x102000,0x102020);
  pc2bytes11 = new Array (0,0x1000000,0x200,0x1000200,0x200000,0x1200000,0x200200,0x1200200,0x4000000,0x5000000,0x4000200,0x5000200,0x4200000,0x5200000,0x4200200,0x5200200);
  pc2bytes12 = new Array (0,0x1000,0x8000000,0x8001000,0x80000,0x81000,0x8080000,0x8081000,0x10,0x1010,0x8000010,0x8001010,0x80010,0x81010,0x8080010,0x8081010);
  pc2bytes13 = new Array (0,0x4,0x100,0x104,0,0x4,0x100,0x104,0x1,0x5,0x101,0x105,0x1,0x5,0x101,0x105);

  //how many iterations (1 for des, 3 for triple des)
  var iterations = key.length > 8 ? 3 : 1; //changed by Paul 16/6/2007 to use Triple DES for 9+ byte keys
  //stores the return keys
  var keys = new Array (32 * iterations);
  //now define the left shifts which need to be done
  var shifts = new Array (0, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0);
  //other variables
  var lefttemp, righttemp, m=0, n=0, temp;

  for (var j=0; j<iterations; j++) { //either 1 or 3 iterations
    left = (key.charCodeAt(m++) << 24) | (key.charCodeAt(m++) << 16) | (key.charCodeAt(m++) << 8) | key.charCodeAt(m++);
    right = (key.charCodeAt(m++) << 24) | (key.charCodeAt(m++) << 16) | (key.charCodeAt(m++) << 8) | key.charCodeAt(m++);

    temp = ((left >>> 4) ^ right) & 0x0f0f0f0f; right ^= temp; left ^= (temp << 4);
    temp = ((right >>> -16) ^ left) & 0x0000ffff; left ^= temp; right ^= (temp << -16);
    temp = ((left >>> 2) ^ right) & 0x33333333; right ^= temp; left ^= (temp << 2);
    temp = ((right >>> -16) ^ left) & 0x0000ffff; left ^= temp; right ^= (temp << -16);
    temp = ((left >>> 1) ^ right) & 0x55555555; right ^= temp; left ^= (temp << 1);
    temp = ((right >>> 8) ^ left) & 0x00ff00ff; left ^= temp; right ^= (temp << 8);
    temp = ((left >>> 1) ^ right) & 0x55555555; right ^= temp; left ^= (temp << 1);

    //the right side needs to be shifted and to get the last four bits of the left side
    temp = (left << 8) | ((right >>> 20) & 0x000000f0);
    //left needs to be put upside down
    left = (right << 24) | ((right << 8) & 0xff0000) | ((right >>> 8) & 0xff00) | ((right >>> 24) & 0xf0);
    right = temp;

    //now go through and perform these shifts on the left and right keys
    for (var i=0; i < shifts.length; i++) {
      //shift the keys either one or two bits to the left
      if (shifts[i]) {left = (left << 2) | (left >>> 26); right = (right << 2) | (right >>> 26);}
      else {left = (left << 1) | (left >>> 27); right = (right << 1) | (right >>> 27);}
      left &= -0xf; right &= -0xf;

      //now apply PC-2, in such a way that E is easier when encrypting or decrypting
      //this conversion will look like PC-2 except only the last 6 bits of each byte are used
      //rather than 48 consecutive bits and the order of lines will be according to 
      //how the S selection functions will be applied: S2, S4, S6, S8, S1, S3, S5, S7
      lefttemp = pc2bytes0[left >>> 28] | pc2bytes1[(left >>> 24) & 0xf]
              | pc2bytes2[(left >>> 20) & 0xf] | pc2bytes3[(left >>> 16) & 0xf]
              | pc2bytes4[(left >>> 12) & 0xf] | pc2bytes5[(left >>> 8) & 0xf]
              | pc2bytes6[(left >>> 4) & 0xf];
      righttemp = pc2bytes7[right >>> 28] | pc2bytes8[(right >>> 24) & 0xf]
                | pc2bytes9[(right >>> 20) & 0xf] | pc2bytes10[(right >>> 16) & 0xf]
                | pc2bytes11[(right >>> 12) & 0xf] | pc2bytes12[(right >>> 8) & 0xf]
                | pc2bytes13[(right >>> 4) & 0xf];
      temp = ((righttemp >>> 16) ^ lefttemp) & 0x0000ffff; 
      keys[n++] = lefttemp ^ temp; keys[n++] = righttemp ^ (temp << 16);
    }
  } //for each iterations
  //return the keys we've created
  return keys;
} //end of des_createKeys


function sendPostAPIRequest(url, action, reqParams, handler){
		var curTime = new Date();
		reqParams["action"]=action;
		reqParams["apikey"]=User.apikey;
		reqParams["timestamp"]=curTime;
		reqParams["version"]="1";

		var sortedKeys = [];
		for( var key in reqParams){
			sortedKeys.push(key);
		}
		Utils.sort(sortedKeys, null, SORT_TYPE_DESC);

		var paramValueStr = "";
		var dataStr = "";
		for (var i=0; i<sortedKeys.length;i++){
			var key = sortedKeys[i];
			paramValueStr += key;
			paramValueStr += reqParams[key];
			dataStr += encodeURIComponent(key)+"="+encodeURIComponent(reqParams[key])+"&";
		}
		var checksum = des(User.secretkey, paramValueStr, 1, 0, [], 1);
		dataStr += "checksum="+checksum;
		Request.sendPOST(url, dataStr, handler);
}

////////////////////////////// TEST //////////////////////////////

var Base64 = {
 
	// private property
	_keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",
 
	// public method for encoding
	encode : function (input) {
		var output = "";
		var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
		var i = 0;
 
		input = Base64._utf8_encode(input);
 
		while (i < input.length) {
 
			chr1 = input.charCodeAt(i++);
			chr2 = input.charCodeAt(i++);
			chr3 = input.charCodeAt(i++);
 
			enc1 = chr1 >> 2;
			enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
			enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
			enc4 = chr3 & 63;
 
			if (isNaN(chr2)) {
				enc3 = enc4 = 64;
			} else if (isNaN(chr3)) {
				enc4 = 64;
			}
 
			output = output +
			this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) +
			this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);
 
		}
 
		return output;
	},
 
	// public method for decoding
	decode : function (input) {
		var output = "";
		var chr1, chr2, chr3;
		var enc1, enc2, enc3, enc4;
		var i = 0;
 
		input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
 
		while (i < input.length) {
 
			enc1 = this._keyStr.indexOf(input.charAt(i++));
			enc2 = this._keyStr.indexOf(input.charAt(i++));
			enc3 = this._keyStr.indexOf(input.charAt(i++));
			enc4 = this._keyStr.indexOf(input.charAt(i++));
 
			chr1 = (enc1 << 2) | (enc2 >> 4);
			chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
			chr3 = ((enc3 & 3) << 6) | enc4;
 
			output = output + String.fromCharCode(chr1);
 
			if (enc3 != 64) {
				output = output + String.fromCharCode(chr2);
			}
			if (enc4 != 64) {
				output = output + String.fromCharCode(chr3);
			}
 
		}
 
		output = Base64._utf8_decode(output);
 
		return output;
 
	},
 
	// private method for UTF-8 encoding
	_utf8_encode : function (string) {
		string = string.replace(/\r\n/g,"\n");
		var utftext = "";
 
		for (var n = 0; n < string.length; n++) {
 
			var c = string.charCodeAt(n);
 
			if (c < 128) {
				utftext += String.fromCharCode(c);
			}
			else if((c > 127) && (c < 2048)) {
				utftext += String.fromCharCode((c >> 6) | 192);
				utftext += String.fromCharCode((c & 63) | 128);
			}
			else {
				utftext += String.fromCharCode((c >> 12) | 224);
				utftext += String.fromCharCode(((c >> 6) & 63) | 128);
				utftext += String.fromCharCode((c & 63) | 128);
			}
 
		}
 
		return utftext;
	},
 
	// private method for UTF-8 decoding
	_utf8_decode : function (utftext) {
		var string = "";
		var i = 0;
		var c = c1 = c2 = 0;
 
		while ( i < utftext.length ) {
 
			c = utftext.charCodeAt(i);
 
			if (c < 128) {
				string += String.fromCharCode(c);
				i++;
			}
			else if((c > 191) && (c < 224)) {
				c2 = utftext.charCodeAt(i+1);
				string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
				i += 2;
			}
			else {
				c2 = utftext.charCodeAt(i+1);
				c3 = utftext.charCodeAt(i+2);
				string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
				i += 3;
			}
 
		}
 
		return string;
	}
 
}

function stringToHex (s) {
  var r = "";
  var hexes = new Array ("0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f");
  for (var i=0; i<s.length; i++) {r += hexes [s.charCodeAt(i) >> 4] + hexes [s.charCodeAt(i) & 0xf];}
  return r;
}

/*
var key = "this is a 24 byte key !!";
var message = "This is a test message";
var ciphertext = des (key, message, 1, 0);
document.writeln ("DES Test: " + stringToHex (ciphertext));
*/



////////////////////////////////////////////////////////////////////////

function getAgentDialog(){
	Controller.showDialogPanel( $id("AddAgent") ,'Agent');
	GENERAL_SETTINGS.REDIRECT_TO_DOWNLOAD_PAGE = true;	
}

function isVisible(obj)
{
    if (obj == document) return true
    
    if (!obj) return false
    if (!obj.parentNode) return false
    if (obj.style) {
        if (obj.style.display == 'none') return false
        if (obj.style.visibility == 'hidden') return false
    }
    
    //Try the computed style in a standard way
    if (window.getComputedStyle) {
        var style = window.getComputedStyle(obj, "")
        if (style.display == 'none') return false
        if (style.visibility == 'hidden') return false
    }
    
    //Or get the computed style using IE's silly proprietary way
    var style = obj.currentStyle
    if (style) {
        if (style['display'] == 'none') return false
        if (style['visibility'] == 'hidden') return false
    }
    
    return isVisible(obj.parentNode)
}