make WebForm_DoCallback useful within AJAX.
[mono.git] / mcs / class / System.Web / resources / webform.js
1 /*
2  * WebForm.js
3  *
4  * Authors:
5  *   Chris Toshok (toshok@ximian.com)
6  *   Lluis Sanchez Gual (lluis@novell.com)
7  *   Igor Zelmanovich (igorz@mainsoft.com)
8  *
9  * (c) 2005 Novell, Inc. (http://www.novell.com)
10  *
11  * Permission is hereby granted, free of charge, to any person obtaining
12  * a copy of this software and associated documentation files (the
13  * "Software"), to deal in the Software without restriction, including
14  * without limitation the rights to use, copy, modify, merge, publish,
15  * distribute, sublicense, and/or sell copies of the Software, and to
16  * permit persons to whom the Software is furnished to do so, subject to
17  * the following conditions:
18  *
19  * The above copyright notice and this permission notice shall be
20  * included in all copies or substantial portions of the Software.
21  *
22  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
23  * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
24  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
25  * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
26  * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
27  * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
28  * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
29  */
30
31 function WebForm_Initialize(webForm) {
32
33 webForm.__pendingCallbacks = new Array();
34
35 webForm.WebForm_AutoFocus = function (id)
36 {
37         var x = this.WebForm_GetElementById (id);
38
39         if (x && (!this.WebForm_CanFocus(x))) {
40                 x = this.WebForm_FindFirstFocusableChild(x);
41         }
42         if (x) { x.focus(); }
43 }
44
45 webForm.WebForm_CanFocus = function (element) {
46         if (!element || !(element.tagName) || element.disabled) {
47                 return false;
48         }
49         if (element.type && element.type.toLowerCase() == "hidden") {
50                 return false;
51         }
52         var tagName = element.tagName.toLowerCase();
53         return (tagName == "input" ||
54                         tagName == "textarea" ||
55                         tagName == "select" ||
56                         tagName == "button" ||
57                         tagName == "a");
58 }
59
60 webForm.WebForm_FindFirstFocusableChild = function (element) {
61         if (!element || !(element.tagName)) {
62                 return null;
63         }
64         var tagName = element.tagName.toLowerCase();
65         if (tagName == "undefined") {
66                 return null;
67         }
68         var children = element.childNodes;
69         if (children) {
70                 for (var i = 0; i < children.length; i++) {
71                         try {
72                                 if (this.WebForm_CanFocus(children[i])) {
73                                         return children[i];
74                                 }
75                                 else {
76                                         var focused = this.WebForm_FindFirstFocusableChild(children[i]);
77                                         if (this.WebForm_CanFocus(focused)) {
78                                                 return focused;
79                                         }
80                                 }
81                         } catch (e) {
82                         }
83                 }
84         }
85         return null;
86 }
87
88 webForm.WebForm_ReEnableControls = function  ()
89 {
90         if (typeof(this._form.__enabledControlArray) != 'undefined' && this._form.__enabledControlArray != null)
91                 __enabledControlArray = this._form.__enabledControlArray;
92         
93         if (typeof(__enabledControlArray) == 'undefined' || __enabledControlArray == null)
94                 return false;
95         
96         this._form.__disabledControlArray = new Array();
97         for (var i = 0; i < __enabledControlArray.length; i++) {
98                 var c = this.WebForm_GetElementById (__enabledControlArray[i]);
99                 if ((typeof(c) != "undefined") && (c != null) && (c.disabled == true)) {
100                         c.disabled = false;
101                         this._form.__disabledControlArray[this._form.__disabledControlArray.length] = c;
102                 }
103         }
104         setTimeout((this._instanceVariableName ? this._instanceVariableName + "." : "") + "WebForm_ReDisableControls ()", 0);
105         return true;
106 }
107
108 webForm.WebForm_ReDisableControls = function  ()
109 {
110         for (var i = 0; i < this._form.__disabledControlArray.length; i++) {
111                 this._form.__disabledControlArray[i].disabled = true;
112         }
113 }
114
115 webForm.WebForm_DoPostback = function  (id, par, url, apb, pval, tf, csubm, vg)
116 {
117         var validationResult = true;
118         if (pval && typeof(this.Page_ClientValidate) == "function")
119                 validationResult =  this.Page_ClientValidate(vg);
120
121         if (validationResult) {
122                 if ((typeof(url) != "undefined") && (url != null) && (url.length > 0))
123                         this._form.action = url;
124                 if (tf) {
125                         var lastFocus = this._form.elements["__LASTFOCUS"];
126                         if ((typeof(lastFocus) != "undefined") && (lastFocus != null))
127                                 lastFocus.value = id;
128                 }
129         }               
130         if (csubm)
131                 this.__doPostBack (id, par);
132 }
133
134 webForm.WebForm_DoCallback = function (id, arg, callback, ctx, errorCallback, useAsync)
135 {
136         var qs = webForm.WebForm_getFormData () + "__CALLBACKTARGET=" + id + "&__CALLBACKARGUMENT=" + encodeURIComponent(arg);
137   
138   if (webForm._form["__EVENTVALIDATION"])
139     qs += "&__EVENTVALIDATION=" + encodeURIComponent(webForm._form["__EVENTVALIDATION"].value);
140   
141         webForm.WebForm_httpPost (webForm._form.serverURL || document.URL, qs, function (httpPost) { webForm.WebForm_ClientCallback (httpPost, ctx, callback, errorCallback); });
142 }
143
144 webForm.WebForm_ClientCallback = function (httpPost, ctx, callback, errorCallback)
145 {
146         var doc = httpPost.responseText;
147         if (doc.charAt(0) == "e") {
148                 if ((typeof(errorCallback) != "undefined") && (errorCallback != null))
149                         errorCallback(doc.substring(1), ctx);
150         } else {
151                 var separatorIndex = doc.indexOf("|");
152                 if (separatorIndex != -1) {
153                         var validationFieldLength = parseInt(doc.substring(0, separatorIndex));
154                         if (!isNaN(validationFieldLength)) {
155                                 var validationField = doc.substring(separatorIndex + 1, separatorIndex + validationFieldLength + 1);
156                                 if (validationField != "") {
157                                         var validationFieldElement = this._form["__EVENTVALIDATION"];
158                                         if (!validationFieldElement) {
159                                                 validationFieldElement = document.createElement("INPUT");
160                                                 validationFieldElement.type = "hidden";
161                                                 validationFieldElement.name = "__EVENTVALIDATION";
162                                                 validationFieldElement.id = validationFieldElement.name;
163                                                 this._form.appendChild(validationFieldElement);
164                                         }
165                                         validationFieldElement.value = validationField;
166                                 }
167                                 if ((typeof(callback) != "undefined") && (callback != null))
168                                         callback (doc.substring(separatorIndex + validationFieldLength + 1), ctx);
169                         }
170                 } else {
171                         if ((typeof(callback) != "undefined") && (callback != null))
172                                 callback (doc, ctx);
173                 }
174         }
175 }
176
177 webForm.WebForm_getFormData = function ()
178 {
179         var qs = "";
180         var len = this._form.elements.length;
181         for (n=0; n<len; n++) {
182                 var elem = this._form.elements [n];
183                 var tagName = elem.tagName.toLowerCase();
184                 if (tagName == "input") {
185                         var type = elem.type;
186                         if ((type == "text" || type == "hidden" || type == "password" ||
187                                 ((type == "checkbox" || type == "radio") && elem.checked)) &&
188           (elem.id != "__EVENTVALIDATION")) {
189                                 qs += elem.name + "=" + encodeURIComponent (elem.value) + "&";
190                         }
191                 } else if (tagName == "select") {
192                         var selectCount = elem.options.length;
193                         for (var j = 0; j < selectCount; j++) {
194                                 var selectChild = elem.options[j];
195                                 if (selectChild.selected == true) {
196                                         qs += elem.name + "=" + encodeURIComponent (elem.value) + "&";
197                                 }
198                         }
199                 }
200                 else if (tagName == "textarea") {
201                         qs += elem.name + "=" + encodeURIComponent (elem.value) + "&";
202                 }
203         }
204         return qs;
205 }
206
207 webForm.WebForm_httpPost = function (url, data, callback)
208 {
209         var httpPost = null;
210         
211         if (typeof XMLHttpRequest != "undefined") {
212                 httpPost = new XMLHttpRequest ();
213         } else {
214                 if (this.axName != null)
215                         httpPost = new ActiveXObject (this.axName);
216                 else {
217                         var clsnames = new Array ("MSXML", "MSXML2", "MSXML3", "Microsoft");
218                         for (n = 0; n < clsnames.length && httpPost == null; n++) {
219                                 this.axName = clsnames [n] + ".XMLHTTP";
220                                 try {
221                                         httpPost = new ActiveXObject (this.axName);
222                                 } catch (e) { this.axName = null; }
223                         }
224                         if (httpPost == null)
225                                 throw new Error ("XMLHTTP object could not be created.");
226                 }
227         }
228         httpPost.onreadystatechange = function () { if (httpPost.readyState == 4) callback (httpPost); };
229         
230         httpPost.open ("POST", url, true);      // async
231         httpPost.setRequestHeader ("Content-Type", "application/x-www-form-urlencoded");
232         setTimeout (function () { httpPost.send (data); }, 10);
233 }
234
235 webForm.WebForm_GetElementById = function (id)
236 {
237         return document.getElementById ? document.getElementById (id) :
238                document.all ? document.all [id] :
239                    document [id];
240 }
241
242 webForm.WebForm_FireDefaultButton = function (event, target)
243 {
244         if (event.keyCode != 13) {
245                 return true;
246         }
247         if(event.srcElement && (event.srcElement.tagName.toLowerCase() == "textarea")) {
248                 return true;
249         }
250         var defaultButton = this.WebForm_GetElementById(target);
251         if (!defaultButton)
252                 return true;
253         
254         if (typeof(defaultButton.click) != "undefined") {
255                 defaultButton.click();
256                 event.cancelBubble = true;
257                 return false;
258         }
259         
260         if (defaultButton.href && defaultButton.href.match(/^javascript:/i)) {
261                 var jsCode = defaultButton.href.match(/^javascript:(.*)/i)[1]; 
262                 eval(jsCode);
263                 event.cancelBubble = true;
264                 return false;
265         }
266         
267         return true;
268 }
269
270 webForm.WebForm_SaveScrollPositionSubmit = function ()
271 {
272         var pos = this.WebForm_GetElementPosition(this._form);
273         this._form.elements['__SCROLLPOSITIONX'].value = this.WebForm_GetScrollX() - pos.x;
274         this._form.elements['__SCROLLPOSITIONY'].value = this.WebForm_GetScrollY() - pos.y;
275         if ((typeof(this._form.oldSubmit) != "undefined") && (this._form.oldSubmit != null)) {
276                 return this._form.oldSubmit();
277         }
278         return true;
279 }
280
281 webForm.WebForm_SaveScrollPositionOnSubmit = function ()
282 {
283         var pos = this.WebForm_GetElementPosition(this._form);
284         this._form.elements['__SCROLLPOSITIONX'].value = this.WebForm_GetScrollX() - pos.x;
285         this._form.elements['__SCROLLPOSITIONY'].value = this.WebForm_GetScrollY() - pos.y;
286         if ((typeof(this._form.oldOnSubmit) != "undefined") && (this._form.oldOnSubmit != null)) {
287                 return this._form.oldOnSubmit();
288         }
289         return true;
290 }
291
292 webForm.WebForm_RestoreScrollPosition = function ()
293 {
294         var pos = this.WebForm_GetElementPosition(this._form);
295         var ScrollX = parseInt(this._form.elements['__SCROLLPOSITIONX'].value);
296         var ScrollY = parseInt(this._form.elements['__SCROLLPOSITIONY'].value);
297         ScrollX = (isNaN(ScrollX)) ? pos.x : (ScrollX + pos.x);
298         ScrollY = (isNaN(ScrollY)) ? pos.y : (ScrollY + pos.y);
299         window.scrollTo(ScrollX, ScrollY);
300         if ((typeof(this._form.oldOnLoad) != "undefined") && (this._form.oldOnLoad != null)) {
301                 return this._form.oldOnLoad();
302         }
303         return true;
304 }
305
306 webForm.WebForm_GetScrollX = function () {
307     if (window.pageXOffset) {
308         return window.pageXOffset;
309     }
310     else if (document.documentElement && document.documentElement.scrollLeft) {
311         return document.documentElement.scrollLeft;
312     }
313     else if (document.body) {
314         return document.body.scrollLeft;
315     }
316     return 0;
317 }
318
319 webForm.WebForm_GetScrollY = function () {
320     if (window.pageYOffset) {
321         return window.pageYOffset;
322     }
323     else if (document.documentElement && document.documentElement.scrollTop) {
324         return document.documentElement.scrollTop;
325     }
326     else if (document.body) {
327         return document.body.scrollTop;
328     }
329     return 0;
330 }
331
332 webForm.WebForm_GetElementPosition = function (element)
333 {
334         var result = new Object();
335         result.x = 0;
336         result.y = 0;
337         result.width = 0;
338         result.height = 0;
339         result.x = element.offsetLeft;
340         result.y = element.offsetTop;
341         var parent = element.offsetParent;
342         while (parent) {
343                 result.x += parent.offsetLeft;
344                 result.y += parent.offsetTop;
345                 parent = parent.offsetParent;
346         }
347         result.width = element.offsetWidth;
348         result.height = element.offsetHeight;
349         return result;
350 }
351 }
352