var menuAnimationQueue = null;
var menuAnimOut;
var menuAnimIn;
var menuStore = null;
var pageAnimOut;
var pageAnimIn;
var pageAnimationQueue = null;

var innerBody = null;

// for goods popUp
var winWidth = 860;
var winHeight = 760;

var pageAnimationEnabled = false;

// Dojo modules init
function dojoInit()
{
	// init left menu
	// init animation
	if (dojo.byId('submenu'))
	{
		menuAnimOut = dojo.fx.wipeOut({node: "submenu",duration: 250});
		menuAnimIn = dojo.fx.wipeIn({node: "submenu",duration: 500});
	
		menuAnimationQueue = new ultima.AnimationQueue();
	
		menuStore = new dojo.data.ItemFileReadStore(
			{
				data: menuDataStore
			}
		);
	}

	if(typeof menuDataStore != 'undefined' && menuDataStore != null)
	{
		menuStore = new dojo.data.ItemFileReadStore(
			{
				data: menuDataStore
			}
		);
	}

	if (dojo.byId('innerBody') && pageAnimationEnabled)
	{
		pageAnimOut = dojo.fadeOut({node: "innerBody",duration: 250});
		pageAnimIn = dojo.fadeIn({node: "innerBody",duration: 500});
		
		pageAnimationQueue = new ultima.AnimationQueue();
	}
	
	
	innerBody =
	{
		_handlePageAnimationEndQueue: null,
		_requestEvents: Array(),
		_deferredList: Array(),
		//page animation end in endAnimationQueue
		
		// Mutex
		_isLoading: false,
		// Список загружаемых страниц
		_loadingQueue: Array(),
		// Время последнего вызова загрузки. Чтобы показать только последнюю страницу
//		_lastCallTimestamp: 0,
		// Функции вызываемые после загрузки страницы
		_onEndLoadFunc: Array(),
		// На странице проигрывается анимация
		_isPageAnimationPlaying: false,

		// Начало анимации (затемнение)
		_startPageAnimation: function()
		{
			if (pageAnimationEnabled)
			{
				this._isPageAnimationPlaying = true;
				pageAnimationQueue.addAnimation(pageAnimOut);
				this._handlePageAnimationEndQueue = dojo.connect(pageAnimationQueue, "onEndQueue", this, "onEndAnimationQueueIn");
			}
			else
			{
				dojo.removeClass(dijit.byId('innerBody').domNode, "dijitVisible");
                dojo.addClass(dijit.byId('innerBody').domNode, "dijitHidden");
				dojo.removeClass(dijit.byId('innerBodyWait').domNode, "dijitHidden");
                dojo.addClass(dijit.byId('innerBodyWait').domNode, "dijitVisible");
			}
		},
		// Конец анимации (затемнение)
		_endPageAnimation: function(type)
		{
			if (pageAnimationEnabled)
			{
				if (this._handlePageAnimationEndQueue != null)
				{
					dojo.disconnect(this._handlePageAnimationEndQueue);
					this._handlePageAnimationEndQueue = null;
					
					if (type == "in")
					{
						dojo.removeClass(dijit.byId('innerBody').domNode, "dijitVisible");
		                dojo.addClass(dijit.byId('innerBody').domNode, "dijitHidden");
						dojo.removeClass(dijit.byId('innerBodyWait').domNode, "dijitHidden");
		                dojo.addClass(dijit.byId('innerBodyWait').domNode, "dijitVisible");
					}
					this._isPageAnimationPlaying = false;
				}
			}
		},
		
		// До загрузки страницы
		onEndAnimationQueueIn: function()
		{
			this._endPageAnimation("in");
		},
		// После загрузки страницы
		onEndAnimationQueueOut: function()
		{
			this._endPageAnimation("out");
		},
		
		// Посмотрим какие событие после загрузки надо вызвать
		_onEndLoadEvents: function()
		{
			if (this._onEndLoadFunc.length > 0)
			{
				var fnName = null;
				while((fnName = this._onEndLoadFunc.pop()) != null)
				{
					if(dojo.isFunction(fnName))
					{
						fnName();
					}
					else
					{
						eval(fnName + "()");
					}
				}
			}
		},
	
		_endLoad: function(content, timestamp, isError)
		{
			// Mutex
			if (!isError)
			{
				if(dojox.timing.doLater(!this._isLoading, this)){return;}
			}
			if(dojox.timing.doLater(!this._isPageAnimationPlaying, this)){return;}
			
			this._isLoading = true;
			
			var _this = this;
			
			this.onEndAnimationQueueIn();
			
			// После того как контент загрузится, поищем событие на скролл страницы
			// Old
			dojo.removeClass(dijit.byId('innerBodyWait').domNode, "dijitVisible");
            dojo.addClass(dijit.byId('innerBodyWait').domNode, "dijitHidden");
			dojo.removeClass(dijit.byId('innerBody').domNode, "dijitHidden");
            dojo.addClass(dijit.byId('innerBody').domNode, "dijitVisible");
			if (dojo.version.major <= 1 && dojo.version.minor <= 3)
			{
				var deferred = dijit.byId("innerBody").attr("content", content);
				deferred.addOnLoad(function()
				{
					var scrollLine = dijit.byId("scrollLine");
					if (scrollLine != null)
					{
						var event = dojo.connect(scrollLine, 'pageChanged', null, 'documentsListChangePage');
						_this._requestEvents.push(event);
						scrollLine.changePage(1);
					}
				}
				);
			}
			// New
			else
			{
				var deferred = dijit.byId("innerBody");
				deferred.attr("content", content);
				deferred.onLoadDeferred.addCallback(function()
				{
					var scrollLine = dijit.byId("scrollLine");
					if (scrollLine != null)
					{
						var event = dojo.connect(scrollLine, 'pageChanged', null, 'documentsListChangePage');
						_this._requestEvents.push(event);
						scrollLine.changePage(1);
					}
				}
				);
			}

			// Анимация. Но уже в обратную сторону
			if (pageAnimationEnabled)
			{
				this._isPageAnimationPlaying = true;
				pageAnimationQueue.addAnimation(pageAnimOut);
	
				pageAnimationQueue.addAnimation(pageAnimIn);
				this._handlePageAnimationEndQueue = dojo.connect(pageAnimationQueue, "onEndQueue", this, "onEndAnimationQueueOut");
			}
			else
			{
			}
			
			this._onEndLoadEvents();
			
			if(typeof afterPageLoaded != 'undefined' && dojo.isFunction(afterPageLoaded))
			{
				afterPageLoaded();
			}

			this._isLoading = false;
		},
		
		load: function(args)
		{
			// Mutex
			if(dojox.timing.doLater(!this._isLoading, this)){return;}

			this._isLoading = true;
			this._lastCallTimestamp = new Date().getTime();
			var timestamp = this._lastCallTimestamp;
			var _this = this;
			// 
			_this._startPageAnimation();
			
			for (var i in this._requestEvents)
			{
				dojo.disconnect(this._requestEvents[i]);
			}
			this._requestEvents = Array();
			
			// Отменяем остальные загрузки
			var deferred;
			while((deferred = this._loadingQueue.pop()) != null)
			{
				if (deferred.fired == -1)
				{
					deferred.cancel();
				}
			}

			var xhrArgs =
			{
				url: "/services/gateway.php",
				handleAs: "text",
				content:
				{
					resultType: "html",
					t: new Date().getTime()
				},
				load: function(data, ioargs)
				{
					_this._endLoad(data, timestamp, false);
				},
				error: function(error, ioargs)
				{
					// Canceled load
					if (error.dojoType == "cancel")
					{
						return;
					}
					
					if (jsDebugEnable)
					{
						console.log("error: %o %o", error, ioargs);
					}
					data = "";
					if (error.responseText != null && dojo.string.trim(error.responseText).length > 0)
					{
						data = "<div>" + error.responseText + "</div>";
					}
					else
					{
						data = "<div>ошибка во время запроса</div>";
					}
					if (jsDebugEnable)
					{
						data += "<br>" + error;
					}
					_this._endLoad(data, timestamp, true);
				},
				timeout: 300000
			}
			
			// URI params
			for(var paramKey in args.params)
			{
				var data = args.params[paramKey];
				var str = "";
				if (typeof(data) == "object" && (data.length > 1 || paramKey == "params"))
				{
					for(var dataKey in data)
					{
						var d = data[dataKey];
						if (typeof(d) == "object")
						{
							str += d.key + ":" + d.value + ";";
						}
						else
						{
							str += dataKey + ":" + d + ";";
						} 
					}
				}
				else
				{
					str = data;
				}

				xhrArgs.content[paramKey] = str;
			}
			
			// Form
			if (args.form != null)
			{
				xhrArgs["form"] = args.form;
			}
			
			// Content to merge
			if (args.content != null)
			{
				xhrArgs.content = dojo.mixin(xhrArgs.content, args.content);
			}
			
			// Call the asynchronous
			var deferred = null;
			if (args.method == "get")
			{
				deferred = dojo.xhrGet(xhrArgs);
			}
			else
			{
				deferred = dojo.xhrPost(xhrArgs);
			}

			this._loadingQueue.push(deferred);
			this._isLoading = false;
		},
		
		addOnEndLoad: function(fnName)
		{
			this._onEndLoadFunc.push(fnName);
			if (!this._isLoading)
			{
				this._onEndLoadEvents();
			}
		}
	}
	
	/*
	innerBody =
	{
		//_loading: false,
		//_timestamp: 0,
		_loadedTimestamp: 0,
		_isEnding: false,
		_handlePageAnimationEndQueue: null,
		_requestEvents: Array(),
		_isPageAnimationPlaying: false,
		_onEndLoadFunc: Array(),
		_deferredList: Array(),
		//page animation end in endAnimationQueue
		
		_isLoading: false,
		_loadingQueue: Array(),
		
		_startLoad: function()
		{
			//_loading = true;
			// status
			this._isPageAnimationPlaying = true;
			pageAnimationQueue.addAnimation(pageAnimOut);
			this._handlePageAnimationEndQueue = dojo.connect(pageAnimationQueue, "onEndQueue", this, "endAnimationQueue");
		},
		
		endAnimationQueue: function()
		{
			dojo.disconnect(this._handlePageAnimationEndQueue);
			this._handlePageAnimationEndQueue = null;
			
			dijit.byId('innerBody').domNode.style.display = 'none';
			dijit.byId('innerBodyWait').domNode.style.display = 'block';
			this._isPageAnimationPlaying = false;
		},
	
		_endLoad: function(content, timestamp)
		{
			if (timestamp < this._loadedTimestamp)
			{
				return;
			}

			if(dojox.timing.doLater(!this._isPageAnimationPlaying, this)){return;}
			if(dojox.timing.doLater(!this._isEnding, this)){return;}
			
			this._loadedTimestamp = timestamp;
			
			this._isEnding = true;
			//console.log("_endLoad1", timestamp);
			// already disconnected
			if (this._handlePageAnimationEndQueue != null)
			{
				dojo.disconnect(this._handlePageAnimationEndQueue);
			}
			
			// Cancel other loading
			var deferred;
			while((deferred = this._deferredList.pop()) != null)
			{
				console.log("D:", deferred);
				if (deferred.fired == -1)
				{
					deferred.cancel();
					console.log("cancel");
				}
			}			
			
			var deferred = dijit.byId("innerBody").attr("content", content);
			var _this = this;
			deferred.addOnLoad(function()
			{
				var scrollLine = dijit.byId("scrollLine");
				if (scrollLine != null)
				{
					var event = dojo.connect(scrollLine, 'pageChanged', null, 'documentsListChangePage');
					_this._requestEvents.push(event);
					scrollLine.changePage(1);
				}
			}
			);
	
			pageAnimationQueue.addAnimation(pageAnimOut);
	
			dijit.byId('innerBodyWait').domNode.style.display = 'none';
			dijit.byId('innerBody').domNode.style.display = 'block';
	
			pageAnimationQueue.addAnimation(pageAnimIn);
			
			if (this._onEndLoadFunc.length > 0)
			{
				var fnName = null;
				while((fnName = this._onEndLoadFunc.pop()) != null)
				{
					eval(fnName + "()");
				}
			}
			
			if(typeof afterPageLoaded != 'undefined' && dojo.isFunction(afterPageLoaded))
			{
				afterPageLoaded();
			}
			//console.log("_endLoad2");
			this._isEnding = false;
			//_loading = false;
		},
		
		load: function(args)
		{
			var timestamp = new Date().getTime();
			
			if(dojox.timing.doLater(!this._isEnding, this)){return;}
			var _this = this;

			_this._startLoad();
			
			for (var i in this._requestEvents)
			{
				dojo.disconnect(this._requestEvents[i]);
			}
			this._requestEvents = Array();

			var xhrArgs =
			{
				//url: "/services/cabinet_block.php",
				url: "/services/gateway.php",
				handleAs: "text",
				content:
				{
					resultType: "html",
					t: new Date().getTime()
				},
				load: function(data, ioargs)
				{
					_this._endLoad(data, timestamp);
				},
				error: function(error, ioargs)
				{
					if (error.dojoType == "cancel")
					{
						return;
					}
					console.log("error: ", error);
					date = "";
					if (error.responseText != null && dojo.string.trim(error.responseText).length > 0)
					{
						data = "<div>" + error.responseText + "</div>";
					}
					else
					{
						data = "<div>ошибка во время запроса</div>";
					}
					
					if (jsDebugEnable)
					{
						data += "<br>" + error;
					}
					_this._endLoad(data, timestamp);
				},
				timeout: 300000
			}
			
			// URI params
			for(var paramKey in args.params)
			{
				var data = args.params[paramKey];
				var str = "";
				if (typeof(data) == "object" && (data.length > 1 || paramKey == "params"))
				{
					for(var dataKey in data)
					{
						var d = data[dataKey];
						if (typeof(d) == "object")
						{
							str += d.key + ":" + d.value + ";";
						}
						else
						{
							str += dataKey + ":" + d + ";";
						} 
					}
				}
				else
				{
					str = data;
				}

				xhrArgs.content[paramKey] = str;
			}
			
			// Form
			if (args.form != null)
			{
				xhrArgs["form"] = args.form;
			}
			
			// Content to merge
			if (args.content != null)
			{
				xhrArgs.content = dojo.mixin(xhrArgs.content, args.content);
			}
			
			//console.log("loading data... ", timestamp);

			// Call the asynchronous
			var deferred = null;
			if (args.method == "get")
			{
				deferred = dojo.xhrGet(xhrArgs);
			}
			else
			{
				deferred = dojo.xhrPost(xhrArgs);
			}
			this._deferredList.push(deferred);
		},
		
		addOnEndLoad: function(fnName)
		{
			this._onEndLoadFunc.push(fnName);
		}
	}


	 */
	
	if(dojo.isFunction(postInit))
	{
		postInit();
	}
	
	//dojo.setInternationalization("ru");
}

function postInit()
{
	// dojo.byId('submenu') && 
	if (dojo.byId('innerBody'))
	{
	
		if (gotoDocId > 0)
		{
			if (typeof goto != 'undefined' && goto != null)
			{
				updateMenu(goto.menuId, goto.submenuId, false);
			}
			else
			{
				updateMenu(1, null, false);
			}
			editDocument(gotoDocId, "", null);
		}
		else
		{
			if (typeof goto != 'undefined' && goto != null)
			{
				updateMenu(goto.menuId, goto.submenuId);
			}
			else
			{
				updateMenu(1);
			}
		}
	}
}

// Update page
/*
function updatePage(node, menuId, submenuId)
{
	// Set all submenu entry to "passive"
	dojo.query(".submenu ul li").forEach
	(
		function(node, index, arr)
		{
			node.className = "passive";
		}
	);
	node.className = "active";

	currentPage.id = menuId;
	currentPage.subId = submenuId;

	var args = 
	{
		method: "get",
		params:
		{
			uid: "page",
			id: currentPage.id,
			sub_id: currentPage.subId
		}
	}

	innerBody.load(args);
}
*/
function updatePage(node, method, params, loadContent)
{
	// Default value
	if (loadContent == null)
	{
		loadContent = true;
	}

	// Set all submenu entry to "passive"
	dojo.query(".menulist ul li").forEach
	(
		function(node, index, arr)
		{
			node.className = "passive";
		}
	);
	node.className = "active";

	currentPage.method = method;
	currentPage.params = params;

	var args = 
	{
		method: "get",
		params:
		{
			method: currentPage.method,
			params: currentPage.params
		}
	}

	if (loadContent)
	{
		innerBody.load(args);
	}
	
	/*
	// scroll to object
	var anim = dojox.fx.smoothScroll({
		node: dojo.byId("body"), // toTop
		win: window,
		duration: 500,
		easing: dojo.fx.easing.easeOut
	}).play(); 
	*/
	//scrollToObj("toTop");
}

// Update menu
function updateMenu(menuId, submenuId, loadContent)
{
	// Default value
	if (submenuId == null)
	{
		//submenuId = 1;
	}
	// Default value
	if (loadContent == null)
	{
		loadContent = true;
	}
	
	// update submenu
	var updateSubmenu = function (items, request)
	{
		var submenu = dojo.byId("submenu_" + request.query.id);
		//var submenu = dojo.create("div", null, null, "only");
		submenu.innerHTML = "";
		currentPage.id = null;
		currentPage.subId = null;

		// We found it!
		if (items.length == 1)
		{
			var ul = dojo.create("ul", null, submenu, "only");
			var pageLoading = false;
	
			var menuItem = items[0];
			
			// Update menu title
			if (dojo.byId("menuTitle") != null)
			{
				dojo.byId("menuTitle").innerHTML = menuItem.descr;
			}
			if (menuItem.children.length > 0)
			{
				// If only one child, but id maybe not 1
				if (menuItem.children.length == 1 || submenuId == null)
				{
					submenuId = menuItem.children[0].id;
				}
				for(var childInx in menuItem.children)
				{
					var submenuItem = menuItem.children[childInx];
					var li = dojo.create("li", null, ul);
					
					var uri = "#" + menuItem.id + ";" + submenuItem.id;
					var a = dojo.create("a", {href: uri, innerHTML: submenuItem.descr }, li);
					dojo.connect(a, 'onclick', dojo.hitch(null, updatePage, li, submenuItem.method, submenuItem.params));
					
					var tooltip = "";
					if (typeof submenuItem.tooltip == "object" && submenuItem.tooltip.length == 1)
					{
						tooltip = submenuItem.tooltip[0];
					}
					tooltip = dojo.trim(tooltip);
					if (dojo.trim(tooltip).length > 0)
					{
						new dijit.Tooltip({label: tooltip, connectId: li, showDelay: 100 });
					}

					// First link? Load page!
					if (!pageLoading && submenuItem.id == submenuId)
					{
						//updatePage(li, menuItem.id, submenuItem.id);
						updatePage(li, submenuItem.method, submenuItem.params, loadContent);
						pageLoading = true;
					}
				}
			}
			else
			{
				dijit.byId("innerBody").attr("content", null);
			}
		}
		else
		{
			dijit.byId("innerBody").attr("content", null);
		}
		
		if (menuAnimationQueue != null)
		{
			menuAnimationQueue.addAnimation(menuAnimIn);
		}
	}

	if (menuAnimationQueue != null)
	{
		menuAnimationQueue.addAnimation(menuAnimOut);
	}

	// change menu active state
	dojo.query('.menu .active').forEach
	(
		function(node, index, arr)
		{
			node.className = "passive";
			if (node.parentNode.nodeName == "TR")
			{
				//node.parentNode.style.display = "";
			}
		}
	);
	dojo.query('.menulist').forEach
	(
		function(node, index, arr)
		{
			if (node.parentNode.nodeName == "TR")
			{
				node.parentNode.style.display = "none";
			}
		}
	);
	if (dojo.byId("dyn_menu") != null)
	{
		dojo.destroy("dyn_menu");
	}
	dojo.query('.menu #menu_' + menuId + " td:first-child").forEach
	(
		function(node, index, arr)
		{
			node.className = "active";
			//node.className = "title";
			if (node.parentNode.nodeName == "TR")
			{
				//node.parentNode.style.display = "none";
				
				// Добавим ещё одну строку с пунктами меню
//				$(node.parentNode).after('<tr id="dyn_menu"><td class="menulist"><div id="submenu"></div></td></tr>');
				//dojo.create("div", {id: "submenu"}, dojo.byId("submenu_"+ menuId), "only");
				dojo.query('#submenu_'+ menuId).forEach
				(
					function(node2)
					{
						if (node2.parentNode.nodeName == "TD")
						{
							if (node2.parentNode.parentNode.nodeName == "TR")
							{
								node2.parentNode.parentNode.style.display = "";
							}
						}
					}
				);
			}			
		}
	);

	var request = menuStore.fetch({query: {id: menuId}, onComplete: updateSubmenu});
}

function isFormValid(formId)
{
	var form = dojo.byId(formId)
	
	var hasErrors = false;
	dojo.forEach
	(
		dojo.query(".dijitError", form),
		function(selectTag)
		{
			hasErrors = true;
		}
	);
	
	console.log("hasErrors: ", hasErrors);
	
	return !hasErrors;
}

// Send interactive form
function pageSubmitForm(formId, checkingForm)
{
	if (checkingForm == null)
	{
		checkingForm = true;
	}
	
	var args = 
	{
		method: "post",
		params:
		{
			method: currentPage.method,
			params: currentPage.params
		}
	}
	
	// Это список форм
	if (formId.indexOf(",") > 0)
	{
		var forms = formId.split(",");
		
		var formObject = {};
		for(var i in forms)
		{
			var form = forms[i];
			if (dojo.byId(form))
			{
				var obj = dojo.formToObject(form);
				formObject = dojo.mixin(formObject, obj);
			}
		}
		args.content = formObject;
	}
	else
	{
		// Work only for 1 form, not for list
		if (checkingForm)
		{
			if (!checkForm(formId))
			{
				return false;
			}
		}
		
		args.method = "post";
		args["form"] = dojo.byId(formId)
	}
	
	innerBody.load(args);
	
	return false;
}

function resetForm(formId)
{
	var form = dojo.byId(formId);
	dojo.forEach
	(
		dojo.query("input", form),
		function(selectTag)
		{
			if (selectTag.type == "text")
			{
				selectTag.value = "";
			}
		}
	);
	
	dojo.forEach
	(
		dojo.query("select", form),
		function(selectTag)
		{
//			selectTag.selectedIndex = 1;
			selectTag.selectedIndex = null;
			//console.log("selectTag: ", selectTag, selectTag.selectedIndex);
		}
	);
	
	return pageSubmitForm(formId);
}

/**
 * @deprecated
 * @param docId
 * @param tab
 * @param formId
 * @param documentType
 * @param method
 * @return
 */
function editDocument(docId, tab, formId, documentType, method)
{
	return openDocument({docId: docId, tab: tab, formId: formId, documentType: documentType, method: method});
}

function openDocument(params)
{
//	docId, tab, formId, documentType, method, forceLoad

	var args = 
	{
		method: 'get',
		params:
		{
			method: 'cabinet.documents.ReserveDocuments.getDocument',
			params:
			{
				view: "edit",
				docId: params.docId
			}
		}
	}
	
	if (params.tab != null && params.tab != '')
	{
		args.params.params.tab = params.tab;
	}

	if (params.forceLoad != null)
	{
		args.params.params.forceLoad = params.forceLoad;
	}

	if (params.documentType != null)
	{
		args.params.params.documentType = params.documentType;
	}
	
	if (params.method != null)
	{
		args.params.method = params.method;
	}
	
	var checkingForm = false;
	if (params.checkForm != null)
	{
		checkingForm = params.checkForm;
	}

	if (params.formId != null)
	{
		// Это список форм
		if (params.formId.indexOf(",") > 0)
		{
			var forms = params.formId.split(",");
			
			var formObject = {};
			for(var i in forms)
			{
				var form = forms[i];
				if (checkingForm)
				{
					if (!checkForm(form))
					{
						return false;
					}
				}
				if (dojo.byId(form))
				{
					var obj = dojo.formToObject(form);
					formObject = dojo.mixin(formObject, obj);
				}
			}
			args.method = "post";
			args.content = formObject;
		}
		else
		{
			if (checkingForm)
			{
				if (!checkForm(params.formId))
				{
					return false;
				}
			}

			args.method = "post";
			args["form"] = dojo.byId(params.formId)
		}
	}
	
	innerBody.load(args);
	
	return false;
}

function checkForm(formId)
{
	var isFormValidated = isFormValid(formId);
	if (!isFormValidated)
	{
		dojo.byId('errorDialogText').innerHTML = 'Некоторые поля заполнены некорректно!<br>Эти поля отмечены жёлтым цветом.';
		dijit.byId('errorDialog').show();
		
		return false;
	}
	
	return true;
}

/**
 * @deprecated
 * @param docId
 * @param formId
 * @return
 */
function viewCertificate(docId, formId)
{
	var args =
	{
		method: 'get',
		params:
		{
			method: 'cabinet.documents.BuhInvoices.getDocument',
			params:
			{
				view: "edit",
				docId: docId
			}
		}
	}
	
	if (formId != null)
	{
		args.method = "post";
		args['form'] = dojo.byId(formId)
	}
	
	innerBody.load(args);
	
	return false;
}

function getDocsList(formId, mode)
{
	var args =
	{
		method: 'get',
		params: 
		{
			method: 'cabinet.documents.BuhInvoices.getDocumentsList',
			params: 
			{
				view: "list",
				type: mode
			}
		}
	}
	
		if (formId != null)
	{
		args.method = "post";
		args['form'] = dojo.byId(formId)
	}
	
	innerBody.load(args);
	
	return false;
}

/**
 * @deprecated
 * @param mode
 * @param formId
 * @return
 */
function createDocument(mode, formId)
{
	var args = 
	{
		method: 'get',
		params:
		{
			method: 'cabinet.documents.BuhInvoices.createDocument',
			params:
			{
				view: "edit",
				mode: mode
			}
		}
	}
	
	if (formId != null)
	{
		args.method = "post";
		args["form"] = dojo.byId(formId)
	}
	
	innerBody.load(args);
	
	return false;
}

// Documents list
function changeSort(column)
{
	var sortColumn = dojo.byId('sortColumn');
	var sortDirect = dojo.byId('sortDirect');
	
	if (column == sortColumn.value)
	{
		if (sortDirect.value == "desc")
		{
			sortDirect.value = "asc";
		}
		else
		{
			sortDirect.value = "desc";
		}
	}
	else
	{
		sortColumn.value = column;
		sortDirect.value = "asc";
	}
	
	return pageSubmitForm('documentsListForm');
}

function documentsListChangePage(pageInx, firstRecord, lastRecord, totalRecords)
{
	var name = 'myStackPage_' + pageInx;
	if (dijit.byId(name) != null)
	{
		sumTableColumn(name);
	}

	if (totalRecords == 0)
	{
		dojo.byId('scrollFromToSplit').style.display = 'none';
		dojo.byId('scrollToRecord').style.display = 'none';
		dojo.byId('scrollFromRecord').innerHTML = "0";
	}
	else
	{
		dojo.byId('scrollFromRecord').innerHTML = firstRecord;
		dojo.byId('scrollToRecord').innerHTML = lastRecord;
	}
	dojo.byId('scrollTotalRecord').innerHTML = totalRecords;

	return false;
}

function sumTableColumn(name)
{
	var page = dijit.byId(name);
	
	// Посчитаем сумму
	var sum = 0;
	dojo.query(".s_amount", dojo.byId(name)).forEach
	(
		function(node, index)
		{
			if(dojo.style(node.parentNode, "display") == "none")
			{
				return;
			}
			
			var text = dojo.string.trim(node.innerHTML);
			var strInx = text.lastIndexOf(" ");
			var str = (strInx == -1 ? text : text.substr(0, strInx));

			// Hack to ru locale
			str = str.replace(".", ",");
			// Strip white spaces
			str = str.replace("&nbsp;", "");
			str = str.replace("+", "");

			var flags = {};
			var num = dojo.number.parse(str, flags);

			sum += num;
		}
	);
	
	dojo.query(".sa_amount", dojo.byId(name)).forEach
	(
		function(node, index)
		{
			var options = {pattern: "#,##0"};
			
			if (sum != Math.floor(sum))
			{
				options.pattern = "#,##0.00";
			}
			var formatSum = dojo.number.format(sum, options).replace(",", ".");

			node.innerHTML = formatSum;
			if (!$(node).hasClass("sa_amount_non_rur"))
			{
				node.innerHTML += " р.";
			}
		}
	);
	
	dijit.byId('myStackContainer').selectChild(page);
}

function backToList()
{
	var li = null;
	dojo.query(".menulist ul li.active").forEach
	(
		function(node, index, arr)
		{
			li = node;
		}
	);
	
	if (li != null)
	{
		updatePage(li, currentPage.method, currentPage.params, true);
	}
	
	return false;
}

/* TOOLS */
function checkPdf()
{
	// check PDF
	var pluginFound = pipwerks.pdfUTILS.detect.pluginFound();
	if (!pluginFound)
	{
		var data = "<div><p>Для работы необходим Adobe&reg; Reader&reg;</p></div>";
		data += "<div align='center'><a href='http://www.adobe.com/products/acrobat/readstep2.html' target='_blank'><img src='{/literal}{$server->static->getUri()}{literal}/pics/cabinet/get_adobe_reader.gif' width='112' height='33' border='0'></a></div>";
		var dialog = new dijit.Dialog({ title: "Ошибка", content: data, draggable: false });
		dialog.startup();
		dialog.show();
		return false;
	}

	/*
	// load into hidden iframe
	dojo.byId('load').style.display = 'block';
	var pdf = dojo.io.iframe.create("pdf");
	dojo.io.iframe.setSrc(pdf, url, true);
	pdf.onload = function(event)
	{
		alert("downloaded");
		event.target.contentWindow.focus();
		event.target.contentWindow.print();
		dojo.disconnect(handle);
		dojo.destroy(event.target);
		dojo.byId('load').style.display = 'none';
	}
	*/
    /*
	var pdf = dojo.create("iframe");
	//var pdf = dojo.byId("pdf");	
	var handle = dojo.connect(pdf, 'onLoad', function(event)
	{
		alert("downloaded");
		event.target.focus();
		event.target.print();
		dojo.disconnect(handle);
		dojo.destroy(event.target);
	});
	pdf.src = url;
	*/
	
	

	return true;
}
images_preload = new Array();
function image_preload(src)
{
	found = false;
	for (i=0; i<images_preload.length; i++)
	{
		ind = images_preload[i].src.indexOf(src);
		
		if (ind >= 0)
		{
			found = true;
		}
	}
	
	if (!found)
	{
		pi = new Image();
		pi.src = src;
		images_preload.push(pi);
	}
}

