// http://akelpad.sourceforge.net/forum/viewtopic.php?p=4537#4537
// Description(1033): Extended undo changes; works without scroll
// Description(1049): Расширенная отмена изменений; работает без скролирования документа
// Version: 2.4 (2015.01.15)
// Author: VladSh
// Initial code: © Instructor
// 
// Arguments:
// 	mode:
// 		0 - ask the user (for saved and modified document only);
// 		[1] - undo unsaved changes only (works as Instructors UndoAll.js);
// 		2 - undo all changes
// Usage:
// 	-"Отменить всё" Call("Scripts::Main", 1, "UndoAllNoScroll.js", `-mode=2`) Icon("%a\AkelFiles\Plugs\ToolBar.dll", 10)
// 	-"Отменить..." Call("Scripts::Main", 1, "UndoAllNoScroll.js", `-mode=0`) Icon("%a\AkelFiles\Plugs\ToolBar.dll", 10) - с запросом

var hWndEdit = AkelPad.GetEditWnd();
var oSys = AkelPad.SystemFunction();

if (hWndEdit) {
	if (AkelPad.SendMessage(hWndEdit, 3075 /*AEM_CANUNDO*/, 0, 0)) {
		
		var mode = AkelPad.GetArgValue("mode", 1);
		if (mode == 0) {
			mode = 2;
			if (AkelPad.GetEditFile(0)) {		// saved document
				var bModify = AkelPad.SendMessage(hWndEdit, 3086 /*AEM_GETMODIFY*/, 0, 0);
				if (bModify) {
					var msgText = "Yes - undo all changes;\nNo - undo unsaved changes only.";
					switch (AkelPad.MessageBox(AkelPad.GetMainWnd(), msgText, "Undo changes...", 32 + 3 /*MB_ICONQUESTION|MB_YESNOCANCEL*/)) {
						case 7 /*IDNO*/:
							mode = 1;
							break;
						case 2 /*IDCANCEL*/:
							WScript.Quit();
					}
				}
			}
		}
		
		SetRedraw(hWndEdit, false);
		AkelPad.SendMessage(hWndEdit, 3185 /*AEM_LOCKSCROLL*/, 3 /*SB_BOTH*/, true)
		
		if (mode == 1) {
			// undo unsaved changes only
			while (AkelPad.SendMessage(hWndEdit, 3077 /*AEM_UNDO*/, 0, 0)) {
				if (!AkelPad.SendMessage(hWndEdit, 3086 /*AEM_GETMODIFY*/, 0, 0)) {
					break;
				}
			}
		}
		else if (mode == 2) {
			// undo all changes
			while (AkelPad.SendMessage(hWndEdit, 3075 /*AEM_CANUNDO*/, 0, 0)) {
				AkelPad.SendMessage(hWndEdit, 3077 /*AEM_UNDO*/, 0, 0)
			}
		}
		
		AkelPad.SendMessage(hWndEdit, 3185 /*AEM_LOCKSCROLL*/, 3 /*SB_BOTH*/, false);
		SetRedraw(hWndEdit, true);
	}
}

function SetRedraw(hWnd, bRedraw) { 
	AkelPad.SendMessage(hWnd, 11 /*WM_SETREDRAW*/, bRedraw, 0); 
	if (bRedraw) oSys.Call("user32::InvalidateRect", hWnd, 0, true); 
}