var dateFormat = function () {
	var token = /d{1,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|[LloSZ]|"[^"]*"|'[^']*'/g,
		timezone = /\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g,
		timezoneClip = /[^-+\dA-Z]/g,
		pad = function (val, len) {
			val = String(val);
			len = len || 2;
			while (val.length < len) val = "0" + val;
			return val;
		};

	// Regexes and supporting functions are cached through closure
	return function (date, mask, utc) {
		var dF = dateFormat;

		// You can't provide utc if you skip other args (use the "UTC:" mask prefix)
		if (arguments.length == 1 && Object.prototype.toString.call(date) == "[object String]" && !/\d/.test(date)) {
			mask = date;
			date = undefined;
		}

		// Passing date through Date applies Date.parse, if necessary
		date = date ? new Date(date) : new Date;
		if (isNaN(date)) throw SyntaxError("invalid date");

		mask = String(dF.masks[mask] || mask || dF.masks["default"]);

		// Allow setting the utc argument via the mask
		if (mask.slice(0, 4) == "UTC:") {
			mask = mask.slice(4);
			utc = true;
		}

		var _ = utc ? "getUTC" : "get",
			d = date[_ + "Date"](),
			D = date[_ + "Day"](),
			m = date[_ + "Month"](),
			y = date[_ + "FullYear"](),
			H = date[_ + "Hours"](),
			M = date[_ + "Minutes"](),
			s = date[_ + "Seconds"](),
			L = date[_ + "Milliseconds"](),
			o = utc ? 0 : date.getTimezoneOffset(),
			flags = {
				d: d,
				dd: pad(d),
				ddd: dF.i18n.dayNames[D],
				dddd: dF.i18n.dayNames[D + 7],
				m: m + 1,
				mm: pad(m + 1),
				mmm: dF.i18n.monthNames[m],
				mmmm: dF.i18n.monthNames[m + 12],
				yy: String(y).slice(2),
				yyyy: y,
				h: H % 12 || 12,
				hh: pad(H % 12 || 12),
				H: H,
				HH: pad(H),
				M: M,
				MM: pad(M),
				s: s,
				ss: pad(s),
				l: pad(L, 3),
				L: pad(L > 99 ? Math.round(L / 10) : L),
				t: H < 12 ? "a" : "p",
				tt: H < 12 ? "am" : "pm",
				T: H < 12 ? "A" : "P",
				TT: H < 12 ? "AM" : "PM",
				Z: utc ? "UTC" : (String(date).match(timezone) || [""]).pop().replace(timezoneClip, ""),
				o: (o > 0 ? "-" : "+") + pad(Math.floor(Math.abs(o) / 60) * 100 + Math.abs(o) % 60, 4),
				S: ["th", "st", "nd", "rd"][d % 10 > 3 ? 0 : (d % 100 - d % 10 != 10) * d % 10]
			};

		return mask.replace(token, function ($0) {
			return $0 in flags ? flags[$0] : $0.slice(1, $0.length - 1);
		});
	};
} ();

// Some common format strings
dateFormat.masks = {
	"default": "ddd mmm dd yyyy HH:MM:ss",
	shortDate: "m/d/yy",
	mediumDate: "mmm d, yyyy",
	longDate: "mmmm d, yyyy",
	fullDate: "dddd, mmmm d, yyyy",
	shortTime: "h:MM TT",
	mediumTime: "h:MM:ss TT",
	longTime: "h:MM:ss TT Z",
	isoDate: "yyyy-mm-dd",
	isoTime: "HH:MM:ss",
	isoDateTime: "yyyy-mm-dd'T'HH:MM:ss",
	isoUtcDateTime: "UTC:yyyy-mm-dd'T'HH:MM:ss'Z'"
};

// Internationalization strings
dateFormat.i18n = {
	dayNames: [
		"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat",
		"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"
	],
	monthNames: [
		"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
		"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"
	]
};

// For convenience...
Date.prototype.format = function (mask, utc) {
	return dateFormat(this, mask, utc);
};

if (typeof(JSON) === 'undefined' || JSON == null) {
	var JSON = function() {}
}

JSON.stringify = JSON.stringify || function (obj) {
	var t = typeof (obj);
	if (t != "object" || obj === null) {
		// simple data type  
		if (t == "string") obj = '"' + obj + '"';
		return String(obj);
	}
	else {
		// recurse array or object  
		var n, v, json = [], arr = (obj && obj.constructor == Array);
		for (n in obj) {
			v = obj[n]; t = typeof (v);
			if (t == "string") v = '"' + v + '"';
			else if (t == "object" && v !== null) v = JSON.stringify(v);
			json.push((arr ? "" : '"' + n + '":') + String(v));
		}
		return (arr ? "[" : "{") + String(json) + (arr ? "]" : "}");
	}
}

JSON.parse = JSON.parse || function (str) {
	if (str === "") str = '""';
	eval("var p = " + str + ";");
	return p;
}

function setWindowElement() {
	if (arguments.length < 2) {
		return;
	}
	var windowElementString = arguments[0];
	var windowElementStringValue = arguments[1];
	// arguments[2] should match parent[.parent].window!!! add regexp check later
	var windowObjectString = arguments.length > 2 ? arguments[2] : 'window';
	var windowElement = null;

	do {
		windowElement = eval(windowObjectString + '.' + windowElementString);
		if (windowElement != null) {
			eval(windowObjectString + '.' + windowElementString + ' = ' + windowElementStringValue);
			break;
		}
	}
	while (getParentWindow(windowObjectString) != null && (windowObjectString = 'parent.' + windowObjectString));
}

function getWindowElement() {
	if (arguments.length == 0) {
		return null;
	}
	var windowElementString = arguments[0];
	// arguments[1] should match parent[.parent].window!!! add regexp check later
	var windowObjectString = arguments.length > 1 ? arguments[1] : 'window';
	var windowElement = null;

	do {
		windowElement = eval(windowObjectString + '.' + windowElementString);
		if (windowElement != null) {
			break;
		}
	}
	while (getParentWindow(windowObjectString) != null && (windowObjectString = 'parent.' + windowObjectString));

	return windowElement;
}

function getParentWindow() {
	var windowObjectString = arguments.length > 0 ? arguments[0] : 'window';
	var windowObject = eval(windowObjectString);
	var windowParentObject = eval('parent.' + windowObjectString);
	return windowObject == windowParentObject || windowParentObject == null ? null : windowParentObject;
}

function getTopWindow() {
	var windowObjectString = 'window';
	var windowObject = null, windowParentObject = window;
	var noMoreParentWindow = false;
	while (!noMoreParentWindow) {
		windowObject = windowParentObject;
		windowObjectString = 'parent.' + windowObjectString;
		windowParentObject = eval(windowObjectString);
		noMoreParentWindow = windowParentObject == null || windowObject == windowParentObject;
	}
	return windowObject;
}

function getCSS(theClass, element) {
	var cssrules;
	var selectorText = new String();
	if (document.all) {
		cssrules = 'rules';
	}
	else if (document.getElementById) {
		cssrules = 'cssRules';
	}
	for (var S = 0; S < document.styleSheets.length; S++) {
		for (var R = 0; R < document.styleSheets[S][cssrules].length; R++) {
			selectorText = document.styleSheets[S][cssrules][R].selectorText;
			if (selectorText && selectorText.replace(/\./g, '').replace(/^\*/, '') == theClass) {
				return document.styleSheets[S][cssrules][R].style[element];
			}
		}
	}
	return '';
}

function setCSS(theClass, element, value) {
	var cssrules;
	if (document.all) {
		cssrules = 'rules';
	}
	else if (document.getElementById) {
		cssrules = 'cssRules';
	}
	for (var S = 0; S < document.styleSheets.length; S++) {
		for (var R = 0; R < document.styleSheets[S][cssrules].length; R++) {
			selectorText = document.styleSheets[S][cssrules][R].selectorText;
			if (selectorText && document.styleSheets[S][cssrules][R].selectorText.replace(/\./g, '').replace(/^\*/, '') == theClass) {
				document.styleSheets[S][cssrules][R].style[element] = value;
			}
		}
	}
}

function setTabControlHeaderWidth() {
	var tabControlHeaderList = document.getElementsByTagName('UL');
	var tabControlHeaderWidth = 0;
	var tabControlHeaderItemList = null;
	for (i = 0; i < tabControlHeaderList.length; i++) {
		if (tabControlHeaderList[i].className && tabControlHeaderList[i].className == 'TabControlHeader') {
			tabControlHeaderItemList = tabControlHeaderList[i].getElementsByTagName('LI');
			tabControlHeaderWidth = 0;
			for (j = 0; j < tabControlHeaderItemList.length; j++) {
				if (tabControlHeaderItemList[j].className) {
					tabControlHeaderItemListWidth = parseInt(getCSS(tabControlHeaderItemList[j].className, 'width'));
					if (tabControlHeaderItemListWidth) {
						tabControlHeaderWidth += tabControlHeaderItemListWidth;
					}
				}
			}
			if (tabControlHeaderWidth > 0) {
				tabControlHeaderOldWidth = parseInt(getCSS('TabControlHeader', 'width'));
				if (tabControlHeaderOldWidth && tabControlHeaderOldWidth < tabControlHeaderWidth) {
					setCSS('TabControlHeader', 'width', tabControlHeaderWidth + 'px');
				}
			}
		}
	}
}

function Trim(trim_value) {
	if (trim_value.length < 1) {
		return '';
	}
	trim_value = RTrim(trim_value);
	trim_value = LTrim(trim_value);
	if (trim_value == '') {
		return '';
	}
	else {
		return trim_value;
	}
}

function RTrim(value) {
	var w_space = String.fromCharCode(32);
	var v_length = value.length;
	var strTemp = '';
	if (v_length < 0) {
		return '';
	}
	var iTemp = v_length - 1;
	while (iTemp > -1) {
		if (value.charAt(iTemp) == w_space) { }
		else {
			strTemp = value.substring(0, iTemp + 1);
			break;
		}
		iTemp = iTemp - 1;
	}
	return strTemp;
}

function LTrim(value) {
	var w_space = String.fromCharCode(32);
	if (v_length < 1) {
		return '';
	}
	var v_length = value.length;
	var strTemp = '';
	var iTemp = 0;
	while (iTemp < v_length) {
		if (value.charAt(iTemp) == w_space) { }
		else {
			strTemp = value.substring(iTemp, v_length);
			break;
		}
		iTemp = iTemp + 1;
	}
	return strTemp;
}

function showNote() {
	var divID = showNote.arguments[0];
	var noteOnOff = showNote.arguments[1];
	var divObj = document.getElementById(divID);
	if (divObj != null && (showNote.arguments.length == 2 || showNote.arguments.length == 3)) {
		divObj.style.visibility = 'hidden';
		return;
	}
	

	var prefixId = "";
	if (showNote.arguments[6] != null) {
		var prefixId = showNote.arguments[6].id.replace(showNote.arguments[3], "");
	}


	var divClass = showNote.arguments[2];
	var bindObj = document.getElementById(prefixId + showNote.arguments[3]);
	var noteTextObj = document.getElementById(prefixId + showNote.arguments[4]);
	var noteDateObj = document.getElementById(prefixId + showNote.arguments[5]);
	var noteText = (noteTextObj.value == '' ? 'Add new note here' : noteTextObj.value);
	noteText = noteText.replace(/\r\n/g, '<br/>'); //replace to html breaks to display correctly in IE
	noteText = noteText.replace(/ /g, '&nbsp;'); //replace to html breaks to display correctly in IE
	var titleText = (noteDateObj.value == '' || noteTextObj.value == '' ? '' : noteDateObj.value);
	if (divObj != null) {
		// divObj, divTitle, divBody have already been created
		var divTitle = divObj.children.length == 1 ? null : divObj.children[0];
		var divBody = divObj.children[divObj.children.length - 1];
		CreateTitleDivForNote(divObj, divTitle, titleText);
		CreateBodyDivForNote(divObj, divBody, noteText);
	}
	else {
		var divLeft = DL_GetElementLeft(bindObj);
		var divTop = DL_GetElementTop(bindObj);
		divObj = document.createElement('DIV');
		divObj.className = divClass;
		divObj.id = divID;
		divObj.style.zIndex = 20;
		divObj.style.position = 'absolute';
		divObj.style.left = (divLeft + bindObj.width + 4) + 'px';
		divObj.style.top = divTop + bindObj.height + 4 + 'px';
		divObj.style.visibility = 'visible';
		divObj.style.padding = '2px';
		document.getElementById('masterBody').appendChild(divObj);
		CreateTitleDivForNote(divObj, null, titleText);
		CreateBodyDivForNote(divObj, null, noteText);
	}
	divObj.style.visibility = 'visible';
}

function CreateBodyDivForNote(divObj, divBody, noteText) {
	if (divObj == null) return;
	if (divBody == null) {
		divBody = document.createElement('DIV');
		divBody.style.display = 'block';
		divObj.appendChild(divBody);
	}
	divBody.innerHTML = noteText;
}

function CreateTitleDivForNote(divObj, divTitle, titleText) {
	if (divObj == null) return;
	if (divTitle == null && titleText != null && titleText != 'null' && titleText != '') {
		var divTitle = document.createElement('DIV');
		divTitle.style.zIndex = 20;
		divTitle.style.display = 'block';
		divTitle.style.height = '20px';
		divTitle.style.whiteSpace = 'nowrap';
		divTitle.className = 'bold';
		divTitle.appendChild(document.createTextNode(titleText));

		var divBody = divObj.children[0];
		if (divBody != null) divObj.insertBefore(divTitle, divBody);
		else divObj.appendChild(divTitle);
	}
	else if (divTitle != null) {
		if (titleText == null || titleText == 'null' || titleText == '') {
			divObj.removeChild(divTitle);
			divTitle = null;
		}
		else divTitle.innerHTML = titleText;
	}
}

function showText() {

	var noteText = showText.arguments[0];
	var noteOnOff = showText.arguments[1];
	var bindObj = showText.arguments[2];
	var divId = showText.arguments[3];

	var divObj = document.getElementById(divId);

	if (noteOnOff.length == 3) {
		divObj.style.visibility = 'hidden';
		return;
	}


	var titleText = '';
	if (divObj == null) {
		var divLeft = DL_GetElementLeft(bindObj);
		var divTop = DL_GetElementTop(bindObj);
		divObj = document.createElement('DIV');
		divObj.className = 'note';
		divObj.id = divId;
		divObj.style.zIndex = 20;
		divObj.style.position = 'absolute';
		divObj.style.left = (divLeft + bindObj.width + 4) + 'px';
		divObj.style.top = divTop + bindObj.height + 4 + 'px';
		divObj.style.visibility = 'visible';
		divObj.style.padding = '2px';
		document.getElementById('masterBody').appendChild(divObj);
		//    if (Trim(titleText) != '') {
		//        var divTitle = document.createElement('DIV');
		//        divTitle.style.zIndex = 20;
		//        divTitle.style.display = 'block';
		//        divTitle.style.height = '20px';
		//        divTitle.style.whiteSpace = 'nowrap';
		//        divTitle.className = 'bold';
		//        divTitle.appendChild(document.createTextNode(''));
		//        divObj.appendChild(divTitle);
		//    }
		var divBody = document.createElement('DIV');
		divBody.style.display = 'block';
		divBody.innerHTML = noteText;
		divObj.appendChild(divBody);
	}
	divObj.style.visibility = 'visible';
}

function DL_GetElementLeft(eElement) {
	var nLeftPos = eElement.offsetLeft;          // initialize var to store calculations
	var eParElement = eElement.offsetParent;     // identify first offset parent element  
	while (eParElement != null) {                                            // move up through element hierarchy
		nLeftPos += eParElement.offsetLeft;      // appending left offset of each parent
		eParElement = eParElement.offsetParent;  // until no more offset parents exist
	}
	if (navigator.appName == 'Microsoft Internet Explorer') {
		marginLeft = parseInt(getCSS('LeftMenu', 'marginLeft'));
		if (marginLeft) {
			//nLeftPos = nLeftPos - marginLeft;
		}
	}

	return nLeftPos;                             // return the number calculated
}

function DL_GetElementTop(eElement) {
	var nTopPos = eElement.offsetTop;            // initialize var to store calculations
	var eParElement = eElement.offsetParent;     // identify first offset parent element  
	while (eParElement != null) {                                            // move up through element hierarchy
		nTopPos += eParElement.offsetTop;        // appending top offset of each parent
		eParElement = eParElement.offsetParent;  // until no more offset parents exist
	}
	return nTopPos;                              // return the number calculated
}

function EndRequestHandler(sender, args) {
	if (args.get_error() != undefined) {
		var errorMessage = args.get_error().message;
		args.set_errorHandled(true);
		$get('AlertMessage').innerHTML = errorMessage;
		$find('mbError').show();
	}
}

function ShowConfirmSimple() {
	if (ShowConfirmSimple.arguments.length == 3) {
		$get('btnDeleteID').value = ShowConfirmSimple.arguments[0];
		$("#" + ShowConfirmSimple.arguments[1] + " div.nowrap").html(ShowConfirmSimple.arguments[2]);
	}
	if (ShowConfirmSimple.arguments.length == 1) {
		$get('btnDeleteID').value = ShowConfirmSimple.arguments[0];
	}

	$find('mbConfirmSimple').show();
	return false;

}

function ShowConfirmApproval() {
	if (ShowConfirmApproval.arguments.length == 1) {
		$get('btnDeleteID').value = ShowConfirmApproval.arguments[0];
	}
	$find('mbConfirmApproval').show();
	return false;
}

function ShowError() {
	if (ShowError.arguments.length == 2) {
		$get('btnDeleteID').value = ShowError.arguments[0];
		$get('AlertMessage').innerHTML = ShowError.arguments[1];
	}
	$find('mbError').show();
	return false;
}

function onContinue() {
	$get('AlertMessage').innerHTML = '';
	$find('mbError').hide();
	return false;
}

function onOkApproval() {
	var murka = onOkApproval.arguments.length == 1 ? onOkApproval.arguments[0] : $get('btnDeleteID').value;
	if ($get('txtEnsureDelete').value.toLowerCase() == 'delete') {
		__doPostBack(murka, '');
	}
}

function onOkSimple() {
	var murka = onOkSimple.arguments.length == 1 ? onOkSimple.arguments[0] : $get('btnDeleteID').value;
	__doPostBack(murka, '');
}

//function getEventTarget(e) {
//    var e = e || window.event;
//    var targ = e.target || e.srcElement;
//    if (targ != null) {
//        if (targ.nodeType == 3) targ = targ.parentNode;
//    }
//    return targ;
//}

function documentSize(whichWinda) {
	var w = 0;
	var h = 0;
	//IE
	if (!window.innerWidth) {
		//strict mode
		if (!(whichWinda.document.documentElement.clientWidth == 0)) {
			w = whichWinda.document.documentElement.clientWidth;
			h = whichWinda.document.documentElement.clientHeight;
		}
		//quirks mode
		else {
			w = whichWinda.document.body.clientWidth;
			h = whichWinda.document.body.clientHeight;
		}
	}
	//w3c
	else {
		w = whichWinda.innerWidth;
		h = whichWinda.innerHeight;
	}
	return { width: w, height: h };
}

function setContentHeightWidth() {
	zapaskaBottom = 0;
	zapaskaLeft = 8;
	var NoLeftMenuForThisNode = false;
	var NoLeftMenuForThisNode = false;
	var windosa = getTopWindow();
	var treeViewObj = windosa.radtree;
	var ifMainContentObj = windosa.document.getElementById('ifMainContent');
	var dvContentObj = windosa.document.getElementById('dvContent');
	var dvContentHeaderObj = windosa.document.getElementById('dvContentHeader');
	var dvContentContentObj = windosa.document.getElementById('dvContentContent');

	if (treeViewObj != null) {
		var ifrmurl = ifMainContentObj.src;
		var getShortWebRoot = windosa.getShortWebRoot;
		var nurl = ifrmurl.substring(ifrmurl.indexOf(getShortWebRoot)); // remove host to fix Firefox
		var node = treeViewObj.findNodeByPath(nurl);
		if (node != null) {
			NoLeftMenuForThisNode = (node.get_parent().get_parent() == null);
		}
	}
	if (NoLeftMenuForThisNode) zapaskaLeft = 0;

	dvTreeMenuContentTop = parseInt(getCSS('dvTreeMenuContent', 'top'));

	if (dvContentObj != null) {
		if (dvTreeMenuContentTop) {
			contentHeight = documentSize(windosa).height - dvTreeMenuContentTop - zapaskaBottom;
			dvContentObj.style.height = contentHeight + 'px';
			//windosa.document.getElementById('ifMainContent').style.width = '100%';
			//setCSS('dvContent', 'height', contentHeight + 'px');
			if (dvContentHeaderObj != null && dvContentContentObj != null) {
				contentHeaderHeight = parseInt(getCSS('dvContentHeader', 'height'));
				contentContentPaddingTop = parseInt(getCSS('dvContentContent', 'paddingTop'));
				contentContentPaddingBottom = parseInt(getCSS('dvContentContent', 'paddingTop'));
				dvContentContentObj.style.height = contentHeight - contentHeaderHeight - contentContentPaddingTop - contentContentPaddingBottom + 'px';
			}
		}
		dvMenuMarginLeft = parseInt(getCSS('dvMenu', 'marginLeft'));
		if (dvMenuMarginLeft) {
			contentWidth = documentSize(windosa).width - (NoLeftMenuForThisNode ? 0 : dvMenuMarginLeft) - zapaskaLeft;
			//setCSS('dvContent', 'width', contentWidth + 'px');
			dvContentObj.style.width = contentWidth + 'px';
			ifMainContentObj.style.width = '100%';
		}
	}
	var customResizeEventName = 'customresize';
	$(document).trigger(customResizeEventName, null);
	$("iframe").each(function() { jQuery(this).contents().find('#'+ customResizeEventName + 'EventElement').trigger('click') });
}

function setContentHeightWidth_Partner() {
	zapaskaBottom = 4;
	zapaskaLeft = 8;
	var noLeftMenuForThisNode = false;
	var windosa = getTopWindow();
	var treeViewObj = windosa.radtree;
	if (treeViewObj != null) {
		var ifMainContentObj = windosa.ifMainContent;
		var ifrmurl = ifMainContentObj.src;
		var getShortWebRoot = windosa.getShortWebRoot;
		var nurl = ifrmurl.substring(ifrmurl.indexOf(getShortWebRoot)); // remove host to fix Firefox
		var node = treeViewObj.findNodeByPath(nurl);
		if (node != null) {
			noLeftMenuForThisNode = (node.get_parent().get_parent() == null);
		}
	}
	dvTreeMenuContentTop = parseInt(getCSS('dvTreeMenuContent', 'top'));
	var dvContentObj = windosa.document.getElementById('dvContent');
	if (dvContentObj != null) {
		if (dvTreeMenuContentTop) {
			contentHeight = documentSize(windosa).height - dvTreeMenuContentTop - zapaskaBottom;
			windosa.document.getElementById('dvContent').style.height = contentHeight + 'px';
			//windosa.document.getElementById('ifMainContent').style.width = '100%';
			//setCSS('dvContent', 'height', contentHeight + 'px');
		}
		dvMenuMarginLeft = parseInt(getCSS('dvMenu', 'marginLeft'));
		if (dvMenuMarginLeft) {
			contentWidth = documentSize(windosa).width - (noLeftMenuForThisNode ? 0 : dvMenuMarginLeft) - zapaskaLeft;
			//setCSS('dvContent', 'width', contentWidth + 'px');
			windosa.document.getElementById('dvContent').style.width = contentWidth + 'px';
			windosa.document.getElementById('ifMainContent').style.width = '100%';
		}
	}
	var customResizeEventName = 'customresize';
	$(document).trigger(customResizeEventName, null);
	$("iframe").each(function () { jQuery(this).contents().find('#' + customResizeEventName + 'EventElement').trigger('click') });
}


function changeURLParams(where, withwhat) {
	var newParamPairs = withwhat.split('&');
	var newParamArray = new Array();
	for (i = 0; i < newParamPairs.length; i++) {
		if (newParamPairs[i].indexOf('=') != -1) {
			var newParamPairArray = newParamPairs[i].split('=');
			newParamArray[newParamPairArray[0]] = newParamPairArray[1];
		}
	}
	whereTmp = where.split('?')[1];
	oldParamPairs = (whereTmp == null ? where : whereTmp);
	whereTmp = oldParamPairs.split('&');
	oldParamPairs = (whereTmp == null ? oldParamPairs : whereTmp);
	var oldParamArray = new Array();
	for (i = 0; i < oldParamPairs.length; i++) {
		if (oldParamPairs[i].indexOf('=') != -1) {
			var oldParamPairArray = oldParamPairs[i].split('=');
			oldParamArray[oldParamPairArray[0].toUpperCase()] = oldParamPairArray[1];
		}
	}
	for (newParam in newParamArray) {
		if (oldParamArray[newParam.toUpperCase()] != null) where = where.replace(new RegExp(newParam + '=' + oldParamArray[newParam.toUpperCase()], ["gi"]), newParam + '=' + newParamArray[newParam]);
		else where += (where.indexOf('?') != -1 ? '&' : '?') + newParam + '=' + newParamArray[newParam];
	}
	return where;
}

function getURLParam(URLstring, parameterName) {

	if (URLstring.indexOf(parameterName) == -1) return null;
	var strReturn = '';
	var strHref = URLstring;
	if (strHref.indexOf('?') > -1) {
		var strQueryString = strHref.substr(strHref.indexOf('?') + 1);
		var aQueryString = strQueryString.split('&');
		for (var iParam = 0; iParam < aQueryString.length; iParam++) {
			if (aQueryString[iParam].toLowerCase().indexOf(parameterName.toLowerCase() + '=') > -1) {
				var aParam = aQueryString[iParam].split('=');
				strReturn = aParam[1];
				break;
			}
		}
	}
	return strReturn;
}

function Contains(array, obj) {
	var i = array.length;
	while (i--) {
		if (array[i] === obj) {
			return true;
		}
	}
	return false;
}

function hilightOption(list, jsddlValue, jsddlID) {

	var IsDefault = ((jsddlValue == null) || (jsddlValue == '')); // flag is to set default value or not
	var mySplitResult = '';
	if (!IsDefault)	mySplitResult = jsddlValue.split(";");
	var items = list.get_items();
	var str = IsDefault ? items.getItem(0).get_text() : '';

	var srcWindow = getTopWindow();
	for (i = 0; i < items.get_count(); i++) {
		var controlid = jsddlID + "_i" + eval(i) + "_chbItem";
		var control = srcWindow.document.getElementById(controlid);

		control.checked = IsDefault; // if IsDefault, then all should be set, the cycle below will be skipped

		for (j = 0; j < mySplitResult.length; j++) {
			if (items.getItem(i).get_value() == mySplitResult[j]) {
				control.checked = true;
				if (str != '') str += ';';
				str += items.getItem(i).get_text();
			}
		}
	} //for i
	//var srcWindow = getTopWindow();
	list.set_text(str);
}

function mSetCombo() {
	var srcWindow = getTopWindow();
	if (srcWindow.radtree != null) {
		var url = location.href.substring(location.href.indexOf(srcWindow.getShortWebRoot)); // remove host to fix Firefox
		var node = srcWindow.radtree.findNodeByPath(url);
		if (node != null) {
			var relateto = node.get_attributes().getAttribute('relateto');
			if (relateto != null && relateto != '') {
				srcWindow.relateTo = relateto.split(',');
			}
			else {
				srcWindow.relateTo = null;
			}
			//!!! Do not use srcWindow.ifMainContent.src, it's still NOT updated by the moment! location.href contains CURRENT url
			//!!! Of course it means this method should be called from iFrame ;)
			if (srcWindow.ifMainContent != null && srcWindow.ddlServer != null) {

				var relatetoServer = srcWindow.relateTo != null && Contains(srcWindow.relateTo, 'TSM');
				var serverValue = getURLParam(location.href, srcWindow.UrlConst_TSMServer_ID);
				if (relatetoServer || serverValue != null) {
					srcWindow.ddlServer.set_visible(true);
					hilightOption(srcWindow.ddlServer, serverValue || srcWindow.document.getElementById('hfServerValue').value, srcWindow.document.getElementById('hfddlServer').value);
				}
				else {
					hilightOption(srcWindow.ddlServer, '', srcWindow.document.getElementById('hfddlServer').value);
					srcWindow.serverValue = '';
					srcWindow.ddlServer.set_visible(false);
				}
			}
			if (srcWindow.ifMainContent != null && srcWindow.ddlCluster != null) {
				var relatetoCluster = srcWindow.relateTo != null && Contains(srcWindow.relateTo, 'SVC');
				var clusterValue = getURLParam(location.href, srcWindow.UrlConst_Cluster_ID);
				if (relatetoCluster || clusterValue != null) {
					srcWindow.ddlCluster.set_visible(true);
					hilightOption(srcWindow.ddlCluster, clusterValue || srcWindow.document.getElementById('hfClusterValue').value, srcWindow.document.getElementById('hfddlCluster').value);
				}
				else {
					hilightOption(srcWindow.ddlCluster, '', srcWindow.document.getElementById('hfddlCluster').value);
					srcWindow.clusterValue = '';
					srcWindow.ddlCluster.set_visible(false);
				}
			}
			if (srcWindow.ifMainContent != null && srcWindow.ddlSwitch != null) {
				var relatetoSwitch = srcWindow.relateTo != null && Contains(srcWindow.relateTo, 'SF');
				var switchValue = getURLParam(location.href, srcWindow.UrlConst_Switch_ID);
				if (relatetoSwitch || switchValue != null) {
					srcWindow.ddlSwitch.set_visible(true);
					hilightOption(srcWindow.ddlSwitch, switchValue || srcWindow.document.getElementById('hfSwitchValue').value, srcWindow.document.getElementById('hfddlSwitch').value);
				}
				else {
					hilightOption(srcWindow.ddlSwitch, '', srcWindow.document.getElementById('hfddlSwitch').value);
					srcWindow.switchValue = '';
					srcWindow.ddlSwitch.set_visible(false);
				}
			}
			if (srcWindow.ifMainContent != null && srcWindow.ddlClariion != null) {
				var relatetoClariion = srcWindow.relateTo != null && Contains(srcWindow.relateTo, 'CLAR');
				var clariionValue = getURLParam(location.href, srcWindow.UrlConst_Clariion_ID);
				if (relatetoClariion || clariionValue != null) {
					srcWindow.ddlClariion.set_visible(true);
					hilightOption(srcWindow.ddlClariion, clariionValue || srcWindow.document.getElementById('hfClariionValue').value, srcWindow.document.getElementById('hfddlClariion').value);
				}
				else {
					hilightOption(srcWindow.ddlClariion, '', srcWindow.document.getElementById('hfddlClariion').value);
					srcWindow.clariionValue = '';
					srcWindow.ddlClariion.set_visible(false);
				}
			}

			var bIsDetailView = false;
			if (typeof jsIsDetailView == 'function') {
				bIsDetailView = jsIsDetailView();
			}
			
			srcWindow.ddlCluster.set_enabled(!bIsDetailView);
			srcWindow.ddlCluster.set_enableTextSelection(!bIsDetailView);

			srcWindow.ddlServer.set_enabled(!bIsDetailView);
			srcWindow.ddlServer.set_enableTextSelection(!bIsDetailView);

			srcWindow.ddlSwitch.set_enabled(!bIsDetailView);
			srcWindow.ddlSwitch.set_enableTextSelection(!bIsDetailView);

			srcWindow.ddlClariion.set_enabled(!bIsDetailView);
			srcWindow.ddlClariion.set_enableTextSelection(!bIsDetailView);
		}
	}
}

function mSetCombo_RBC() {
	var srcWindow = getTopWindow();

	var url = location.href.substring(location.href.indexOf(srcWindow.getShortWebRoot)); // remove host to fix Firefox
	var node = srcWindow.radtree.findNodeByPath(url);
	if (node != null) {
		var relateto = node.get_attributes().getAttribute('relateto');
		var contractrelateto = node.get_attributes().getAttribute('contractrelateto');
		srcWindow.contractRelateTo = true;
		if (contractrelateto != null && contractrelateto != '' && contractrelateto == 'false') {
			srcWindow.contractRelateTo = false;
		}
		if (relateto != null && relateto != '') {
			srcWindow.relateTo = relateto.split(',');
		}
		else {
			srcWindow.relateTo = null;
		}
		//!!! Do not use srcWindow.ifMainContent.src, it's still NOT updated by the moment! location.href contains CURRENT url
		//!!! Of course it means this method should be called from iFrame ;)

		if (srcWindow.ifMainContent != null && srcWindow.ddlContract != null) {
			var relatetoContract = srcWindow.contractRelateTo;
			var nodeValue = getURLParam(location.href, srcWindow.UrlConst_Node_Name);
			var contractValue = getURLParam(location.href, srcWindow.UrlConst_Contract_ID);
			if (relatetoContract || nodeValue != null) {
				srcWindow.ddlContract.set_visible(true);
				hilightOption(srcWindow.ddlContract, contractValue || srcWindow.document.getElementById('hfContractValue').value, srcWindow.document.getElementById('hfddlContract').value);
			}
			else {
				hilightOption(srcWindow.ddlContractr, '', srcWindow.document.getElementById('hfddlContract').value);
				srcWindow.serverValue = '';
				srcWindow.ddlContract.set_visible(false);
			}
		}
		//		if (srcWindow.ifMainContent != null && srcWindow.ddlContract != null) {
		//			//var contractValue = getURLParam(location.href, srcWindow.UrlConst_Contract_ID);
		//			var nodeValue = getURLParam(location.href, srcWindow.UrlConst_Node_Name);
		//			if ((nodeValue == null || nodeValue == '') && srcWindow.contractRelateTo) {
		//				srcWindow.ddlContract.className = srcWindow.ddlContract.className.replace('displayNone', 'displayBlock');
		//				//srcWindow.ddlContract.className = srcWindow.ddlContract.className.replace('displayBlock', 'displayNone'); ;
		//			}
		//			else {
		//				srcWindow.ddlContract.className = srcWindow.ddlContract.className.replace('displayBlock', 'displayNone'); ;
		//				//srcWindow.ddlContract.className = srcWindow.ddlContract.className.replace('displayNone', 'displayBlock');
		//				//hilightOption(srcWindow.ddlContract, nodeValue || srcWindow.nodeValue);
		//			}
		//		}

		var bIsDetailView = false;
		if (typeof jsIsDetailView == 'function') {
			bIsDetailView = jsIsDetailView();
		}

		srcWindow.ddlContract.set_enabled(!bIsDetailView);
		srcWindow.ddlContract.set_enableTextSelection(!bIsDetailView);
	}
}

function mSetCombo_Partner() {
	var srcWindow = getTopWindow();

	var url = location.href.substring(location.href.indexOf(srcWindow.getShortWebRoot)); // remove host to fix Firefox
	var node = srcWindow.radtree.findNodeByPath(url);
	if (node != null) {
		var relateto = node.get_attributes().getAttribute('relateto');
		if (relateto != null && relateto != '') {
			srcWindow.relateTo = relateto.split(',');
		}
		else {
			srcWindow.relateTo = null;
		}
		//!!! Do not use srcWindow.ifMainContent.src, it's still NOT updated by the moment! location.href contains CURRENT url
		//!!! Of course it means this method should be called from iFrame ;)
		if (srcWindow.ifMainContent != null && srcWindow.ddlServer != null) {

			var relatetoServer = srcWindow.relateTo != null && Contains(srcWindow.relateTo, 'TSM');
			var serverValue = getURLParam(location.href, srcWindow.UrlConst_TSMServer_ID);
			if (relatetoServer || serverValue != null) {
				srcWindow.ddlServer.className = srcWindow.ddlServer.className.replace('displayNone', 'displayBlock');
				hilightOption(srcWindow.ddlServer, serverValue || srcWindow.serverValue);
			}
			else {
				srcWindow.ddlServer.className = srcWindow.ddlServer.className.replace('displayBlock', 'displayNone'); ;


			}
		}
		if (srcWindow.ifMainContent != null && srcWindow.ddlCluster != null) {
			var relatetoCluster = srcWindow.relateTo != null && Contains(srcWindow.relateTo, 'SVC');
			var clusterValue = getURLParam(location.href, srcWindow.UrlConst_SVCCluster_ID);
			if (relatetoCluster || clusterValue != null) {
				srcWindow.ddlCluster.className = srcWindow.ddlCluster.className.replace('displayNone', 'displayBlock');
				hilightOption(srcWindow.ddlCluster, clusterValue || srcWindow.clusterValue);
			}
			else {
				srcWindow.ddlCluster.className = srcWindow.ddlCluster.className.replace('displayBlock', 'displayNone'); ;
			}
		}

		if (srcWindow.ifMainContent != null && srcWindow.ddlContract != null) {
			//var contractValue = getURLParam(location.href, srcWindow.UrlConst_Contract_ID);
			var nodeValue = getURLParam(location.href, srcWindow.UrlConst_Node_Name);
			if (nodeValue == null || nodeValue == '') {
				srcWindow.ddlContract.className = srcWindow.ddlContract.className.replace('displayNone', 'displayBlock');
				//srcWindow.ddlContract.className = srcWindow.ddlContract.className.replace('displayBlock', 'displayNone'); ;
			}
			else {
				srcWindow.ddlContract.className = srcWindow.ddlContract.className.replace('displayBlock', 'displayNone'); ;
				//srcWindow.ddlContract.className = srcWindow.ddlContract.className.replace('displayNone', 'displayBlock');
				//hilightOption(srcWindow.ddlContract, nodeValue || srcWindow.nodeValue);
			}
		}
	}
}


function SendCommandCollapse(objID, collapse) {
	var windosa = getTopWindow();
	var getShortWebRoot = windosa.getShortWebRoot;
	var dvObj = document.getElementById('dv' + objID);
	var linkObj = document.getElementById('link' + objID);
	var linkImgObj = document.getElementById('linkImg' + objID);
	var imgObj = document.getElementById('img' + objID);
	var mustHide = collapse == 'collapse';
	linkObj.onclick = function() { SendCommandCollapse('PartnerInfo', (collapse == 'collapse' ? 'expand' : 'collapse')); }
	linkImgObj.onclick = function() { SendCommandCollapse('PartnerInfo', (collapse == 'collapse' ? 'expand' : 'collapse')); }
	linkObj.innerHTML = mustHide ? '[Details]' : '[Details]';
	imgObj.src = getShortWebRoot + (mustHide ? '/images/up.gif' : '/images/down.gif');
	dvObj.className = mustHide ? 'displayNone' : 'displayYes';

	$.ajax({
		type: "POST",
		url: "../WebServices/ParameterSaver.asmx/SaveCollapse",
		data: "{'objID' : '" + objID + "','collapse' : '" + collapse + "'}",
		contentType: "application/json; charset=utf-8",
		dataType: "json",
		success: function(result, status) {
			AjaxFinishedSendCollapse(result, status);
		},
		error: function(XMLHttpRequest, textStatus, errorThrown) {
			AjaxFailedSendCollapse(XMLHttpRequest, textStatus, errorThrown);
		}
	});
}

function GetDetailEvent(serverID, serverName, nodeName, domainName, scheduleName, dateFrom, dateTo, cellObj) {
	var cellLeft = DL_GetElementLeft(cellObj);
	var cellTop = DL_GetElementTop(cellObj);
	if (cellLeft + $('#pnlEventDetail').width() > documentSize(window).width) {
		$('#pnlEventDetail').css('left', cellLeft - $('#pnlEventDetail').width() + 28);
	}
	else {
		$('#pnlEventDetail').css('left', cellLeft + 2);
	}
	if (cellTop + $('#pnlEventDetail').height() > documentSize(window).height) {
		$('#pnlEventDetail').css('top', cellTop - $('#pnlEventDetail').height() - 10);
	}
	else {
		$('#pnlEventDetail').css('top', cellTop + 19);
	}

	$('#pnlEventDetail').show();
	$("#content").hide();
	$("#preloader").show();

	$('#pnlEventDetail').hover(function() {
		mouse_is_inside = true;
	}, function() {
		mouse_is_inside = false;
	});

	$(prevcellObj).removeClass('eventreportactivecell');
	$(cellObj).addClass('eventreportactivecell');
	prevcellObj = cellObj;
	$.ajax({
		type: "POST",
		url: "../WebServices/GetDetail.asmx/Event",
		data: "{'serverID' : '" + serverID + "','serverName' : '" + serverName + "','nodeName' : '" + nodeName + "','domainName' : '" + domainName + "','scheduleName' : '" + scheduleName + "','dateFrom' : '" + dateFrom + "','dateTo' : '" + dateTo + "'}",
		contentType: "application/json; charset=utf-8",
		dataType: "json",
		success: function(xml, status) {
			AjaxFinishedGetDetailEvent(xml, status, cellObj);
		},
		error: function(XMLHttpRequest, textStatus, errorThrown) {
			AjaxFailedGetDetailEvent(XMLHttpRequest, textStatus, errorThrown, cellObj);
		}
	});
}

function AjaxFinishedGetDetailEvent(xml, status, cellObj) {
	$("#content").show();
	$("#preloader").hide();
	$('#content').html(xml.d.Entity);
}

function AjaxFailedGetDetailEvent(XMLHttpRequest, textStatus, errorThrown, cellObj) {
	$("#content").show();
	$("#preloader").hide();
	$('#content').html('Failed to get details');
}

function CreateEventDetailPanel() {
	var windosa = getTopWindow();
	var pnlEventDetail = document.createElement('DIV');
	pnlEventDetail.className = 'eventreportbox paddingLeft4px paddingRight4px paddingTop4px paddingBottom4px';
	pnlEventDetail.id = 'pnlEventDetail';
	pnlEventDetail.style.overflowY = 'scroll';
	pnlEventDetail.style.overflowX = 'hidden';
	pnlEventDetail.style.display = 'none';
	pnlEventDetail.style.width = '496px';
	pnlEventDetail.style.height = '200px';
	pnlEventDetail.style.position = 'absolute';
	var table = document.createElement('TABLE');
	var tbody = document.createElement('TBODY');
	table.setAttribute('width', '100%');
	table.setAttribute('height', '100%');
	var tr = document.createElement('TR');
	var td = document.createElement('TD');
	td.className = 'ca ma';
	var pnlPreloader = document.createElement('DIV');
	pnlPreloader.id = 'preloader';
	pnlPreloader.style.display = 'block';
	pnlPreloader.style.width = '496px';
	var pnlPreloaderImage = document.createElement('DIV');
	pnlPreloaderImage.className = 'ca';
	var imgForPreloader = document.createElement('IMG');
	imgForPreloader.src = windosa.getWebRoot + '/images/ajax/LoadingProgressBar.gif';
	pnlPreloaderImage.appendChild(imgForPreloader);
	pnlPreloader.appendChild(pnlPreloaderImage);
	var pnlPreloaderText = document.createElement('DIV');
	pnlPreloaderText.className = 'ca darkgreen';
	var textForPreloader = document.createTextNode('Loading event details...');
	pnlPreloaderText.appendChild(textForPreloader);
	pnlPreloader.appendChild(pnlPreloaderText);
	td.appendChild(pnlPreloader);
	var pnlContent = document.createElement('DIV');
	pnlContent.id = 'content';
	pnlContent.style.display = 'block';
	pnlContent.style.width = '496px';
	td.appendChild(pnlContent);
	tr.appendChild(td);
	tbody.appendChild(tr);
	table.appendChild(tbody);
	pnlEventDetail.appendChild(table);
	var imgClose = document.createElement('IMG');
	imgClose.src = windosa.getWebRoot + '/images/close.gif';
	imgClose.style.position = 'absolute';
	imgClose.style.right = '4px';
	imgClose.style.top = '4px';
	imgClose.style.float = 'right';
	imgClose.style.cursor = 'hand';
	imgClose.style.cursor = 'pointer';
	imgClose.onclick = function() {
		$(prevcellObj).removeClass('eventreportactivecell');
		$('#pnlEventDetail').hide();
	};
	pnlEventDetail.appendChild(imgClose);
	document.getElementById('masterBody').appendChild(pnlEventDetail);
}

		function HtmlEncode(strPlainText, blnPartialEncodeOnly) {
			var strPartial = new Array();
			var strFull = new Array();
			var intP = 0;
			var intF = 0;

			var objRegExp = new RegExp();
			var objPartialRegExp = objRegExp.compile('[\\w\\s]');
			for (var i = 0, j = strPlainText.length; i < j; ++i) {
				var strChar = strPlainText.charAt(i);
				var intChar = strChar.charCodeAt(0);

				if (isNaN(intChar)) {
					// IF CHAR FAILED TO DECODE, LEAVE AS CHAR
					strPartial.push(strFull.push(strChar));
				}
				else {
					var strEntity = '&#' + intChar + ';';
					strFull.push(strEntity);
					// IF CHAR WAS [a-zA-Z0-9_ \t] LEAVE AS CHAR, ELSE REPLACE WITH ENTITY
					strPartial.push(objRegExp.test(strChar) ? strChar : strEntity);
				}
			}
			return (blnPartialEncodeOnly ? strPartial.join('') : strFull.join(''));
		}
//		function HtmlDecode(strEncodedText) {
//		    var strData = String(strEncodedText);
//		    var objRegExp = new RegExp();
//		    var objPartialRegExp = objRegExp.compile('&#(\\d+);', 'ig');

//		    /* FOR EACH MATCH TO ANY ENTITY, REPLACE THAT
//		    ENTITY GLOBALLY WITH ITS SINGLE CHAR EQUIVALENT */
//		    while (objRegExp.test(strData)) {
//		        var strCharMatch = RegExp.$1;
//		        var objRegExpMatch = new RegExp('&#' + strCharMatch + ';', 'ig');
//		        strData = strData.replace(objRegExpMatch, String.fromCharCode(strCharMatch));
//		    }
//		    return strData;
//		}


function AjaxFinishedSendCollapse(xml, status) {
}

function AjaxFailedSendCollapse(XMLHttpRequest, textStatus, errorThrown) {
}