var BrowserDetect = {
	init: function () {
		this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
		this.version = this.searchVersion(navigator.userAgent)
			|| this.searchVersion(navigator.appVersion)
			|| "an unknown version";
		this.OS = this.searchString(this.dataOS) || "an unknown OS";
	},
	searchString: function (data) {
		for (var i=0;i<data.length;i++)	{
			var dataString = data[i].string;
			var dataProp = data[i].prop;
			this.versionSearchString = data[i].versionSearch || data[i].identity;
			if (dataString) {
				if (dataString.indexOf(data[i].subString) != -1)
					return data[i].identity;
			}
			else if (dataProp)
				return data[i].identity;
		}
	},
	searchVersion: function (dataString) {
		var index = dataString.indexOf(this.versionSearchString);
		if (index == -1) return;
		return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
	},
	dataBrowser: [
		{ 	string: navigator.userAgent,
			subString: "OmniWeb",
			versionSearch: "OmniWeb/",
			identity: "OmniWeb"
		},
		{
			string: navigator.vendor,
			subString: "Apple",
			identity: "Safari"
		},
		{
			prop: window.opera,
			identity: "Opera"
		},
		{
			string: navigator.vendor,
			subString: "iCab",
			identity: "iCab"
		},
		{
			string: navigator.vendor,
			subString: "KDE",
			identity: "Konqueror"
		},
		{
			string: navigator.userAgent,
			subString: "Firefox",
			identity: "Firefox"
		},
		{
			string: navigator.vendor,
			subString: "Camino",
			identity: "Camino"
		},
		{		// for newer Netscapes (6+)
			string: navigator.userAgent,
			subString: "Netscape",
			identity: "Netscape"
		},
		{
			string: navigator.userAgent,
			subString: "MSIE",
			identity: "Explorer",
			versionSearch: "MSIE"
		},
		{
			string: navigator.userAgent,
			subString: "Gecko",
			identity: "Mozilla",
			versionSearch: "rv"
		},
		{ 		// for older Netscapes (4-)
			string: navigator.userAgent,
			subString: "Mozilla",
			identity: "Netscape",
			versionSearch: "Mozilla"
		}
	],
	dataOS : [
		{
			string: navigator.platform,
			subString: "Win",
			identity: "Windows"
		},
		{
			string: navigator.platform,
			subString: "Mac",
			identity: "Mac"
		},
		{
			string: navigator.platform,
			subString: "Linux",
			identity: "Linux"
		}
	]

};
BrowserDetect.init();

Array.prototype.each = function(f, rev){
	if (!rev) {
		for ( var i = 0; i < this.length; i++ ) {
			if (f(this[i], i))
				break
		}
	}
	else {
		for ( var i = this.length - 1; i >= 0; i-- ) {
			if (f(this[i], i))
				break
		}
	}
}


dev1Application = {
	latestMove : {x:0, y:0},
	is_admin : false,
	uid : 0,
	oldUrl : '',
	baseUrl : null,
	config : {
		autoload : 'cms/view/__home__', //'fabrics/list',
		stateControl : {
			fakeUrl : 'http://pottery.rigorka.net/w1/fake.php',
			baseUrls : [ // MUST end with '/'
				'http://www.worcestershireceramics.org/',    
				'http://worcestershireceramics.org/',
				'http://localhost:3000/',
				'http://10.10.0.32:3000/',
				'http://pottery.rigorka.net/w1/',
				'http://www.pottery.rigorka.net/w1/',
				'http://pottery.rigorka.net:3001/',
				'http://pottery.rigorka.net/',
				'http://photo.rigorka.net/'
			]
		},
		menu : {
			//contentsUrl : 'javascripts/dev1scripts/menu.json' //'modules/menu/menu.json'
			contentsUrl : 'menus/get'
		},
		imagesDir : 'images/dev1images'
	},
	start : function (){
		var BusyCursor = document.getElementById('dev1Application-dro4ilka-img');
		document.body.onclick = document.body.onmousemove = function(evt){
			evt = evt || window.event;
			evt = dev1Application.moduleAPI.evt.getPageXY(evt);
			dev1Application.latestMove = evt;
			
			BusyCursor.style.left = (evt.x + 10) + 'px';
			BusyCursor.style.top  = (evt.y + 10) + 'px';
			
			
			return true;
		}
		document.getElementById('help-link').onclick = dev1Application.Help.helpMe;
		try {
			function doUrlCheck(){
				clearInterval(urlCheckIntrvl)
				do {
					if (dev1Application.oldUrl != window.location.href){
						if (window.location.href.indexOf('#') == -1)
							break
						dev1Application.oldUrl = window.location.href
						var sModuleUrl = dev1Application.oldUrl.replace(/.*#/, '')
						dev1Application.executeAction(sModuleUrl)
					}
				}
				while (false)
				
				var footer = document.getElementById('the-very-footer')
				var itable = document.getElementById('invisible-table')
				var y = parseInt(itable.style.height || itable.offsetHeight) + 200
				
				if (y < 770)
					y = 770
				
				
				footer.style.top = y + 'px'
				footer.style.left = '0px'
				
				urlCheckIntrvl = setInterval(doUrlCheck, 1000)
			}
			var urlCheckIntrvl = setInterval(doUrlCheck, 1000);
			
			//this.loadMenu();
			this.applyLoginActions();
			
			
			this.stateManagement.restoreStateFromURL(location.href);
			
			Ext.get('body-element').fadeIn({
				duration : 3,
				display: 'block'
			});
			
			
			
			var applyResize = window.onresize = function(){
				var winW = parseInt(window.innerWidth || document.body.offsetWidth)
				var winH = parseInt(window.innerHeight || document.body.offsetHeight)
				
				var invTblW = winW - 270
				document.getElementById('invisible-table').style.width = invTblW + 'px'
			}
			applyResize()
		}
		catch (e) {
			dev1Application.Exception(e);
		}
	},
	ExceptionLog : [],
	Exception : function(e){
		Ext.Msg.alert('Oops...', 'Exception ' + e);
		//alert('Exception ' + e);
		this.ExceptionLog.push(e + '');
		
		Ext.Msg.alert('Exception log', '<textarea rows="10" cols="80">' + this.ExceptionLog + '</textarea>')
		//alert('<textarea rows="10" cols="80">' + this.ExceptionLog + '</textarea>')
		
		
		//dev1Application.executeAction('javascripts/dev1scripts/applets/feedback.json');
	},
	applyLoginActions : function(){
		var loginLink = document.getElementById('login-link');
		function applyLoginLink(){
			function forPublic(){
				return {
					caption : 'Log in',
					onclick : function(evt){
						evt = dev1Application.moduleAPI.evt.getPageXY(evt || window.event);
						
						var wnd = dev1Application.moduleAPI.dialog.open();
						wnd.setPos(evt.x - 200, evt.y, true);
						
						wnd.className = 'login-actions-window';
						var loginTable = wnd.appendChild(document.createElement('table'));
						var tr = loginTable.insertRow(-1);
						var td = tr.insertCell(-1);
						td.innerHTML = 'User name:';
						td = tr.insertCell(-1);
						td.innerHTML = '<input type="text" name="application-authentication-username" id="application-authentication-username" />';
						
						tr = loginTable.insertRow(-1);
						td = tr.insertCell(-1);
						td.innerHTML = 'Password: ';
						td = tr.insertCell(-1);
						td.innerHTML = '<input type="password" name="application-authentication-password" id="application-authentication-password" />';
						
						tr = loginTable.insertRow(-1);
						td = tr.insertCell(-1);
						var loginBtn = td.appendChild(document.createElement('button'));
						loginBtn.innerHTML = 'Log in';
						
						loginBtn.onclick = function(){
							var parameters = {
								"username" : document.getElementById('application-authentication-username').value,
								"password" : document.getElementById('application-authentication-password').value
							}
							Ext.Ajax.request({
								url : '/users/login?js=1',
								method : 'post',
								params : parameters,
								success : function(response, options) {
									oResponse = Ext.util.JSON.decode(response.responseText);
									if (oResponse.error) {
										Ext.Msg.alert('error: ' + oResponse.error);
									}
									else {
										//Ext.Msg.alert('', oResponse.message);
									}
									applyLoginLink();
									dev1Application.moduleManagement.reloadModule();
									//dev1Application.reloadMenu();
									
								}
							});
						}
						td = tr.insertCell(-1);
						var cancelBtn = td.appendChild(document.createElement('button'));
						cancelBtn.innerHTML = 'Cancel';
						cancelBtn.onclick = function(){
							wnd.close();
						}
						document.getElementById('application-authentication-username').focus();
					}
				}
			}
			function forRegged(userName){
				return {
					onclick : function(){
						
						Ext.Ajax.request({
							url : '/users/logout?js=1',
							success : function(){
								applyLoginLink();
								dev1Application.executeAction(dev1Application.config.autoload);
								//dev1Application.moduleManagement.reloadModule();
								//dev1Application.reloadMenu();
							}
						});
					},
					caption : 'Log out ' + userName
				}
			}
			Ext.Ajax.request({
				url : '/users/who_am_i?js=1',
				success : function(response,options){
					var oResponse = Ext.util.JSON.decode(response.responseText);
					dev1Application.is_admin = oResponse.is_admin;
					dev1Application.uid = oResponse.id;
					
					
					var oLogin;
					if (oResponse.id != 0) {
						oLogin = forRegged(oResponse.name);
					}
					else {
						oLogin = forPublic();
					}
					loginLink.innerHTML = oLogin.caption;
					loginLink.onclick = oLogin.onclick;
					
					dev1Application.reloadMenu();
				}
			});
		}
		
		applyLoginLink();
		//dev1Application.reloadMenu();
	},
	stateManagement : {
		restoreStateFromURL : function(absUrl){
			var moduleUrl = this.getModuleUrlByAbsoluteUrl(absUrl);
			moduleUrl = moduleUrl.replace('#', '');
			
			
			if (moduleUrl.trim() == '') {
				moduleUrl = dev1Application.config.autoload;
			}
			
			dev1Application.moduleManagement.loadModule(moduleUrl);
		},
		getModuleUrlByAbsoluteUrl : function(absUrl){
			var baseUrls = dev1Application.config.stateControl.baseUrls;
			var effectiveBaseUrl = null;
			
			for (i = 0; i < baseUrls.length; i++){
				regEx = new RegExp("^" + baseUrls[i]);
				if (absUrl.match(regEx)){
					effectiveBaseUrl = baseUrls[i];
					break;
				}
			}
			
			if (effectiveBaseUrl == null) {
				dev1Application.Exception('could not determine base url');
			}
			
			dev1Application.baseUrl = effectiveBaseUrl;
			
			return absUrl.replace(new RegExp("^" + effectiveBaseUrl.replace('?', '\\?')), '');
		}
	},
	moduleAPI : {
		cookies : {
			setCookie : function(name,value,days) {
				if (days) {
					var date = new Date();
					date.setTime(date.getTime()+(days*24*60*60*1000));
					var expires = "; expires="+date.toGMTString();
				}
				else var expires = "";
				document.cookie = name+"="+value+expires+"; path=/";
			},
			getCookie : function(name) {
				var nameEQ = name + "=";
				var ca = document.cookie.split(';');
				for(var i=0;i < ca.length;i++) {
					var c = ca[i];
					while (c.charAt(0)==' ') c = c.substring(1,c.length);
					if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
				}
				return '';
			},
			rmCookie : function(name) {
				dev1Application.moduleAPI.cookies.setCookie(name,"",-1);
			}
		},
		humanity : {
			singularize : function(many) {
				if (many == 'Bibliographies' || many == 'Bibliography')
					return 'Reference'
				if (many.match(/(.*)[ies]/))
					many.replace(/(.*)[ies]/, '$1y');
				
				return many.replace(/(.*)[es|s]/, '$1');
			},
			pluralize : function(one) {
				if (one == 'Reference')
					return 'Bibliography'
				if (one.match(/(.*)y/))
					return one.replace(/(.*)y/, '$1ies');
				
				return one + 's';
			}
		},
		document : {
			createElement : function(elname){
				elname = elname || 'span'
				var el = document.createElement(elname)
				var stillIsOver = false
				var tipDiv = null
				el.setTip = function(tip){
					this.setAttribute('tip', tip)
				}
				el.onmouseover = function(evt) {
					var xy = dev1Application.moduleAPI.evt.getPageXY(evt || window.event)
					
					var tip = this.getAttribute('tip')
					if (!tip)
						return
					tipDiv = document.body.appendChild(document.createElement('span'))
					
					tipDiv.style.display = 'none'
					
					tipDiv.style.top  = (xy.y + 3) + 'px'
					tipDiv.style.left = (xy.x + 10) + 'px'
					tipDiv.style.border = '1px solid #ddd'
					tipDiv.style.position = 'absolute'
					tipDiv.style.background = '#ccf'
					tipDiv.style.fontStyle = 'italic'
					tipDiv.style.fontWeight = 'bold'
					tipDiv.style.textAlign = 'center'
					tipDiv.style.width  = '100px'
					
					tipDiv.innerHTML = tip
					
					stillIsOver = true
					setTimeout(function(){
						if (!stillIsOver)
							return
						tipDiv.style.display = 'block'
						setTimeout(function(){
							if (tipDiv && tipDiv.parentNode) tipDiv.parentNode.removeChild(tipDiv)
						}, 5000)
					}, 1000)
					
				}
				el.onmouseout = function(){
					if (!tipDiv)
						return
					stillIsOver = false
					tipDiv.parentNode.removeChild(tipDiv)
					tipDiv = null
				}
				el.setInnerHtml = function(html){
					this.innerHTML = html
				}
				return el
			}
		},
		evt : {
			getPageXY : function(evt){
				return { x : (evt.pageX || (evt.clientX + document.body.scrollLeft)), y : (evt.pageY || (evt.clientY + document.body.scrollTop))};
			},
			isInside : function(lt, rb, coords){
				return (lt.x < coords.x) && (lt.y < coords.y) && (rb.x > coords.y) && (rb.y > coords.y);
			}
		},
		dialog : {
			isOpen : false,
			open : function(){
				var tinted = [
					document.getElementById('the-very-footer'),
					document.getElementById('invisible-table'),
					document.getElementById('global-tint')
				]
				for (var i = 0; i < tinted.length; i++){
					var t = tinted[i]
					t.style.opacity = '0.6'
					//t.style.filter = 'alpha(opacity = 60)'
				}
				
				dev1Application.moduleAPI.dialog.isOpen = true
				
				var diaRoot = document.getElementById('dev1dialog')
				dev1Application.moduleAPI.util.dropSubNodes({ node : diaRoot })
				var userArea = diaRoot.appendChild(document.createElement('div'))
				diaRoot.style.top = (parseInt(document.body.scrollTop) + 50) + 'px'
				diaRoot.style.left = '230px'
				
				//Ext.get('central-panel-content').fadeOut();
				Ext.get('dev1dialog').fadeIn()
				userArea.setOnClose = function(fn){
					dev1Application.moduleAPI.dialog.onclose = fn
				}
				userArea.setPos = function(x, y, ignoreScroll){
					if (!ignoreScroll) {
						x = parseInt(document.body.scrollLeft) + parseInt(x)
						y = parseInt(document.body.scrollTop ) + parseInt(y)
					}
					
					x += 'px'
					y += 'px'
					diaRoot.style.top  = y
					diaRoot.style.left = x
				}
				userArea.setSize = function(w, h){
					w = parseInt(w)
					h = parseInt(h)
					
					if (w == NaN)
						w = 'auto'
					else
						w += 'px'
					if (h == NaN)
						h = 'auto'
					else
						h += 'px'
					
					try {
						this.style.width  = w
					}catch (e) { this.style.width = 'auto' }
					try {
						this.style.height = h
					} catch (e) { this.style.height = 'auto' }
				}
				userArea.close = function(){
					dev1Application.moduleAPI.dialog.close()
				}
				return userArea
			},
			onclose : function(){},
			close : function(){
				var tinted = [
					document.getElementById('the-very-footer'),
					document.getElementById('invisible-table'),
					document.getElementById('global-tint')
				]
				for (var i = 0; i < tinted.length; i++){
					var t = tinted[i]
					t.style.opacity = '1.0'
					//t.style.filter = 'alpha(opacity = 100)'
				}
				
				dev1Application.moduleAPI.dialog.onclose();
				dev1Application.moduleAPI.dialog.onclose = function(){};
				if (!dev1Application.moduleAPI.dialog.isOpen)
					return;
				dev1Application.moduleAPI.dialog.isOpen = false;
				Ext.get('dev1dialog').fadeOut();
				//Ext.get('central-panel-content').fadeIn();
				dev1Application.moduleAPI.util.dropSubNodes({ id : 'dev1dialog' });
			}
		},
		util : {
			highlight : function(node, text){
				if (!node.childNodes) {
					if (text == '' && node.origHTML) {
						node.innerHTML = node.origHTML
					}
					else{
						if (node.className == 'highlighted-div')
							return;
						if (!node.origHTML){
							node.origHTML = node.innerHTML || '';
						}
						var start = node.origHTML.toLowerCase().indexOf(text.toLowerCase())
						if (start == -1)
							return;
						var end = start + text.length;
						
						var sBefore = node.origHTML.substr(0, start);
						var sAfter = node.origHTML.substr(end);
						var sHigh = node.origHTML.substr(start, text.length);
						
						node.innerHTML = sBefore + '<div class="highlighted-div">' + sHigh + '</div>' + sAfter;
						
					}
					return;
				}
				for (var i = 0; i < node.clildNodes.length; i++) {
					dev1Application.moduleAPI.util.highlight(node.childNodes[i], text);
				}
			},
			findPosition : function(obj) {
				var curleft = curtop = 0;
				if (obj.offsetParent) {
					do {
						curleft += obj.offsetLeft;
						curtop += obj.offsetTop;
					} while (obj = obj.offsetParent);
				}
				return { x : curleft, y : curtop };
			},
			dropSubNodes : function(nodeObj) {
				if (!nodeObj) {
					return null;
				}
				var node = null;
				if (nodeObj.id) {
					node = document.getElementById(nodeObj.id);
				}
				else if (nodeObj.node) {
					node = nodeObj.node;
				}
				if (!node){
					alert('dropSubNodes failed');
					return null;
				}
				
				var childNodes = node.childNodes;
				
				for (var i = childNodes.length-1; i >= 0 ; i--) {
					childNodes[i].parentNode.removeChild(childNodes[i]);
					//node.removeChild(childNodes[i]);
				}
				
				return node;
			},
			parseBB : function(bbCode){
				if (!bbCode || !bbCode.replace)
					return '';
				return bbCode
					.replace(/&/g, '&amp;')
					.replace(/</g, '&lt;')
					.replace(/>/g, '&gt;')
					.replace(/\[([^\]]+)\]/g, '<$1>')
					.replace(/\[\/([^\]]+)\]/g, '</$1>')
					.replace(/\n/g, '<br/>\n')
					.replace(/((http|https):\/\/[^\s]+)/g, '<a href="$1" style="background:transparent url(/images/dev1images/external-link.png) no-repeat scroll right center; padding-right:13px; color: #3366BB;">$1</a>');
			}
		},
		setCaption : function(newCaption){
			dev1Application.fullTitle = newCaption
			
			document.title = 'Worcestershire pottery' + (newCaption ? ' - ' + newCaption.replace(/<a[^>]+>/g, '').replace('</a>', '') : '');
			
			document.getElementById('applet-header-text').innerHTML = newCaption;
			//document.getElementById('applet-header-text').style.display = 'block';
		},
		getCaption : function() {
			return document.getElementById('applet-header-text').innerHTML;
		},
		setContentHTML : function(newContent) {
			document.getElementById('central-panel-content').innerHTML = newContent;
		},
		getContentHTML : function(){
			return document.getElementById('central-panel-content').innerHTML;
		},
		getAppletActionsArea : function(){
			return document.getElementById('applet-actions');
		}
	},
	moduleManagement : {
		appletPool : {
			m_Pool : {},
			loader : function(url, data, pool){
				this.url = url;
				this.pool = pool;
				this.data = data;
				
				this.getAppletStarter = function(url, data, pool){
					return function(response, options){
						pool[url] = response.responseText;
						dev1Application.moduleManagement.appletPool.launchApplet(url, data);
						
						Ext.Ajax.on('beforerequest', function(){}, this);
						Ext.Ajax.on('requestcomplete', function(){}, this);
					}
				}
				appPool = this;
				
				Ext.Ajax.on('beforerequest', dev1Application.Blinds.addBlind, this);
				Ext.Ajax.on('requestcomplete', dev1Application.Blinds.subBlind, this);
				Ext.Ajax.request({
					url : appPool.url,
					success : appPool.getAppletStarter(appPool.url, appPool.data, appPool.pool)
				});
			},
			launchApplet : function(url, data, ignoreCache){
				var actionsPanel = dev1Application.moduleAPI.getAppletActionsArea();
				var children = actionsPanel.childNodes;
				for (var i = children.length - 1; i >= 0; i--){
					actionsPanel.removeChild(children[i]);
				}
				
				if (this.m_Pool[url]) { // && !ignoreCache){
					var applet = Ext.util.JSON.decode(this.m_Pool[url]);
					dev1Application.moduleManagement.activeApplet = applet;
					applet.data = data;
					applet.start();
					
					dev1Application.ignoreExecuteAction = false
					setTimeout(function(){
						Ext.get('the-very-footer').fadeIn()
					}, 2000)
					setTimeout(function(){
						Ext.get('invisible-table').fadeIn()
					}, 2000)
					return;
				}
				
				new this.loader(url, data, this.m_Pool)
			}
		},
		reloadModule : function(){
			dev1Application.executeAction(dev1Application.moduleManagement.activeModuleUrl);
		},
		activeModuleUrl : '',
		activeApplet : null,
		loadModule : function(modulePath, params){
			dev1Application.moduleManagement.activeModuleUrl = modulePath;
			//alert(this.activeApplet);
			if (this.activeApplet) {
				this.activeApplet.stop();
			}
			var ModuleManagement = this;
			var moduleUrl = dev1Application.baseUrl + modulePath.replace(/^\//, '');
			
			if (moduleUrl.indexOf('?') == -1) {
				moduleUrl += '?js=1';
			}
			else {
				moduleUrl += '&js=1';
			}
			
			if (!params) {
				dev1Application.currentTranId = Ext.Ajax.request({
					url : moduleUrl,
					success : ModuleManagement.moduleJSONReady,
					failure : ModuleManagement.moduleJSONFailure
				});
			}
			else {
				dev1Application.currentTranId = Ext.Ajax.request({
					url : moduleUrl,
					success : ModuleManagement.moduleJSONReady,
					failure : ModuleManagement.moduleJSONFailure,
					method : 'POST',
					params : params
				});
			}
		},
		
		moduleJSONReady : function(response, options){
			
			try {
				Ext.Ajax.abort(dev1Application.currentTranId)
			}
			catch (e){}
			
			var json = response.responseText;
			var moduleObj = Ext.util.JSON.decode(json);
			if (moduleObj.error){
				dev1Application.Exception('while loading module: ' + moduleObj.error);
				return;
			}
			var data = moduleObj.content.moduleData;
			data.moduleUrl = options.url.replace(new RegExp('^' + dev1Application.baseUrl), '');
			
			
			var codeUrl = dev1Application.baseUrl + moduleObj.content.codeUrl;
			
			var applet = dev1Application.moduleManagement.appletPool.launchApplet(codeUrl, data, true);
		},
		moduleJSONFailure : function(response, options){
			this.activeApplet = null;
			dev1Application.Blinds.subBlind();
			
			Ext.Msg.alert('Failed to fetch data from server', 'Here some technical info:<br/>\n' +
				'Server said: <br/><textarea rows="10" cols="80">' + response.responseText + '</textarea><br/>\n'+
				'Previous problems (Exception log): <br/>\n<textarea rows="10" cols="80">' + dev1Application.ExceptionLog.join('\n') + '</textarea>'
			)
			
			//Ext.Msg.alert('Error', "Sorry, we're experiencing technical problems.\n You can use our feedback form to submit error report.");
			//dev1Application.executeAction("javascripts/dev1scripts/applets/feedback.json");
		}
	},
	HistoryManager : {
		histMakerOnload : function(iframe){
			try {
				var loc = false;
				if (iframe.contentDocument)
					loc = iframe.contentDocument.location.href;
				else
					loc = iframe.src;
				state = parseInt(loc.replace(/^.*\?state=/, ''));
				
				dev1Application.HistoryManager.goTo(state);
				return true;
			}
			catch (e) {
				return false;
			}
		},
		current : -1,
		stack : [],
		histMaker : null,
		goTo : function (state){
			return;
			if (state >= dev1Application.HistoryManager.stack.length) {
				return;
			}
			dev1Application.executeAction(dev1Application.HistoryManager.stack[state], false);
		},
		push : function (moduleUrl) {
			dev1Application.HistoryManager.histMaker = document.getElementById('history-maker');
			
			dev1Application.HistoryManager.current++;
			dev1Application.HistoryManager.stack[dev1Application.HistoryManager.current] = moduleUrl;
			
			var newFakeUrl = (dev1Application.config.stateControl.fakeUrl + '?state=' + dev1Application.HistoryManager.current);
			
			dev1Application.HistoryManager.histMaker.src = newFakeUrl;
		},
		back : function () {
			if (current < 0) {
				dev1Application.HistoryManager.current--;
				dev1Application.executeAction(dev1Application.HistoryManager.stack[dev1Application.HistoryManager.current]);
				return true;
			}
			return false;
		},
		forward : function () {
			if (dev1Application.HistoryManager.current < dev1Application.HistoryManager.stack.length) {
				dev1Application.HistoryManager.current++;
				dev1Application.executeAction(dev1Application.HistoryManager.stack[dev1Application.HistoryManager.current]);
				return true;
			}
			return false;
		}
	},
	ignoreExecuteAction : false,
	
	currentTranId : null,
	
	executeAction : function(action, withPushToHistory, params, noHist){
		
		try {
			Ext.Ajax.abort(dev1Application.currentTranId)
		}
		catch (e){}
		
		dev1Application.ignoreExecuteAction = true
		
		if (!noHist && BrowserDetect.browser == "Explorer") {
			var ieIFrame = document.getElementById('history-maker')
			ieIFrame.src = '/iehistory/hist.html?' + action
		}
		
		document.getElementById('fucking-ie-hack').name = action
		dev1Application.moduleAPI.dialog.close();
		if (typeof(action) == 'string'){
			Ext.get('invisible-table').fadeOut()
			Ext.get('the-very-footer').fadeOut()
			if (!action.match(/delete/)) {
				if (window.location.href.indexOf('#') == -1) {
					window.location.href = dev1Application.baseUrl + '#' + action;
				}
				else {
					window.location.href = window.location.href.replace(/#.*/, '#'+action);
				}
				dev1Application.oldUrl = window.location.href;
				document.getElementById('action-direct-link').href = dev1Application.baseUrl + '#' + action;
				//if (withPushToHistory){
				//	dev1Application.HistoryManager.push(action);
				//}
			}
			//Ext.get('invisible-table').fadeIn()
			return dev1Application.moduleManagement.loadModule(action, params);
		}
	},
	Menu : {
		appendMenu : function(to, what, ignoreTextInMenu){
			if (what.adminOnly && !dev1Application.is_admin){
				to.parentNode.removeChild(to)
				return
			}
			if (what.authOnly && dev1Application.uid == 0) {
				to.parentNode.removeChild(to)
				return
			}
			
			switch (what.type){
				case 'menu':
					var div = document.createElement('div');
					var ul = document.createElement('ul');
					
					if (!ignoreTextInMenu) {
						var menuCaption = document.createElement('div');
						var anchor = document.createElement('a');
						
						menuCaption.appendChild(anchor);
						anchor.className = 'menu-collapsed';
						
						anchor.innerHTML = what.text;
						anchor.onclick = function(){
							if (ul.style.display == 'none'){
								ul.style.display = 'block';
								anchor.className = 'menu-expanded';
								if (what.href) {
									window.location.href = what.href;
								} else if (what.action) {
									dev1Application.executeAction(what.action);
								}
								
							}
							else{
								ul.style.display = 'none';
								anchor.className = 'menu-collapsed';
							}
						}
						div.appendChild(anchor);
					}
					
					
					
					for (var i = 0; i < what.items.length; i++) {
						var li = document.createElement('li');
						ul.appendChild(li);
						dev1Application.Menu.appendMenu(li, what.items[i]);
					}
					
					div.appendChild(ul);
					if(!ignoreTextInMenu){
						ul.style.display = 'none';
					}
					
					to.appendChild(div);
					
					return div;
				break;
				case 'link':
					var anchor = document.createElement('a');
					anchor.className = 'menu-plain-item'
					anchor.href = what.href;
					anchor.innerHTML = what.text;
					to.appendChild(anchor);
					
					return anchor;
				break;
				case 'action':
					var anchor = document.createElement('a');
					//anchor.href = '#';
					anchor.className = 'menu-plain-item'
					anchor.innerHTML = what.text;
					anchor.onclick = function(){
						dev1Application.executeAction(what.action, true);
					}
					to.appendChild(anchor);
					
					return anchor;
				break;
				case 'image':
					var div = document.createElement('div');
					var img = document.createElement('img');
					img.src = what.src;
					img.style.width = what.width + 'px';
					img.style.height = what.height + 'px';
					img.style.paddingLeft = what.paddingLeft + 'px';
					
					div.appendChild(img);
					to.appendChild(div);
					return div;
				break;
				default:
					dev1Application.Exception('Bad menu item type ' + what.type);
			}
		},
		loadSuccess : function(response, options){
			//alert('menu::loadsuccess');
			var oResponse = Ext.util.JSON.decode(response.responseText);
			if (oResponse.error){
				dev1Application.Menu.loadFailure(oResponse.error);
				return;
			}
			
			var menuContents = oResponse.content.menuPanels;
			var menuPanel = Ext.get('west-panel-menu');
			
			for (var i = 0; i < menuContents.length; i++){
				var panel = dev1Application.Menu.appendMenu(menuPanel, menuContents[i], true);
				panel.className = 'submenu-panel';
			}
		},
		loadFailure : function(error) {
			alert('failed to load menu');
		}
	},
	loadMenu : function(){
		Ext.Ajax.request({
			url: dev1Application.config.menu.contentsUrl,
			success: this.Menu.loadSuccess,
			failure: this.Menu.loadFailure
		});
	},
	reloadMenu : function(){
		var menuPanel = document.getElementById('west-panel-menu');
		var children  = menuPanel.childNodes;
		for (var i = children.length -1 ; i >= 0 ; i--){
			menuPanel.removeChild(children[i]);
		}
		this.loadMenu();
	},
	Blinds : {
		addBlind : function(){
			document.getElementById('dev1Application-dro4ilka-img').style.display = 'block'
		},
		subBlind : function(){
			var blind = document.getElementById('dev1Application-blind-shtorko');
			if (blind)
				blind.parentNode.removeChild(blind);
			document.getElementById('dev1Application-dro4ilka-img').style.display = 'none'
		}
	},
	Help : {
		helpMe : function(evt){
			evt = evt || window.event;
			var xy = dev1Application.moduleAPI.evt.getPageXY(evt);
			
			var wnd = dev1Application.moduleAPI.dialog.open();
			wnd.setPos(xy.x - 600, xy.y);
			var helpWnd = wnd.appendChild(document.createElement('div'));
			helpWnd.className = 'help-pan-window';
			
			var hlpHead = helpWnd.appendChild(document.createElement('div'));
			var hlpBody = helpWnd.appendChild(document.createElement('div'));
			var hlpControls = helpWnd.appendChild(document.createElement('div'));
			
			var editHelpBtn = hlpControls.appendChild(document.createElement('button'))
			editHelpBtn.style.visibility = 'hidden'
			editHelpBtn.innerHTML = 'Edit this help page'
			
			
			var closeBtn = hlpControls.appendChild(document.createElement('button'));
			var hlpBottom = helpWnd.appendChild(document.createElement('div'));
			
			hlpHead.id = "help-head";
			hlpBody.id = "help-body";
			hlpControls.id = "help-controls";
			hlpBottom.id = "help-bottom";
			
			
			closeBtn.innerHTML = 'Close help window';
			closeBtn.style.float = 'right'
			closeBtn.onclick = function(){
				wnd.close();
			}
			
			var helpItem = dev1Application.moduleManagement.activeModuleUrl;
			helpItem = helpItem.replace(/^([^\/]+\/[^\/]+)\/.*$/, '$1').replace('/', '__');
			
			if (helpItem == 'cms__view') {
				helpItem = dev1Application.moduleManagement.activeModuleUrl.replace(/\//g, '__').replace(/\s/g, '_')
			}
			
			if (helpItem == 'cms__view____home__') {
				helpItem = 'cms__view__worcestershire_on-line_ceramic_database'
			}
			
			function createHelpPage (pageTitle){
				var action = 'cms/add?page_title=' + pageTitle
				dev1Application.executeAction(action)
			}
			function editHelpPage (pageTitle, o) {
				//alert('edit page ' + pageTitle + '\n' + o.content.moduleData.fields.page_id)
				var action = 'cms/show/' + o.content.moduleData.fields.page_id
				dev1Application.executeAction(action)
			}
			
			//editHelpBtn.onclick = function (){ editHelpPage('help__' + helpItem) }
			
			Ext.Ajax.request({
				url : '/cms/view/help__' + helpItem + '?js=1',
				success : function(response, options) {
					if (Ext.util.JSON.decode(response.responseText).content.moduleData.fields){
						//try {
						sHelpText = Ext.util.JSON.decode(response.responseText).content.moduleData.fields.content;
						
						//alert(sHelpText)
						
						hlpBody.innerHTML = sHelpText;
						/*}
						catch (e){
							//alert(e)
						}*/
						
						
						editHelpBtn.onclick = function (){ editHelpPage('help__' + helpItem, Ext.util.JSON.decode(response.responseText)) }
					}
					else {
						hlpBody.innerHTML = 'Sorry, no help for this page';
						editHelpBtn.innerHTML = 'Create this help page'
						editHelpBtn.onclick = function() { createHelpPage('help__' + helpItem) }
					}
					if (dev1Application.is_admin) {
						editHelpBtn.style.visibility = 'visible'
					}
				},
				failure : function() {
					hlpBody.innerHTML = 'Sorry, no help for this page';
					editHelpBtn.innerHTML = 'Create this help page'
					editHelpBtn.onclick = function() { createHelpPage('help__' + helpItem) }
					if (dev1Application.is_admin) {
						editHelpBtn.style.visibility = 'visible'
					}
				}
			});
		}
	}
}


Ext.onReady(function(){
	dev1Application.start();
});
