
String.prototype.trim = function () { return (this.replace(/^[\s\xA0]+/, "").replace(/[\s\xA0]+$/, "")); }
String.prototype.startsWith = function (str) { return (this.match("^" + str) == str); }
String.prototype.endsWith = function (str) { return (this.match(str + "$") == str); }

function ShowDebugInfo (obj, useValues) { var msg = ""; for (neco in obj) msg += neco + (useValues !== false ? " = " + obj[neco] : "") + "\r\n"; alert(msg); }

var Admin = {

	_appPath: "http://www.powerlifter.cz/admin/",
	_windowsCount: 0,
	_windowsIds: 0,
	_getMainWindow: function () {
		if (window.opener && window.opener.ctl00_Body_tabs)
			return window.opener;
		if (window.ctl00_Body_tabs)
			return window;
		if (top.ctl00_Body_tabs)
			return top;
		return null;
	},
	_getTabs: function () { return (this._getMainWindow() || window).ctl00_Body_tabs; },
	_getTaskBar: function () { return (this._getMainWindow() || window).ctl00_Body_taskBar; },
	_isStandalone: function () { try { return (window.external && (window.external + "") == "PowerADMIN.Bridge"); } catch (e) { return false; } },

	GetUrl: function (relativeUrl) {
		if (relativeUrl.indexOf("://") > 0)
			return relativeUrl;
		if (relativeUrl.startsWith("/"))
			relativeUrl = relativeUrl.substr(1);
		return this._appPath + relativeUrl;
	},

	// MENU: otevre okno vyvolanim z ovladaciho panelu
	OpenMenuWindow: function (menuItem, config, e) {
		var cfg = {
			title: menuItem.text,
			icon: menuItem.icon,
			iconCls: menuItem.iconCls,
			url: menuItem.href,
			defaultMode: 1
		};
		if (config != null) {
			for (prop in config)
				cfg[prop] = config[prop];
		}
		if (cfg.url) {
			e.stopEvent();
			return Admin.OpenWindow(cfg, e);
		}
		return null;
	},

	// MENU: otevre okno vyvolanim z linku (odkazu)
	OpenLinkWindow: function (link, config, e) {
		var cfg = {
			title: link.title,
			url: link.href
		};
		if (config != null) {
			for (prop in config)
				cfg[prop] = config[prop];
		}
		if (cfg.url)
			return Admin.OpenWindow(cfg, e);
		return null;
	},

	// WINDOW: otevre okno se zadanym linkem v ext.js zalozce, ext.js okne nebo v okne prohlizece
	OpenWindow: function (config, e) {
		if (self != top)
			return top.Admin.OpenWindow(config, e);
		var cfg = config || {};
		cfg.url = Admin.GetUrl(cfg.url || cfg.href);
		cfg.mode = (cfg.forceMode && cfg.forceMode != null ? cfg.forceMode : (e != null ? (e.ctrlKey ? 1 : e.shiftKey ? 2 : e.altKey ? 0 : cfg.defaultMode) : cfg.defaultMode) || 0);
		cfg.tab =  cfg.tab || {};
		cfg.standalone = cfg.standalone || {};
		cfg.window = cfg.window || {};
		// zalozky
		if (cfg.mode == 1) {
			var tabs = Admin._getTabs();
			if (tabs == null)
				return null;
			var tab = tabs.getItem(cfg.url);
			if (!tab) {
				var tabCfg = {
					id: cfg.url,
					title: cfg.title,
					icon: cfg.icon,
					iconCls: cfg.iconCls,
					closable: true,
					autoLoad: {
						showMask: true,
						url: cfg.url,
						mode: "iframe",
						maskMsg: "Načítá se '" + cfg.title + "' ..."
					}
				};
				for (prop in cfg.tab)
					tabCfg[prop] = cfg.tab[prop];
				tab = tabs.add(tabCfg);
			}
			tabs.setActiveTab(tab);
			return tab;
		// samostatne okno
		} else if (cfg.mode == 2) {
			var modal = (cfg.standalone.modal != null ? cfg.standalone.modal : (cfg.modal != null ? cfg.modal : Admin.IsModalWindow()));
			var width = (cfg.standalone.width || cfg.standalone.minWidth || cfg.width || cfg.minWidth || 640);
			var height = (cfg.standalone.height || cfg.standalone.minHeight || cfg.height || cfg.minHeight || 480);
			if (Admin._isStandalone())
				return window.external.OpenWindow(cfg.standalone.title || cfg.title, cfg.url, width, height, modal, JSON.stringify(cfg), cfg.pickerCallback);
			var params = (cfg.standalone.parameters || "toolbar=no,location=no,directories=no,status=no,menubar=no,resizable=yes") + "";
			if (params.indexOf("width") < 0)
				params += (params.length > 0 ? "," : "") + "width=" + width;
			if (params.indexOf("height") < 0)
				params += (params.length > 0 ? "," : "") + "height=" + height;
			if (cfg.standalone.scrollable && params.indexOf("scrollbars") < 0)
				params += (params.length > 0 ? "," : "") + "scrollbars=yes";
			return window.open(cfg.url, cfg.standalone.target || "_blank", params);
		// ext.js okno
		} else {
			var modal = (cfg.window.modal != null ? cfg.window.modal : (cfg.modal != null ? cfg.modal : Admin.IsModalWindow()));
			var width = (cfg.window.width || cfg.window.minWidth || cfg.width || cfg.minWidth || 640);
			var height = (cfg.window.height || cfg.window.minHeight || cfg.height || cfg.minHeight || 480);
			var winCfg = {
				title: cfg.window.title || cfg.title,
				icon: cfg.window.icon || cfg.icon,
				iconCls: cfg.window.iconCls || cfg.iconCls,
				border: false,
				width: width,
				height: height,
				minimizable: !modal && top == Admin._getMainWindow(),
				maximizable: true,
				onEsc: Ext.emptyFn,
				closeAction: 'close',
				modal: modal,
				autoLoad: {
					showMask: true,
					url: cfg.url,
					mode: "iframe",
					maskMsg: "Načítá se '" + (cfg.window.title || cfg.title) + "' ..."
				}
			};
			for (prop in cfg.window)
				winCfg[prop] = cfg.window[prop];
			if (Admin._isStandalone())
				return window.external.OpenWindow(winCfg.title, cfg.url, width, height, modal, JSON.stringify(winCfg), cfg.pickerCallback);
			var bodyOverflow = null;
			var bodyOverflowChanged = false;
			if (modal && document.body) {
				bodyOverflow = document.body.style.overflow;
				document.body.style.overflow = "hidden";
				bodyOverflowChanged = true;
			}
			Admin._windowsIds ++;
			winCfg.id = "window" + Admin._windowsIds;
			winCfg.autoLoad.callback = function () {
				var iframe = this.getEl().child("iframe", true);
				if (iframe != null) {
					var iframeWin = (iframe.contentWindow ? (iframe.contentWindow.window ? iframe.contentWindow.window : iframe.contentWindow) : (iframe.window ? iframe.window : iframe));
					iframeWin.extWindow = win;
					iframeWin.pickerCallback = function (records) {
						if (cfg.pickerCallback != null)
							cfg.pickerCallback.call(win, records);
					}
				}
			};
			var win = new Ext.Window(winCfg);
			win.on('minimize', function () {
				this.hide();
			});
			win.on('close', function () {
				Admin._windowsCount --;
				var taskBar = Admin._getTaskBar();
				if (taskBar != null) {
					taskBar.remove("button-" + this.id);
					if (Admin._windowsCount <= 0)
						taskBar.hide();
				}
				if (bodyOverflowChanged)
					document.body.style.overflow = bodyOverflow;
			});
			Admin._windowsCount ++;
			var taskBar = Admin._getTaskBar();
			if (taskBar != null) {
				taskBar.add({
					id: "button-" + win.id,
					text: win.title,
					icon: win.icon,
					iconCls: win.iconCls,
					scope: win,
					handler: function () {
						this.show();
					}
				});
				taskBar.show();
				taskBar.doLayout();
			}
			win.show();
			return win;
		}
	},

	OpenUserWindow: function (userIdOrUrl, config, e) {
		var userId = (userIdOrUrl != null ? parseInt(userIdOrUrl, 10) : null);
		var userUrl = (userId == null || !isNaN(userId) ? "system/userdetail.aspx" + (userId != null ? "?id=" + userId : "") : userIdOrUrl.toString());
		var cfg = {
			url: userUrl,
			width: 640,
			height: 490,
			defaultMode: 0,
			forceMode: 0,
			window: {
				maximizable: false
			}
		};
		if (config != null) {
			for (prop in config)
				cfg[prop] = config[prop];
		}
		return Admin.OpenWindow(cfg, e);
	},

	OpenSubjectWindow: function (subjectIdOrUrl, config, e) {
		var subjectId = (subjectIdOrUrl != null ? parseInt(subjectIdOrUrl, 10) : null);
		var subjectUrl = (subjectId == null || !isNaN(subjectId) ? "system/subjectdetail.aspx" + (subjectId != null ? "?id=" + subjectId : "") : subjectIdOrUrl.toString());
		var cfg = {
			url: subjectUrl,
			width: 640,
			height: 490,
			defaultMode: 0,
			forceMode: 0,
			window: {
				maximizable: false
			}
		};
		if (config != null) {
			for (prop in config)
				cfg[prop] = config[prop];
		}
		return Admin.OpenWindow(cfg, e);
	},

	CloseWindow: function () {
		if (window.extWindow) {
			window.extWindow.close();
		} else if (Admin._isStandalone()) {
			window.external.CloseWindow();
		} else {
			window.close();
		}
	},

	IsModalWindow: function () {
		if (window.extWindow)
			return (window.extWindow.modal === true);
		if (Admin._isStandalone())
			return window.external.IsModal();
		return false;
	},

	IsPickerWindow: function () {
		if (window.pickerCallback)
			return Admin.IsModalWindow();
		return false;
	},

	Picked: function (grid) {
		if (window.pickerCallback)
			window.pickerCallback(grid.getRowsValues({selectedOnly : true}));
		Admin.CloseWindow();
	},

	// GRID column/cell renderers
	Renderers: {

		// sestavi link pro url (www, mail) adresu
		Url: function (value, meta, record) {
			if (value == null)
				return "";
			if (value.indexOf("@") > 0) {
				var emails = value.split(",");
				if (emails.length == 1)
					emails = value.split(";");
				var result = "";
				for (var i = 0; i < emails.length; i ++) {
					if (emails[i].trim().length > 0)
						result += (result.length > 0 ? ", " : "") + String.format("<a href='mailto:{0}'>{0}</a>", emails[i].trim());
				}
				return result;
			}
			var text = value;
			var idx = text.indexOf("://");
			if (idx >= 0)
				text = text.substr(idx + 3, value.length - idx - 3);
			var idx = text.lastIndexOf("/");
			if (idx >= 0)
				text = text.substr(0, idx);
			if (value.indexOf("://") < 0)
				value = "http://" + value;
			return String.format("<a href='{0}' target='_blank'>{1}</a>", value, text);
		},

		// prevede enum divize na text
		Division: function (value, meta, record) {
			if (value == null)
				return "";
			if (value == "SubJuniors")
				return "Sub-Juniors";
			if (value == "Seniors")
				return "Open";
			if (value == "Masters1")
				return "Masters 1";
			if (value == "Masters2")
				return "Masters 2";
			if (value == "Masters3")
				return "Masters 3";
			if (value == "Masters4")
				return "Masters 4";
			return value.toString();
		}
	}
}

SetPickerCallback = function (pickerCallback)
{
	window.pickerCallback = pickerCallback;
}

