diff options
author | Fabio Bas <ctrlaltca@gmail.com> | 2013-10-19 19:16:51 +0200 |
---|---|---|
committer | Fabio Bas <ctrlaltca@gmail.com> | 2013-10-19 19:16:51 +0200 |
commit | 8b34b4117b43d1e9287c93f031923236cc3deb7f (patch) | |
tree | b71f96afe52804a945a752cc05c7be8d89024160 /framework/Web/Javascripts | |
parent | 7d1cdcd61796a437f9ec7ba776f2a69640ba513f (diff) |
Started work on ajax
Diffstat (limited to 'framework/Web/Javascripts')
6 files changed, 1020 insertions, 1487 deletions
diff --git a/framework/Web/Javascripts/packages.php b/framework/Web/Javascripts/packages.php index ec918402..5ddb9301 100644 --- a/framework/Web/Javascripts/packages.php +++ b/framework/Web/Javascripts/packages.php @@ -39,8 +39,6 @@ $packages = array( ), 'ajax' => array( - SCRIPTACULOUS_DIR.'/controls.js', - 'prado/activecontrols/json2.js', 'prado/activecontrols/ajax3.js', 'prado/activecontrols/activecontrols3.js', ), @@ -109,16 +107,17 @@ $packages = array( //package names and their dependencies $dependencies = array( - 'prototype' => array('prototype'), + //'prototype' => array('prototype'), 'jquery' => array('jquery'), 'prado' => array('jquery', 'prado'), 'validator' => array('jquery', 'prado', 'validator'), 'tabpanel' => array('jquery', 'prado', 'tabpanel'), + 'ajax' => array('jquery', 'prado', 'ajax'), + 'effects' => array('prototype', 'prado', 'effects'), 'logger' => array('prototype', 'prado', 'logger'), 'datepicker' => array('prototype', 'prado', 'datepicker'), 'colorpicker' => array('prototype', 'prado', 'colorpicker'), - 'ajax' => array('prototype', 'prado', 'effects', 'ajax'), 'dragdrop' => array('prototype', 'prado', 'effects', 'ajax', 'dragdrop'), 'slider' => array('prototype', 'prado', 'slider'), 'keyboard' => array('prototype', 'prado', 'keyboard'), diff --git a/framework/Web/Javascripts/source/prado/activecontrols/activecontrols3.js b/framework/Web/Javascripts/source/prado/activecontrols/activecontrols3.js index 1b94ef7c..a586c4d9 100644 --- a/framework/Web/Javascripts/source/prado/activecontrols/activecontrols3.js +++ b/framework/Web/Javascripts/source/prado/activecontrols/activecontrols3.js @@ -1,63 +1,63 @@ /** * Generic postback control. */ -Prado.WebUI.CallbackControl = Class.extend(Prado.WebUI.PostBackControl, +Prado.WebUI.CallbackControl = jQuery.klass(Prado.WebUI.PostBackControl, { - onPostBack : function(event, options) + onPostBack : function(options, event) { var request = new Prado.CallbackRequest(options.EventTarget, options); request.dispatch(); - Event.stop(event); + event.preventDefault(); } }); /** * TActiveButton control. */ -Prado.WebUI.TActiveButton = Class.extend(Prado.WebUI.CallbackControl); +Prado.WebUI.TActiveButton = jQuery.klass(Prado.WebUI.CallbackControl); /** * TActiveLinkButton control. */ -Prado.WebUI.TActiveLinkButton = Class.extend(Prado.WebUI.CallbackControl); +Prado.WebUI.TActiveLinkButton = jQuery.klass(Prado.WebUI.CallbackControl); -Prado.WebUI.TActiveImageButton = Class.extend(Prado.WebUI.TImageButton, +Prado.WebUI.TActiveImageButton = jQuery.klass(Prado.WebUI.TImageButton, { - onPostBack : function(event, options) + onPostBack : function(options, event) { this.addXYInput(event,options); var request = new Prado.CallbackRequest(options.EventTarget, options); request.dispatch(); - Event.stop(event); + event.stopPropagation(); this.removeXYInput(event,options); } }); /** * Active check box. */ -Prado.WebUI.TActiveCheckBox = Class.extend(Prado.WebUI.CallbackControl, +Prado.WebUI.TActiveCheckBox = jQuery.klass(Prado.WebUI.CallbackControl, { - onPostBack : function(event, options) + onPostBack : function(options, event) { var request = new Prado.CallbackRequest(options.EventTarget, options); if(request.dispatch()==false) - Event.stop(event); + event.stopPropagation(); } }); /** * TActiveRadioButton control. */ -Prado.WebUI.TActiveRadioButton = Class.extend(Prado.WebUI.TActiveCheckBox); +Prado.WebUI.TActiveRadioButton = jQuery.klass(Prado.WebUI.TActiveCheckBox); -Prado.WebUI.TActiveCheckBoxList = Base.extend( +Prado.WebUI.TActiveCheckBoxList = jQuery.extend( { constructor : function(options) { - Prado.Registry.set(options.ListID, this); + Prado.Registry[options.ListID] = this; for(var i = 0; i<options.ItemCount; i++) { - var checkBoxOptions = Object.extend( + var checkBoxOptions = jQuery.extend( { ID : options.ListID+"_c"+i, EventTarget : options.ListName+"$c"+i @@ -72,7 +72,7 @@ Prado.WebUI.TActiveRadioButtonList = Prado.WebUI.TActiveCheckBoxList; /** * TActiveTextBox control, handles onchange event. */ -Prado.WebUI.TActiveTextBox = Class.extend(Prado.WebUI.TTextBox, +Prado.WebUI.TActiveTextBox = jQuery.klass(Prado.WebUI.TTextBox, { onInit : function(options) { @@ -88,15 +88,16 @@ Prado.WebUI.TActiveTextBox = Class.extend(Prado.WebUI.TTextBox, var request = new Prado.CallbackRequest(options.EventTarget, options); request.dispatch(); if (!Prototype.Browser.IE) - Event.stop(event); + event.stopPropagation(); } }); /** * TAutoComplete control. */ -Prado.WebUI.TAutoComplete = Class.extend(Autocompleter.Base, Prado.WebUI.TActiveTextBox.prototype); -Prado.WebUI.TAutoComplete = Class.extend(Prado.WebUI.TAutoComplete, + /* +Prado.WebUI.TAutoComplete = jQuery.klass(Autocompleter.Base, Prado.WebUI.TActiveTextBox.prototype); +Prado.WebUI.TAutoComplete = jQuery.klass(Prado.WebUI.TAutoComplete, { initialize : function(options) { @@ -104,7 +105,7 @@ Prado.WebUI.TAutoComplete = Class.extend(Prado.WebUI.TAutoComplete, this.observers = new Array(); this.hasResults = false; this.baseInitialize(options.ID, options.ResultPanel, options); - Object.extend(this.options, + jQuery.extend(this.options, { onSuccess : this.onComplete.bind(this) }); @@ -112,7 +113,7 @@ Prado.WebUI.TAutoComplete = Class.extend(Prado.WebUI.TAutoComplete, if(options.AutoPostBack) this.onInit(options); - Prado.Registry.set(options.ID, this); + Prado.Registry[options.ID] = this; }, doCallback : function(event, options) @@ -121,18 +122,18 @@ Prado.WebUI.TAutoComplete = Class.extend(Prado.WebUI.TAutoComplete, { var request = new Prado.CallbackRequest(this.options.EventTarget, options); request.dispatch(); - Event.stop(event); + event.stopPropagation(); } }, //Overrides parent implementation, fires onchange event. onClick: function(event) { - var element = Event.findElement(event, 'LI'); + var element = jQuery(event.target).closest('LI'); this.index = element.autocompleteIndex; this.selectEntry(); this.hide(); - Event.fireEvent(this.element, "change"); + $(this.element).trigger( "change" ); }, getUpdatedChoices : function() @@ -143,7 +144,7 @@ Prado.WebUI.TAutoComplete = Class.extend(Prado.WebUI.TAutoComplete, /** * Overrides parent implements, don't update if no results. - */ + * / selectEntry: function() { if(this.hasResults) @@ -174,7 +175,7 @@ Prado.WebUI.TAutoComplete = Class.extend(Prado.WebUI.TAutoComplete, } } }); - +*/ /** * Time Triggered Callback class. */ @@ -182,7 +183,7 @@ Prado.WebUI.TTimeTriggeredCallback = jQuery.klass(Prado.WebUI.Control, { onInit : function(options) { - this.options = Object.extend({ Interval : 1 }, options || {}); + this.options = jQuery.extend({ Interval : 1 }, options || {}); Prado.WebUI.TTimeTriggeredCallback.registerTimer(this); }, @@ -231,7 +232,7 @@ Prado.WebUI.TTimeTriggeredCallback = jQuery.klass(Prado.WebUI.Control, } }); -Object.extend(Prado.WebUI.TTimeTriggeredCallback, +jQuery.extend(Prado.WebUI.TTimeTriggeredCallback, { //class methods @@ -277,7 +278,7 @@ Prado.WebUI.ActiveListControl = jQuery.klass(Prado.WebUI.Control, { var request = new Prado.CallbackRequest(this.options.EventTarget, this.options); request.dispatch(); - Event.stop(event); + event.stopPropagation(); } }); @@ -320,7 +321,7 @@ Prado.WebUI.TEventTriggeredCallback = jQuery.klass(Prado.WebUI.Control, var request = new Prado.CallbackRequest(this.options.EventTarget, this.options); request.dispatch(); if(this.options.StopEvent == true) - Event.stop(event); + event.stopPropagation(); } }); @@ -389,7 +390,7 @@ Prado.WebUI.TValueTriggeredCallback = jQuery.klass(Prado.WebUI.Control, } }); -Object.extend(Prado.WebUI.TValueTriggeredCallback, +jQuery.extend(Prado.WebUI.TValueTriggeredCallback, { //class methods diff --git a/framework/Web/Javascripts/source/prado/activecontrols/ajax3.js b/framework/Web/Javascripts/source/prado/activecontrols/ajax3.js index 10f4fae6..e86bf00c 100644 --- a/framework/Web/Javascripts/source/prado/activecontrols/ajax3.js +++ b/framework/Web/Javascripts/source/prado/activecontrols/ajax3.js @@ -1,160 +1,9 @@ - -Prado.AjaxRequest = jQuery.klass(); -Prado.AjaxRequest.prototype = Object.clone(Ajax.Request.prototype); - -/** - * Override Prototype's response implementation. - */ -Object.extend(Prado.AjaxRequest.prototype, -{ - /*initialize: function(request) - { - this.CallbackRequest = request; - this.transport = Ajax.getTransport(); - this.setOptions(request.options); - this.request(request.url); - },*/ - - /** - * Customize the response, dispatch onXXX response code events, and - * tries to execute response actions (javascript statements). - */ - respondToReadyState : function(readyState) - { - var event = Ajax.Request.Events[readyState]; - var transport = this.transport, json = this.getBodyDataPart(Prado.CallbackRequest.DATA_HEADER); - - if (event == 'Complete') - { - var redirectUrl = this.getBodyContentPart(Prado.CallbackRequest.REDIRECT_HEADER); - if (redirectUrl) - document.location.href = redirectUrl; - - if ((this.getHeader('Content-type') || '').match(/^text\/javascript/i)) - { - try - { - json = eval('(' + transport.responseText + ')'); - } - catch (e) - { - if(typeof(json) == "string") - json = Prado.CallbackRequest.decode(result); - } - } - - try - { - Prado.CallbackRequest.updatePageState(this,transport); - Prado.CallbackRequest.checkHiddenFields(this,transport); - var obj = this; - Prado.CallbackRequest.loadAssets(this,transport, function() - - { - try - { - Ajax.Responders.dispatch('on' + transport.status, obj, transport, json); - Prado.CallbackRequest.dispatchActions(transport,obj.getBodyDataPart(Prado.CallbackRequest.ACTION_HEADER)); - - ( - obj.options['on' + obj.transport.status] - || - obj.options['on' + (obj.success() ? 'Success' : 'Failure')] - || - Prototype.emptyFunction - ) (obj, json); - } - catch (e) - { - obj.dispatchException(e); - } - } - ); - } - catch (e) - { - this.dispatchException(e); - } - } - - try { - (this.options['on' + event] || Prototype.emptyFunction)(this, json); - Ajax.Responders.dispatch('on' + event, this, transport, json); - } catch (e) { - this.dispatchException(e); - } - - /* Avoid memory leak in MSIE: clean up the oncomplete event handler */ - if (event == 'Complete') - this.transport.onreadystatechange = Prototype.emptyFunction; - }, - - /** - * Gets header data assuming JSON encoding. - * @param string header name - * @return object header data as javascript structures. - */ - getHeaderData : function(name) - { - return this.getJsonData(this.getHeader(name)); - }, - - getBodyContentPart : function(name) - { - if(typeof(this.transport.responseText)=="string") - return Prado.Element.extractContent(this.transport.responseText, name); - }, - - getJsonData : function(json) - { - try - { - return eval('(' + json + ')'); - } - catch (e) - { - if(typeof(json) == "string") - return Prado.CallbackRequest.decode(json); - } - }, - - getBodyDataPart : function(name) - { - return this.getJsonData(this.getBodyContentPart(name)); - } -}); - -/** - * Prado Callback client-side request handler. - */ -Prado.CallbackRequest = jQuery.klass(); - -/** - * Static definitions. - */ -Object.extend(Prado.CallbackRequest, +Prado.CallbackRequestManager = { /** - * Callback request target POST field name. - */ - FIELD_CALLBACK_TARGET : 'PRADO_CALLBACK_TARGET', - /** - * Callback request parameter POST field name. - */ - FIELD_CALLBACK_PARAMETER : 'PRADO_CALLBACK_PARAMETER', - /** - * Callback request page state field name, + * Response redirect header name. */ - FIELD_CALLBACK_PAGESTATE : 'PRADO_PAGESTATE', - - FIELD_POSTBACK_TARGET : 'PRADO_POSTBACK_TARGET', - - FIELD_POSTBACK_PARAMETER : 'PRADO_POSTBACK_PARAMETER', - - /** - * List of form fields that will be collected during callback. - */ - PostDataLoaders : [], + REDIRECT_HEADER : 'X-PRADO-REDIRECT', /** * Response data header name. */ @@ -186,215 +35,203 @@ Object.extend(Prado.CallbackRequest, /** * Hidden field list header name. */ - HIDDENFIELDLIST_HEADER : 'X-PRADO-HIDDENFIELDLIST', - - REDIRECT_HEADER : 'X-PRADO-REDIRECT', + HIDDENFIELDLIST_HEADER : 'X-PRADO-HIDDENFIELDLIST' +}; - requestQueue : [], +Prado.CallbackRequest = jQuery.klass(Prado.PostBack, { - //all request objects - requests : {}, + options : {}, - getRequestById : function(id) + initialize: function(target, options) { - var requests = Prado.CallbackRequest.requests; - if(typeof(requests[id]) != "undefined") - return requests[id]; - }, + this.options = { + RequestTimeOut : 30000, // 30 second timeout. + EnablePageStateUpdate : true, + HasPriority : true, + CausesValidation : true, + ValidationGroup : null, + PostInputs : true, - dispatch : function(id) - { - var requests = Prado.CallbackRequest.requests; - if(typeof(requests[id]) != "undefined") - requests[id].dispatch(); + type: "POST", + iscallback: true, + + context: this, + success: this.onSuccess, + }; + + jQuery.extend(this.options, options || {}); }, - /** - * Add ids of inputs element to post in the request. - */ - addPostLoaders : function(ids) + getForm: function() { - var self = Prado.CallbackRequest; - self.PostDataLoaders = self.PostDataLoaders.concat(ids); - var list = []; - self.PostDataLoaders.each(function(id) - { - if(list.indexOf(id) < 0) - list.push(id); - }); - self.PostDataLoaders = list; + return jQuery('#PRADO_PAGESTATE').get(0).form; }, - /** - * Dispatch callback response actions. - */ - dispatchActions : function(transport,actions) + dispatch: function() { - var self = Prado.CallbackRequest; - if(actions && actions.length > 0) - actions.each(self.__run.bind(self,transport)); + this.options.data = this.getParameters(); + this.options.url = this.getForm().action; + + jQuery.ajax(this.options); }, - /** - * Prase and evaluate a Callback clien-side action - */ - __run : function(transport, command) + onSuccess: function(data) { - var self = Prado.CallbackRequest; - self.transport = transport; - for(var method in command) + var redirectUrl = Prado.Element.extractContent(data, Prado.CallbackRequestManager.REDIRECT_HEADER); + if (redirectUrl) + document.location.href = redirectUrl; +/* + if ((this.getHeader('Content-type') || '').match(/^text\/javascript/i)) { - try + try { - method.toFunction().apply(self,command[method]); - } - catch(e) + json = eval('(' + transport.responseText + ')'); + } + catch (e) { - if(typeof(Logger) != "undefined") - self.Exception.onException(null,e); - else - debugger; + if(typeof(json) == "string") + json = Prado.CallbackRequest.decode(result); } } - }, - - /** - * Respond to Prado Callback request exceptions. - */ - Exception : - { - /** - * Server returns 500 exception. Just log it. - */ - "on500" : function(request, transport, data) - { - var e = request.getHeaderData(Prado.CallbackRequest.ERROR_HEADER); - if (e) - Logger.error("Callback Server Error "+e.code, this.formatException(e)); - else - Logger.error("Callback Server Error Unknown",''); - }, - - /** - * Callback OnComplete event,logs reponse and data to console. - */ - 'on200' : function(request, transport, data) +*/ + try { - if(transport.status < 500) - { - var msg = 'HTTP '+transport.status+" with response : \n"; - if(transport.responseText.trim().length >0) - { - var f = RegExp('(<!--X-PRADO[^>]+-->)([\\s\\S\\w\\W]*)(<!--//X-PRADO[^>]+-->)',"m"); - msg += transport.responseText.replace(f,'') + "\n"; - } - if(typeof(data)!="undefined" && data != null) - msg += "Data : \n"+inspect(data)+"\n"; - data = request.getBodyDataPart(Prado.CallbackRequest.ACTION_HEADER); - if(data && data.length > 0) + this.updatePageState(this, data); + this.checkHiddenFields(this, data); + var obj = this; + this.loadAssets(this, data, function() { - msg += "Actions : \n"; - data.each(function(action) + // try + // { + //Ajax.Responders.dispatch('on' + transport.status, obj, transport, json); + obj.dispatchActions(obj, data); +/* + ( + obj.options['on' + obj.transport.status] + || + obj.options['on' + (obj.success() ? 'Success' : 'Failure')] + || + Prototype.emptyFunction + ) (obj, json); + */ + /* + } + catch (e) { - msg += inspect(action)+"\n"; - }); + obj.dispatchException(e); + } + */ } - Logger.info(msg); - } - }, + ); - /** - * Uncaught exceptions during callback response. - */ - onException : function(request,e) - { - var msg = ""; - $H(e).each(function(item) - { - msg += item.key+": "+item.value+"\n"; - }) - Logger.error('Uncaught Callback Client Exception:', msg); - }, + } + catch (e) + { + this.dispatchException(e); + } + }, - /** - * Formats the exception message for display in console. - */ - formatException : function(e) + /** + * Updates the page state. It will update only if EnablePageStateUpdate and + * HasPriority options are both true. + */ + updatePageState : function(request, datain) + { + //var self = Prado.CallbackRequest; + var pagestate = $("#"+Prado.RequestManager.FIELD_CALLBACK_PAGESTATE); + var enabled = request.options.EnablePageStateUpdate && request.options.HasPriority; + var aborted = false; //typeof(self.currentRequest) == 'undefined' || self.currentRequest == null; + if(enabled && !aborted && pagestate) { - var msg = e.type + " with message \""+e.message+"\""; - msg += " in "+e.file+"("+e.line+")\n"; - msg += "Stack trace:\n"; - var trace = e.trace; - for(var i = 0; i<trace.length; i++) + var data = Prado.Element.extractContent(datain, Prado.CallbackRequestManager.PAGESTATE_HEADER); + if(typeof(data) == "string" && data.length > 0) + pagestate.val(data); + else { - msg += " #"+i+" "+trace[i].file; - msg += "("+trace[i].line+"): "; - msg += trace[i]["class"]+"->"+trace[i]["function"]+"()"+"\n"; + if(typeof(Logger) != "undefined") + Logger.warn("Missing page state:"+data); + //Logger.warn('## bad state: setting current request to null'); + //self.endCurrentRequest(); + //self.tryNextRequest(); + return false; } - msg += e.version+" "+e.time+"\n"; - return msg; } + //self.endCurrentRequest(); + //Logger.warn('## state updated: setting current request to null'); + //self.tryNextRequest(); + return true; }, - /** - * @return string JSON encoded data. - */ - encode : function(data) + checkHiddenField: function(name, value) { - return Prado.JSON.stringify(data); + var id = name.replace(':','_'); + if (!document.getElementById(id)) + { + var field = document.createElement('input'); + field.setAttribute('type','hidden'); + field.id = id; + field.name = name; + field.value = value; + document.body.appendChild(field); + } }, - /** - * @return mixed javascript data decoded from string using JSON decoding. - */ - decode : function(data) + checkHiddenFields : function(request, datain) { - if(typeof(data) == "string" && data.trim().length > 0) - return Prado.JSON.parse(data); - else - return null; + var data = Prado.Element.extractContent(datain, Prado.CallbackRequestManager.HIDDENFIELDLIST_HEADER); + if (typeof(data) == "string" && data.length > 0) + { + json = jQuery.parseJSON(data); + if(typeof(json) != "object") + Logger.warn("Invalid hidden field list:"+data); + else + for(var key in json) + Prado.CallbackRequestManager.checkHiddenField(key,json[key]); + } }, - /** - * Dispatch a normal request, no timeouts or aborting of requests. + /* + * Checks which assets are used by the response and ensures they're loaded */ - dispatchNormalRequest : function(callback) + loadAssets : function(request, datain, callback) { - callback.options.postBody = callback._getPostData(), - callback.request(callback.url); - return true; - }, + /* - /** - * Abort the current priority request in progress. - */ - tryNextRequest : function() - { - var self = Prado.CallbackRequest; - //Logger.debug('trying next request'); - if(typeof(self.currentRequest) == 'undefined' || self.currentRequest==null) - { - if(self.requestQueue.length > 0) - return self.dispatchQueue(); - //else - //Logger.warn('empty queque'); - } - //else - //Logger.warn('current request ' + self.currentRequest.id); + ! This is the callback-based loader for stylesheets, which loads them one-by-one, and + ! waits for all of them to be loaded before loading scripts and processing the rest of + ! the callback. + ! + ! That however is not neccessary, as stylesheets can be loaded asynchronously too. + ! + ! I leave this code here for the case that this turns out to be a compatibility issue + ! (for ex. I can imagine some scripts trying to access stylesheet properties and such) + ! so if need can be reactivated. If you do so, comment out the async stylesheet loader below! + + var obj = this; + this.loadStyleSheets(request,transport, function() { + obj.loadScripts(request,transport,callback); + }); + + */ + + this.loadStyleSheetsCode(request,datain); + + this.loadStyleSheetsAsync(request,datain); + + this.loadScripts(request,datain,callback); }, /* * Checks which scripts are used by the response and ensures they're loaded */ - loadScripts : function(request, transport, callback) + loadScripts : function(request, datain, callback) { - var self = Prado.CallbackRequest; - var data = request.getBodyContentPart(self.SCRIPTLIST_HEADER); + var data = Prado.Element.extractContent(datain, Prado.CallbackRequestManager.SCRIPTLIST_HEADER); if (!this.ScriptsToLoad) this.ScriptsToLoad = new Array(); this.ScriptLoadFinishedCallback = callback; if (typeof(data) == "string" && data.length > 0) { - json = Prado.CallbackRequest.decode(data); + json = jQuery.parseJSON(data); if(typeof(json) != "object") Logger.warn("Invalid script list:"+data); else @@ -435,13 +272,12 @@ Object.extend(Prado.CallbackRequest, } }, - loadStyleSheetsCode : function(request, transport) + loadStyleSheetsCode : function(request, datain) { - var self = Prado.CallbackRequest; - var data = request.getBodyContentPart(self.STYLESHEET_HEADER); + var data = Prado.Element.extractContent(datain, Prado.CallbackRequestManager.STYLESHEET_HEADER); if (typeof(data) == "string" && data.length > 0) { - json = Prado.CallbackRequest.decode(data); + json = jQuery.parseJSON(data); if(typeof(json) != "object") Logger.warn("Invalid stylesheet list:"+data); else @@ -451,13 +287,12 @@ Object.extend(Prado.CallbackRequest, } }, - loadStyleSheetsAsync : function(request, transport) + loadStyleSheetsAsync : function(request, datain) { - var self = Prado.CallbackRequest; - var data = request.getBodyContentPart(self.STYLESHEETLIST_HEADER); + var data = Prado.Element.extractContent(datain, Prado.CallbackRequestManager.STYLESHEETLIST_HEADER); if (typeof(data) == "string" && data.length > 0) { - json = Prado.CallbackRequest.decode(data); + json = jQuery.parseJSON(data); if(typeof(json) != "object") Logger.warn("Invalid stylesheet list:"+data); else @@ -467,15 +302,14 @@ Object.extend(Prado.CallbackRequest, } }, - loadStyleSheets : function(request, transport, callback) + loadStyleSheets : function(request, datain, callback) { - var self = Prado.CallbackRequest; - var data = request.getBodyContentPart(self.STYLESHEETLIST_HEADER); + var data = Prado.Element.extractContent(datain, Prado.CallbackRequestManager.STYLESHEETLIST_HEADER); if (!this.StyleSheetsToLoad) this.StyleSheetsToLoad = new Array(); this.StyleSheetLoadFinishedCallback = callback; if (typeof(data) == "string" && data.length > 0) { - json = Prado.CallbackRequest.decode(data); + json = jQuery.parseJSON(data); if(typeof(json) != "object") Logger.warn("Invalid stylesheet list:"+data); else @@ -516,594 +350,781 @@ Object.extend(Prado.CallbackRequest, } }, - /* - * Checks which assets are used by the response and ensures they're loaded + /** + * Dispatch callback response actions. */ - loadAssets : function(request, transport, callback) - { - /* - - ! This is the callback-based loader for stylesheets, which loads them one-by-one, and - ! waits for all of them to be loaded before loading scripts and processing the rest of - ! the callback. - ! - ! That however is not neccessary, as stylesheets can be loaded asynchronously too. - ! - ! I leave this code here for the case that this turns out to be a compatibility issue - ! (for ex. I can imagine some scripts trying to access stylesheet properties and such) - ! so if need can be reactivated. If you do so, comment out the async stylesheet loader below! - - var obj = this; - this.loadStyleSheets(request,transport, function() { - obj.loadScripts(request,transport,callback); - }); - - */ - - this.loadStyleSheetsCode(request,transport); - - this.loadStyleSheetsAsync(request,transport); - - this.loadScripts(request,transport,callback); - }, - - checkHiddenField: function(name, value) + dispatchActions : function(request, datain) { - var id = name.replace(':','_'); - if (!document.getElementById(id)) - { - var field = document.createElement('input'); - field.setAttribute('type','hidden'); - field.id = id; - field.name = name; - field.value = value; - document.body.appendChild(field); - } - }, - - checkHiddenFields : function(request, transport) - { - var self = Prado.CallbackRequest; - var data = request.getBodyContentPart(self.HIDDENFIELDLIST_HEADER); + var data = Prado.Element.extractContent(datain, Prado.CallbackRequestManager.ACTION_HEADER); if (typeof(data) == "string" && data.length > 0) { - json = Prado.CallbackRequest.decode(data); + json = jQuery.parseJSON(data); if(typeof(json) != "object") Logger.warn("Invalid hidden field list:"+data); else for(var key in json) - this.checkHiddenField(key,json[key]); + this.__run(this, json[key]); } }, /** - * Updates the page state. It will update only if EnablePageStateUpdate and - * HasPriority options are both true. + * Prase and evaluate a Callback clien-side action */ - updatePageState : function(request, transport) + __run : function(request, command) { - var self = Prado.CallbackRequest; - var pagestate = $(self.FIELD_CALLBACK_PAGESTATE); - var enabled = request.ActiveControl.EnablePageStateUpdate && request.ActiveControl.HasPriority; - var aborted = typeof(self.currentRequest) == 'undefined' || self.currentRequest == null; - if(enabled && !aborted && pagestate) + for(var method in command) { - var data = request.getBodyContentPart(self.PAGESTATE_HEADER); - if(typeof(data) == "string" && data.length > 0) - pagestate.value = data; - else + try + { + method.toFunction().apply(request,command[method]); + } + catch(e) { if(typeof(Logger) != "undefined") - Logger.warn("Missing page state:"+data); - //Logger.warn('## bad state: setting current request to null'); - self.endCurrentRequest(); - //self.tryNextRequest(); - return false; + this.Exception.onException(null,e); + else + debugger; } } - self.endCurrentRequest(); - //Logger.warn('## state updated: setting current request to null'); - //self.tryNextRequest(); - return true; }, - enqueue : function(callback) - { - var self = Prado.CallbackRequest; - self.requestQueue.push(callback); - //Logger.warn("equeued "+callback.id+", current queque length="+self.requestQueue.length); - self.tryNextRequest(); - }, - - dispatchQueue : function() - { - var self = Prado.CallbackRequest; - //Logger.warn("dispatching queque, length="+self.requestQueue.length+" request="+self.currentRequest); - var callback = self.requestQueue.shift(); - self.currentRequest = callback; - - //get data - callback.options.postBody = callback._getPostData(), - - //callback.request = new Prado.AjaxRequest(callback); - callback.timeout = setTimeout(function() - { - //Logger.warn("priority timeout"); - self.abortRequest(callback.id); - },callback.ActiveControl.RequestTimeOut); - callback.request(callback.url); - //Logger.debug("dispatched "+self.currentRequest.id + " ...") - }, - - endCurrentRequest : function() - { - var self = Prado.CallbackRequest; - if(typeof(self.currentRequest) != 'undefined' && self.currentRequest != null) - clearTimeout(self.currentRequest.timeout); - self.currentRequest=null; - }, - - abortRequest : function(id) - { - //Logger.warn("abort id="+id); - var self = Prado.CallbackRequest; - if(typeof(self.currentRequest) != 'undefined' - && self.currentRequest != null && self.currentRequest.id == id) - { - var request = self.currentRequest; - if(request.transport.readyState < 4) - request.transport.abort(); - //Logger.warn('## aborted: setting current request to null'); - self.endCurrentRequest(); - } - self.tryNextRequest(); - } }); -/** - * Automatically aborts the current request when a priority request has returned. - */ -Ajax.Responders.register({onComplete : function(request) +Prado.CallbackRequest.addPostLoaders = function(ids) { - if(request && request instanceof Prado.AjaxRequest) - { - if(request.ActiveControl.HasPriority) - Prado.CallbackRequest.tryNextRequest(); - } -}}); + //dummy +}; -//Add HTTP exception respones when logger is enabled. -Event.OnLoad(function() -{ - if(typeof Logger != "undefined") - Ajax.Responders.register(Prado.CallbackRequest.Exception); -}); -/** - * Create and prepare a new callback request. - * Call the dispatch() method to start the callback request. - * <code> - * request = new Prado.CallbackRequest(UniqueID, callback); - * request.dispatch(); - * </code> - */ -Prado.CallbackRequest.prototype = Object.extend(Prado.AjaxRequest.prototype, -{ - /** - * Prepare and inititate a callback request. - */ - initialize : function(id, options) - { - /** - * Callback URL, same url as the current page. - */ - this.url = this.getCallbackUrl(); +// Prado.AjaxRequest = jQuery.klass(); +// Prado.AjaxRequest.prototype = { +// * Customize the response, dispatch onXXX response code events, and +// * tries to execute response actions (javascript statements). +// */ +// respondToReadyState : function(readyState) +// { +// var event = Ajax.Request.Events[readyState]; +// var transport = this.transport, json = this.getBodyDataPart(Prado.CallbackRequest.DATA_HEADER); + +// if (event == 'Complete') +// { + +// } + +// try { +// (this.options['on' + event] || Prototype.emptyFunction)(this, json); +// Ajax.Responders.dispatch('on' + event, this, transport, json); +// } catch (e) { +// this.dispatchException(e); +// } + +// /* Avoid memory leak in MSIE: clean up the oncomplete event handler */ +// if (event == 'Complete') +// this.transport.onreadystatechange = Prototype.emptyFunction; +// }, + +// /** +// * Gets header data assuming JSON encoding. +// * @param string header name +// * @return object header data as javascript structures. +// */ +// getHeaderData : function(name) +// { +// return this.getJsonData(this.getHeader(name)); +// }, + +// getJsonData : function(json) +// { +// try +// { +// return eval('(' + json + ')'); +// } +// catch (e) +// { +// if(typeof(json) == "string") +// return Prado.CallbackRequest.decode(json); +// } +// }, + +// getBodyDataPart : function(name) +// { +// return this.getJsonData(this.getBodyContentPart(name)); +// } +// }; + +// /** +// * Prado Callback client-side request handler. +// */ +// Prado.CallbackRequestManager = +// { +// /** +// * Callback request target POST field name. +// */ +// FIELD_CALLBACK_TARGET : 'PRADO_CALLBACK_TARGET', +// /** +// * Callback request parameter POST field name. +// */ +// FIELD_CALLBACK_PARAMETER : 'PRADO_CALLBACK_PARAMETER', +// /** +// * Callback request page state field name, +// */ +// FIELD_CALLBACK_PAGESTATE : 'PRADO_PAGESTATE', + +// FIELD_POSTBACK_TARGET : 'PRADO_POSTBACK_TARGET', + +// FIELD_POSTBACK_PARAMETER : 'PRADO_POSTBACK_PARAMETER', + +// /** +// * List of form fields that will be collected during callback. +// */ +// PostDataLoaders : [], + + + + +// requestQueue : [], + +// //all request objects +// requests : {}, + +// getRequestById : function(id) +// { +// var requests = Prado.CallbackRequest.requests; +// if(typeof(requests[id]) != "undefined") +// return requests[id]; +// }, + +// dispatch : function(id) +// { +// var requests = Prado.CallbackRequest.requests; +// if(typeof(requests[id]) != "undefined") +// requests[id].dispatch(); +// }, + +// /** +// * Add ids of inputs element to post in the request. +// */ +// addPostLoaders : function(ids) +// { +// var self = Prado.CallbackRequest; +// self.PostDataLoaders = self.PostDataLoaders.concat(ids); +// var list = []; +// self.PostDataLoaders.each(function(id) +// { +// if(list.indexOf(id) < 0) +// list.push(id); +// }); +// self.PostDataLoaders = list; +// }, + +// /** +// * Respond to Prado Callback request exceptions. +// */ +// Exception : +// { +// /** +// * Server returns 500 exception. Just log it. +// */ +// "on500" : function(request, transport, data) +// { +// var e = request.getHeaderData(Prado.CallbackRequest.ERROR_HEADER); +// if (e) +// Logger.error("Callback Server Error "+e.code, this.formatException(e)); +// else +// Logger.error("Callback Server Error Unknown",''); +// }, + +// /** +// * Callback OnComplete event,logs reponse and data to console. +// */ +// 'on200' : function(request, transport, data) +// { +// if(transport.status < 500) +// { +// var msg = 'HTTP '+transport.status+" with response : \n"; +// if(transport.responseText.trim().length >0) +// { +// var f = RegExp('(<!--X-PRADO[^>]+-->)([\\s\\S\\w\\W]*)(<!--//X-PRADO[^>]+-->)',"m"); +// msg += transport.responseText.replace(f,'') + "\n"; +// } +// if(typeof(data)!="undefined" && data != null) +// msg += "Data : \n"+inspect(data)+"\n"; +// data = request.getBodyDataPart(Prado.CallbackRequest.ACTION_HEADER); +// if(data && data.length > 0) +// { +// msg += "Actions : \n"; +// data.each(function(action) +// { +// msg += inspect(action)+"\n"; +// }); +// } +// Logger.info(msg); +// } +// }, + +// /** +// * Uncaught exceptions during callback response. +// */ +// onException : function(request,e) +// { +// var msg = ""; +// $H(e).each(function(item) +// { +// msg += item.key+": "+item.value+"\n"; +// }) +// Logger.error('Uncaught Callback Client Exception:', msg); +// }, + +// /** +// * Formats the exception message for display in console. +// */ +// formatException : function(e) +// { +// var msg = e.type + " with message \""+e.message+"\""; +// msg += " in "+e.file+"("+e.line+")\n"; +// msg += "Stack trace:\n"; +// var trace = e.trace; +// for(var i = 0; i<trace.length; i++) +// { +// msg += " #"+i+" "+trace[i].file; +// msg += "("+trace[i].line+"): "; +// msg += trace[i]["class"]+"->"+trace[i]["function"]+"()"+"\n"; +// } +// msg += e.version+" "+e.time+"\n"; +// return msg; +// } +// }, + +// /** +// * Dispatch a normal request, no timeouts or aborting of requests. +// */ +// dispatchNormalRequest : function(callback) +// { +// callback.options.postBody = callback._getPostData(), +// //callback.request(callback.url); +// jQuery.ajax(callback.url, callback.options); +// return true; +// }, + +// /** +// * Abort the current priority request in progress. +// */ +// tryNextRequest : function() +// { +// var self = Prado.CallbackRequest; +// //Logger.debug('trying next request'); +// if(typeof(self.currentRequest) == 'undefined' || self.currentRequest==null) +// { +// if(self.requestQueue.length > 0) +// return self.dispatchQueue(); +// //else +// //Logger.warn('empty queque'); +// } +// //else +// //Logger.warn('current request ' + self.currentRequest.id); +// }, + +// enqueue : function(callback) +// { +// var self = Prado.CallbackRequest; +// self.requestQueue.push(callback); +// //Logger.warn("equeued "+callback.id+", current queque length="+self.requestQueue.length); +// self.tryNextRequest(); +// }, + +// dispatchQueue : function() +// { +// var self = Prado.CallbackRequest; +// //Logger.warn("dispatching queque, length="+self.requestQueue.length+" request="+self.currentRequest); +// var callback = self.requestQueue.shift(); +// self.currentRequest = callback; + +// //get data +// callback.options.postBody = callback._getPostData(), + +// //callback.request = new Prado.AjaxRequest(callback); +// callback.timeout = setTimeout(function() +// { +// //Logger.warn("priority timeout"); +// self.abortRequest(callback.id); +// },callback.ActiveControl.RequestTimeOut); +// callback.request(callback.url); +// //Logger.debug("dispatched "+self.currentRequest.id + " ...") +// }, + +// endCurrentRequest : function() +// { +// var self = Prado.CallbackRequest; +// if(typeof(self.currentRequest) != 'undefined' && self.currentRequest != null) +// clearTimeout(self.currentRequest.timeout); +// self.currentRequest=null; +// }, + +// abortRequest : function(id) +// { +// //Logger.warn("abort id="+id); +// var self = Prado.CallbackRequest; +// if(typeof(self.currentRequest) != 'undefined' +// && self.currentRequest != null && self.currentRequest.id == id) +// { +// var request = self.currentRequest; +// if(request.transport.readyState < 4) +// request.transport.abort(); +// //Logger.warn('## aborted: setting current request to null'); +// self.endCurrentRequest(); +// } +// self.tryNextRequest(); +// } +// }; + +// /** +// * Automatically aborts the current request when a priority request has returned. +// */ +// /* +// Ajax.Responders.register({onComplete : function(request) +// { +// if(request && request instanceof Prado.AjaxRequest) +// { +// if(request.ActiveControl.HasPriority) +// Prado.CallbackRequest.tryNextRequest(); +// } +// }}); +// */ +// //Add HTTP exception respones when logger is enabled. +// /* +// Event.OnLoad(function() +// { +// if(typeof Logger != "undefined") +// Ajax.Responders.register(Prado.CallbackRequest.Exception); +// }); +// */ + +// /** +// * Create and prepare a new callback request. +// * Call the dispatch() method to start the callback request. +// * <code> +// * request = new Prado.CallbackRequest(UniqueID, callback); +// * request.dispatch(); +// * </code> +// */ +// Prado.CallbackRequest = jQuery.klass({ + +// /** +// * Prepare and inititate a callback request. +// */ +// initialize : function(id, options) +// { +// /** +// * Callback URL, same url as the current page. +// */ +// this.url = this.getCallbackUrl(); - this.transport = Ajax.getTransport(); - this.Enabled = true; - this.id = id; - this.randomId = this.randomString(); +// //this.transport = Ajax.getTransport(); +// this.Enabled = true; +// this.id = id; +// this.randomId = this.randomString(); - if(typeof(id)=="string"){ - Prado.CallbackRequest.requests[id+"__"+this.randomId] = this; - } +// if(typeof(id)=="string"){ +// Prado.CallbackRequestManager.requests[id+"__"+this.randomId] = this; +// } - this.setOptions(Object.extend( - { - RequestTimeOut : 30000, // 30 second timeout. - EnablePageStateUpdate : true, - HasPriority : true, - CausesValidation : true, - ValidationGroup : null, - PostInputs : true - }, options || {})); - - this.ActiveControl = this.options; - Prado.CallbackRequest.requests[id+"__"+this.randomId].ActiveControl = this.options; - }, +// this.setOptions(jQuery.extend( +// { +// RequestTimeOut : 30000, // 30 second timeout. +// EnablePageStateUpdate : true, +// HasPriority : true, +// CausesValidation : true, +// ValidationGroup : null, +// PostInputs : true +// }, options || {})); + +// this.ActiveControl = this.options; +// Prado.CallbackRequestManager.requests[id+"__"+this.randomId].ActiveControl = this.options; +// }, - /** - * Sets the request options - * @return {Array} request options. - */ - setOptions: function(options){ +// /** +// * Sets the request options +// * @return {Array} request options. +// */ +// setOptions: function(options){ - this.options = { - method: 'post', - asynchronous: true, - contentType: 'application/x-www-form-urlencoded', - encoding: 'UTF-8', - parameters: '', - evalJSON: true, - evalJS: true - }; +// this.options = { +// method: 'post', +// asynchronous: true, +// contentType: 'application/x-www-form-urlencoded', +// encoding: 'UTF-8', +// parameters: '', +// evalJSON: true, +// evalJS: true +// }; - Object.extend(this.options, options || { }); +// jQuery.extend(this.options, options || { }); - this.options.method = this.options.method.toLowerCase(); - if(Object.isString(this.options.parameters)){ - this.options.parameters = this.options.parameters.toQueryParams(); - } - }, +// this.options.method = this.options.method.toLowerCase(); +// if(jQuery.type(this.options.parameters) === "string") { +// //this.options.parameters = this.options.parameters.toQueryParams(); +// } +// }, - /** - * Gets the url from the forms that contains the PRADO_PAGESTATE - * @return {String} callback url. - */ - getCallbackUrl : function() - { - return $('PRADO_PAGESTATE').form.action; - }, +// /** +// * Gets the url from the forms that contains the PRADO_PAGESTATE +// * @return {String} callback url. +// */ +// getCallbackUrl : function() +// { +// return jQuery('#PRADO_PAGESTATE').get(0).form.action; +// }, + +// /** +// * Sets the request parameter +// * @param {Object} parameter value +// */ +// setCallbackParameter : function(value) +// { +// var requestId = this.id+"__"+this.randomId; +// this.ActiveControl['CallbackParameter'] = value; +// Prado.CallbackRequestManager.requests[requestId].ActiveControl['CallbackParameter'] = value; +// }, + +// /** +// * @return {Object} request paramater value. +// */ +// getCallbackParameter : function() +// { +// return Prado.CallbackRequestManager.requests[this.id+"__"+this.randomId].ActiveControl['CallbackParameter']; +// }, + +// /** +// * Sets the callback request timeout. +// * @param {integer} timeout in milliseconds +// */ +// setRequestTimeOut : function(timeout) +// { +// this.ActiveControl['RequestTimeOut'] = timeout; +// }, + +// /** +// * @return {integer} request timeout in milliseconds +// */ +// getRequestTimeOut : function() +// { +// return this.ActiveControl['RequestTimeOut']; +// }, + +// /** +// * Set true to enable validation on callback dispatch. +// * @param {boolean} true to validate +// */ +// setCausesValidation : function(validate) +// { +// this.ActiveControl['CausesValidation'] = validate; +// }, + +// /** +// * @return {boolean} validate on request dispatch +// */ +// getCausesValidation : function() +// { +// return this.ActiveControl['CausesValidation']; +// }, + +// /** +// * Sets the validation group to validate during request dispatch. +// * @param {string} validation group name +// */ +// setValidationGroup : function(group) +// { +// this.ActiveControl['ValidationGroup'] = group; +// }, + +// /** +// * @return {string} validation group name. +// */ +// getValidationGroup : function() +// { +// return this.ActiveControl['ValidationGroup']; +// }, + +// /** +// * Dispatch the callback request. +// */ +// dispatch : function() +// { +// //Logger.info("dispatching request"); +// //trigger tinyMCE to save data. +// if(typeof tinyMCE != "undefined") +// tinyMCE.triggerSave(); + +// if(this.ActiveControl.CausesValidation && typeof(Prado.Validation) != "undefined") +// { +// var form = this.ActiveControl.Form || Prado.Validation.getForm(); +// if(Prado.Validation.validate(form,this.ActiveControl.ValidationGroup,this) == false) +// return false; +// } + +// if(this.ActiveControl.onPreDispatch) +// this.ActiveControl.onPreDispatch(this,null); + +// if(!this.Enabled) +// return; + +// // Opera don't have onLoading/onLoaded state, so, simulate them just +// // before sending the request. +// /* +// if (Prototype.Browser.Opera) +// { +// if (this.ActiveControl.onLoading) +// { +// this.ActiveControl.onLoading(this,null); +// Ajax.Responders.dispatch('onLoading',this, this.transport,null); +// } +// if (this.ActiveControl.onLoaded) +// { +// this.ActiveControl.onLoaded(this,null); +// Ajax.Responders.dispatch('onLoaded',this, this.transport,null); +// } +// } +// */ +// var result; +// if(this.ActiveControl.HasPriority) +// { +// return Prado.CallbackRequestManager.enqueue(this); +// //return Prado.CallbackRequest.dispatchPriorityRequest(this); +// } +// else +// return Prado.CallbackRequestManager.dispatchNormalRequest(this); +// }, + +// abort : function() +// { +// return Prado.CallbackRequestManager.abortRequest(this.id); +// }, + +// /** +// * Collects the form inputs, encode the parameters, and sets the callback +// * target id. The resulting string is the request content body. +// * @return string request body content containing post data. +// */ +// _getPostData : function() +// { +// var data = {}; +// var callback = Prado.CallbackRequest; +// if(this.ActiveControl.PostInputs != false) +// { +// callback.PostDataLoaders.each(function(name) +// { +// var elements=$A(document.getElementsByName(name)); +// if(elements.size() == 0) +// { +// name += '[]'; +// elements=$A(document.getElementsByName(name)); +// } +// elements.each(function(element) +// { +// //IE will try to get elements with ID == name as well. +// if(element.type && element.name == name) +// { +// var value = $F(element); +// if(typeof(value) != "undefined" && value != null) +// data[name] = value; +// } +// }) +// }) +// } +// if(typeof(this.ActiveControl.CallbackParameter) != "undefined") +// data[callback.FIELD_CALLBACK_PARAMETER] = callback.encode(this.getCallbackParameter()); +// var pageState = $F(callback.FIELD_CALLBACK_PAGESTATE); +// if(typeof(pageState) != "undefined") +// data[callback.FIELD_CALLBACK_PAGESTATE] = pageState; +// data[callback.FIELD_CALLBACK_TARGET] = this.id; +// if(this.ActiveControl.EventTarget) +// data[callback.FIELD_POSTBACK_TARGET] = this.ActiveControl.EventTarget; +// if(this.ActiveControl.EventParameter) +// data[callback.FIELD_POSTBACK_PARAMETER] = this.ActiveControl.EventParameter; +// return $H(data).toQueryString(); +// }, + +// /** +// * Creates a random string with a length of 8 chars. +// * @return string +// */ +// randomString : function() +// { +// chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"; +// randomString = ""; +// for(x=0;x<8;x++) +// randomString += chars.charAt(Math.floor(Math.random() * 62)); +// return randomString +// } +// }); + +// /** +// * Create a new callback request using default settings. +// * @param string callback handler unique ID. +// * @param mixed parameter to pass to callback handler on the server side. +// * @param function client side onSuccess event handler. +// * @param object additional request options. +// * @return boolean always false. +// */ +// Prado.Callback = function(UniqueID, parameter, onSuccess, options) +// { +// var callback = +// { +// 'CallbackParameter' : parameter || '', +// 'onSuccess' : onSuccess || Prototype.emptyFunction +// }; + +// Object.extend(callback, options || {}); + +// var request = new Prado.CallbackRequest(UniqueID, callback); +// request.dispatch(); +// return false; +// }; - /** - * Sets the request parameter - * @param {Object} parameter value - */ - setCallbackParameter : function(value) - { - var requestId = this.id+"__"+this.randomId; - this.ActiveControl['CallbackParameter'] = value; - Prado.CallbackRequest.requests[requestId].ActiveControl['CallbackParameter'] = value; - }, - /** - * @return {Object} request paramater value. - */ - getCallbackParameter : function() - { - return Prado.CallbackRequest.requests[this.id+"__"+this.randomId].ActiveControl['CallbackParameter']; - }, - /** - * Sets the callback request timeout. - * @param {integer} timeout in milliseconds - */ - setRequestTimeOut : function(timeout) - { - this.ActiveControl['RequestTimeOut'] = timeout; - }, +/** +* Asset manager classes for lazy loading of scripts and stylesheets +* @author Gabor Berczi (gabor.berczi@devworx.hu) +*/ - /** - * @return {integer} request timeout in milliseconds - */ - getRequestTimeOut : function() - { - return this.ActiveControl['RequestTimeOut']; - }, +if (typeof(Prado.AssetManagerClass)=="undefined") { - /** - * Set true to enable validation on callback dispatch. - * @param {boolean} true to validate - */ - setCausesValidation : function(validate) - { - this.ActiveControl['CausesValidation'] = validate; - }, + Prado.AssetManagerClass = jQuery.klass(); + Prado.AssetManagerClass.prototype = { - /** - * @return {boolean} validate on request dispatch - */ - getCausesValidation : function() - { - return this.ActiveControl['CausesValidation']; - }, + initialize: function() { + this.loadedAssets = new Array(); + this.discoverLoadedAssets(); + }, - /** - * Sets the validation group to validate during request dispatch. - * @param {string} validation group name - */ - setValidationGroup : function(group) - { - this.ActiveControl['ValidationGroup'] = group; - }, - /** - * @return {string} validation group name. - */ - getValidationGroup : function() - { - return this.ActiveControl['ValidationGroup']; - }, + /** + * Detect which assets are already loaded by page markup. + * This is done by looking up all <asset> elements and registering the values of their src attributes. + */ + discoverLoadedAssets: function() { - /** - * Dispatch the callback request. - */ - dispatch : function() - { - //Logger.info("dispatching request"); - //trigger tinyMCE to save data. - if(typeof tinyMCE != "undefined") - tinyMCE.triggerSave(); + // wait until document has finished loading to avoid javascript errors + if (!document.body) return; - if(this.ActiveControl.CausesValidation && typeof(Prado.Validation) != "undefined") - { - var form = this.ActiveControl.Form || Prado.Validation.getForm(); - if(Prado.Validation.validate(form,this.ActiveControl.ValidationGroup,this) == false) - return false; - } + var assets = this.findAssetUrlsInMarkup(); + for(var i=0;i<assets.length;i++) + this.markAssetAsLoaded(assets[i]); + }, - if(this.ActiveControl.onPreDispatch) - this.ActiveControl.onPreDispatch(this,null); + /** + * Extend url to a fully qualified url. + * @param string url + */ + makeFullUrl: function(url) { - if(!this.Enabled) - return; - - // Opera don't have onLoading/onLoaded state, so, simulate them just - // before sending the request. - if (Prototype.Browser.Opera) - { - if (this.ActiveControl.onLoading) - { - this.ActiveControl.onLoading(this,null); - Ajax.Responders.dispatch('onLoading',this, this.transport,null); - } - if (this.ActiveControl.onLoaded) - { - this.ActiveControl.onLoaded(this,null); - Ajax.Responders.dispatch('onLoaded',this, this.transport,null); - } - } - - var result; - if(this.ActiveControl.HasPriority) - { - return Prado.CallbackRequest.enqueue(this); - //return Prado.CallbackRequest.dispatchPriorityRequest(this); - } - else - return Prado.CallbackRequest.dispatchNormalRequest(this); - }, + // this is not intended to be a fully blown url "canonicalizator", + // just to handle the most common and basic asset paths used by Prado - abort : function() - { - return Prado.CallbackRequest.abortRequest(this.id); - }, + if (!this.baseUri) this.baseUri = window.location; - /** - * Collects the form inputs, encode the parameters, and sets the callback - * target id. The resulting string is the request content body. - * @return string request body content containing post data. - */ - _getPostData : function() - { - var data = {}; - var callback = Prado.CallbackRequest; - if(this.ActiveControl.PostInputs != false) - { - callback.PostDataLoaders.each(function(name) + if (url.indexOf('://')==-1) { - var elements=$A(document.getElementsByName(name)); - if(elements.size() == 0) - { - name += '[]'; - elements=$A(document.getElementsByName(name)); - } - elements.each(function(element) - { - //IE will try to get elements with ID == name as well. - if(element.type && element.name == name) + var a = document.createElement('a'); + a.href = url; + + if (a.href.indexOf('://')!=-1) + url = a.href; + else { - var value = $F(element); - if(typeof(value) != "undefined" && value != null) - data[name] = value; + var path = a.pathname; + if (path.substr(0,1)!='/') path = '/'+path; + url = this.baseUri.protocol+'//'+this.baseUri.host+path; } - }) - }) - } - if(typeof(this.ActiveControl.CallbackParameter) != "undefined") - data[callback.FIELD_CALLBACK_PARAMETER] = callback.encode(this.getCallbackParameter()); - var pageState = $F(callback.FIELD_CALLBACK_PAGESTATE); - if(typeof(pageState) != "undefined") - data[callback.FIELD_CALLBACK_PAGESTATE] = pageState; - data[callback.FIELD_CALLBACK_TARGET] = this.id; - if(this.ActiveControl.EventTarget) - data[callback.FIELD_POSTBACK_TARGET] = this.ActiveControl.EventTarget; - if(this.ActiveControl.EventParameter) - data[callback.FIELD_POSTBACK_PARAMETER] = this.ActiveControl.EventParameter; - return $H(data).toQueryString(); - }, - - /** - * Creates a random string with a length of 8 chars. - * @return string - */ - randomString : function() - { - chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"; - randomString = ""; - for(x=0;x<8;x++) - randomString += chars.charAt(Math.floor(Math.random() * 62)); - return randomString - } -}); - -/** - * Create a new callback request using default settings. - * @param string callback handler unique ID. - * @param mixed parameter to pass to callback handler on the server side. - * @param function client side onSuccess event handler. - * @param object additional request options. - * @return boolean always false. - */ -Prado.Callback = function(UniqueID, parameter, onSuccess, options) -{ - var callback = - { - 'CallbackParameter' : parameter || '', - 'onSuccess' : onSuccess || Prototype.emptyFunction - }; - - Object.extend(callback, options || {}); - - var request = new Prado.CallbackRequest(UniqueID, callback); - request.dispatch(); - return false; -}; - - - -/** - * Asset manager classes for lazy loading of scripts and stylesheets - * @author Gabor Berczi (gabor.berczi@devworx.hu) - */ + } + return url; + }, -if (typeof(Prado.AssetManagerClass)=="undefined") { + isAssetLoaded: function(url) { + url = this.makeFullUrl(url); + return (this.loadedAssets.indexOf(url)!=-1); + }, - Prado.AssetManagerClass = jQuery.klass(); - Prado.AssetManagerClass.prototype = { + /** + * Mark asset as being already loaded + * @param string url of the asset + */ + markAssetAsLoaded: function(url) { + url = this.makeFullUrl(url); + if (this.loadedAssets.indexOf(url)==-1) + this.loadedAssets.push(url); + }, - initialize: function() { - this.loadedAssets = new Array(); - this.discoverLoadedAssets(); - }, + assetReadyStateChanged: function(url, element, callback, finalevent) { + if (finalevent || (element.readyState == 'loaded') || (element.readyState == 'complete')) + if (!element.assetCallbackFired) + { + element.assetCallbackFired = true; + callback(url,element); + } + }, - - /** - * Detect which assets are already loaded by page markup. - * This is done by looking up all <asset> elements and registering the values of their src attributes. - */ - discoverLoadedAssets: function() { + assetLoadFailed: function(url, element, callback) { + debugger; + element.assetCallbackFired = true; + if(typeof Logger != "undefined") + Logger.error("Failed to load asset: "+url, this); + if (!element.assetCallbackFired) + callback(url,element,false); + }, - // wait until document has finished loading to avoid javascript errors - if (!document.body) return; + /** + * Load a new asset dynamically into the page. + * Please not thet loading is asynchronous and therefore you can't assume that + * the asset is loaded and ready when returning from this function. + * @param string url of the asset to load + * @param callback will be called when the asset has loaded (or failed to load) + */ + startAssetLoad: function(url, callback) { - var assets = this.findAssetUrlsInMarkup(); - for(var i=0;i<assets.length;i++) - this.markAssetAsLoaded(assets[i]); - }, + // create new <asset> element in page header + var asset = this.createAssetElement(url); - /** - * Extend url to a fully qualified url. - * @param string url - */ - makeFullUrl: function(url) { + if (callback) + { + asset.onreadystatechange = this.assetReadyStateChanged.bind(this, url, asset, callback, false); + asset.onload = this.assetReadyStateChanged.bind(this, url, asset, callback, true); + asset.onerror = this.assetLoadFailed.bind(this, url, asset, callback); + asset.assetCallbackFired = false; + } - // this is not intended to be a fully blown url "canonicalizator", - // just to handle the most common and basic asset paths used by Prado + var head = document.getElementsByTagName('head')[0]; + head.appendChild(asset); - if (!this.baseUri) this.baseUri = window.location; + // mark this asset as loaded + this.markAssetAsLoaded(url); - if (url.indexOf('://')==-1) - { - var a = document.createElement('a'); - a.href = url; + return (callback!=false); + }, - if (a.href.indexOf('://')!=-1) - url = a.href; - else + /** + * Check whether a asset is loaded into the page, and if itsn't, load it now + * @param string url of the asset to check/load + * @return boolean returns true if asset is already loaded, or false, if loading has just started. callback will be called when loading has finished. + */ + ensureAssetIsLoaded: function(url, callback) { + url = this.makeFullUrl(url); + if (this.loadedAssets.indexOf(url)==-1) { - var path = a.pathname; - if (path.substr(0,1)!='/') path = '/'+path; - url = this.baseUri.protocol+'//'+this.baseUri.host+path; + this.startAssetLoad(url,callback); + return false; } + else + return true; } - return url; - }, - - isAssetLoaded: function(url) { - url = this.makeFullUrl(url); - return (this.loadedAssets.indexOf(url)!=-1); - }, - - /** - * Mark asset as being already loaded - * @param string url of the asset - */ - markAssetAsLoaded: function(url) { - url = this.makeFullUrl(url); - if (this.loadedAssets.indexOf(url)==-1) - this.loadedAssets.push(url); - }, - - assetReadyStateChanged: function(url, element, callback, finalevent) { - if (finalevent || (element.readyState == 'loaded') || (element.readyState == 'complete')) - if (!element.assetCallbackFired) - { - element.assetCallbackFired = true; - callback(url,element); - } - }, - - assetLoadFailed: function(url, element, callback) { - debugger; - element.assetCallbackFired = true; - if(typeof Logger != "undefined") - Logger.error("Failed to load asset: "+url, this); - if (!element.assetCallbackFired) - callback(url,element,false); - }, - - /** - * Load a new asset dynamically into the page. - * Please not thet loading is asynchronous and therefore you can't assume that - * the asset is loaded and ready when returning from this function. - * @param string url of the asset to load - * @param callback will be called when the asset has loaded (or failed to load) - */ - startAssetLoad: function(url, callback) { - - // create new <asset> element in page header - var asset = this.createAssetElement(url); - - if (callback) - { - asset.onreadystatechange = this.assetReadyStateChanged.bind(this, url, asset, callback, false); - asset.onload = this.assetReadyStateChanged.bind(this, url, asset, callback, true); - asset.onerror = this.assetLoadFailed.bind(this, url, asset, callback); - asset.assetCallbackFired = false; - } - - var head = document.getElementsByTagName('head')[0]; - head.appendChild(asset); - - // mark this asset as loaded - this.markAssetAsLoaded(url); - return (callback!=false); - }, - - /** - * Check whether a asset is loaded into the page, and if itsn't, load it now - * @param string url of the asset to check/load - * @return boolean returns true if asset is already loaded, or false, if loading has just started. callback will be called when loading has finished. - */ - ensureAssetIsLoaded: function(url, callback) { - url = this.makeFullUrl(url); - if (this.loadedAssets.indexOf(url)==-1) - { - this.startAssetLoad(url,callback); - return false; - } - else - return true; } - } - }; - Prado.ScriptManagerClass = Class.extend(Prado.AssetManagerClass, { +Prado.ScriptManagerClass = jQuery.klass(Prado.AssetManagerClass, { findAssetUrlsInMarkup: function() { var urls = new Array(); @@ -1118,16 +1139,16 @@ if (typeof(Prado.AssetManagerClass)=="undefined") { }, createAssetElement: function(url) { - var asset = document.createElement('script'); - asset.type = 'text/javascript'; - asset.src = url; -// asset.async = false; // HTML5 only + var asset = document.createElement('script'); + asset.type = 'text/javascript'; + asset.src = url; + // asset.async = false; // HTML5 only return asset; } - }); +}); - Prado.StyleSheetManagerClass = Class.extend(Prado.AssetManagerClass, { +Prado.StyleSheetManagerClass = jQuery.klass(Prado.AssetManagerClass, { findAssetUrlsInMarkup: function() { var urls = new Array(); @@ -1142,34 +1163,34 @@ if (typeof(Prado.AssetManagerClass)=="undefined") { }, createAssetElement: function(url) { - var asset = document.createElement('link'); - asset.rel = 'stylesheet'; - asset.media = 'screen'; - asset.setAttribute('type', 'text/css'); - asset.href = url; -// asset.async = false; // HTML5 only + var asset = document.createElement('link'); + asset.rel = 'stylesheet'; + asset.media = 'screen'; + asset.setAttribute('type', 'text/css'); + asset.href = url; + // asset.async = false; // HTML5 only return asset; }, createStyleSheetCode: function(code) { - var asset = document.createElement('style'); - asset.setAttribute('type', 'text/css'); + var asset = document.createElement('style'); + asset.setAttribute('type', 'text/css'); asset.innerText = code; var head = document.getElementsByTagName('head')[0]; - head.appendChild(asset); + head.appendChild(asset); } - }); +}); - if (typeof(Prado.ScriptManager)=="undefined") Prado.ScriptManager = new Prado.ScriptManagerClass(); - if (typeof(Prado.StyleSheetManager)=="undefined") Prado.StyleSheetManager = new Prado.StyleSheetManagerClass(); +if (typeof(Prado.ScriptManager)=="undefined") Prado.ScriptManager = new Prado.ScriptManagerClass(); +if (typeof(Prado.StyleSheetManager)=="undefined") Prado.StyleSheetManager = new Prado.StyleSheetManagerClass(); - // make sure we scan for loaded scripts again when the page has been loaded - var discover = function() { +// make sure we scan for loaded scripts again when the page has been loaded +var discover = function() { Prado.ScriptManager.discoverLoadedAssets(); Prado.StyleSheetManager.discoverLoadedAssets(); - } - if (window.attachEvent) window.attachEvent('onload', discover); - else if (window.addEventListener) window.addEventListener('load', discover, false); +} +if (window.attachEvent) window.attachEvent('onload', discover); +else if (window.addEventListener) window.addEventListener('load', discover, false); diff --git a/framework/Web/Javascripts/source/prado/activecontrols/json2.js b/framework/Web/Javascripts/source/prado/activecontrols/json2.js deleted file mode 100644 index 3eec6f20..00000000 --- a/framework/Web/Javascripts/source/prado/activecontrols/json2.js +++ /dev/null @@ -1,479 +0,0 @@ -/* - http://www.JSON.org/json2.js - 2011-02-23 - - Public Domain. - - NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK. - - See http://www.JSON.org/js.html - - - This code should be minified before deployment. - See http://javascript.crockford.com/jsmin.html - - USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO - NOT CONTROL. - - - This file creates a global JSON object containing two methods: stringify - and parse. - - JSON.stringify(value, replacer, space) - value any JavaScript value, usually an object or array. - - replacer an optional parameter that determines how object - values are stringified for objects. It can be a - function or an array of strings. - - space an optional parameter that specifies the indentation - of nested structures. If it is omitted, the text will - be packed without extra whitespace. If it is a number, - it will specify the number of spaces to indent at each - level. If it is a string (such as '\t' or ' '), - it contains the characters used to indent at each level. - - This method produces a JSON text from a JavaScript value. - - When an object value is found, if the object contains a toJSON - method, its toJSON method will be called and the result will be - stringified. A toJSON method does not serialize: it returns the - value represented by the name/value pair that should be serialized, - or undefined if nothing should be serialized. The toJSON method - will be passed the key associated with the value, and this will be - bound to the value - - For example, this would serialize Dates as ISO strings. - - Date.prototype.toJSON = function (key) { - function f(n) { - // Format integers to have at least two digits. - return n < 10 ? '0' + n : n; - } - - return this.getUTCFullYear() + '-' + - f(this.getUTCMonth() + 1) + '-' + - f(this.getUTCDate()) + 'T' + - f(this.getUTCHours()) + ':' + - f(this.getUTCMinutes()) + ':' + - f(this.getUTCSeconds()) + 'Z'; - }; - - You can provide an optional replacer method. It will be passed the - key and value of each member, with this bound to the containing - object. The value that is returned from your method will be - serialized. If your method returns undefined, then the member will - be excluded from the serialization. - - If the replacer parameter is an array of strings, then it will be - used to select the members to be serialized. It filters the results - such that only members with keys listed in the replacer array are - stringified. - - Values that do not have JSON representations, such as undefined or - functions, will not be serialized. Such values in objects will be - dropped; in arrays they will be replaced with null. You can use - a replacer function to replace those with JSON values. - JSON.stringify(undefined) returns undefined. - - The optional space parameter produces a stringification of the - value that is filled with line breaks and indentation to make it - easier to read. - - If the space parameter is a non-empty string, then that string will - be used for indentation. If the space parameter is a number, then - the indentation will be that many spaces. - - Example: - - text = JSON.stringify(['e', {pluribus: 'unum'}]); - // text is '["e",{"pluribus":"unum"}]' - - - text = JSON.stringify(['e', {pluribus: 'unum'}], null, '\t'); - // text is '[\n\t"e",\n\t{\n\t\t"pluribus": "unum"\n\t}\n]' - - text = JSON.stringify([new Date()], function (key, value) { - return this[key] instanceof Date ? - 'Date(' + this[key] + ')' : value; - }); - // text is '["Date(---current time---)"]' - - - JSON.parse(text, reviver) - This method parses a JSON text to produce an object or array. - It can throw a SyntaxError exception. - - The optional reviver parameter is a function that can filter and - transform the results. It receives each of the keys and values, - and its return value is used instead of the original value. - If it returns what it received, then the structure is not modified. - If it returns undefined then the member is deleted. - - Example: - - // Parse the text. Values that look like ISO date strings will - // be converted to Date objects. - - myData = JSON.parse(text, function (key, value) { - var a; - if (typeof value === 'string') { - a = -/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value); - if (a) { - return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4], - +a[5], +a[6])); - } - } - return value; - }); - - myData = JSON.parse('["Date(09/09/2001)"]', function (key, value) { - var d; - if (typeof value === 'string' && - value.slice(0, 5) === 'Date(' && - value.slice(-1) === ')') { - d = new Date(value.slice(5, -1)); - if (d) { - return d; - } - } - return value; - }); - - - This is a reference implementation. You are free to copy, modify, or - redistribute. -*/ - -/*jslint evil: true, strict: false, regexp: false */ - -/*members "", "\b", "\t", "\n", "\f", "\r", "\"", JSON, "\\", apply, - call, charCodeAt, getUTCDate, getUTCFullYear, getUTCHours, - getUTCMinutes, getUTCMonth, getUTCSeconds, hasOwnProperty, join, - lastIndex, length, parse, prototype, push, replace, slice, stringify, - test, toJSON, toString, valueOf -*/ - - -// Create a JSON object only if one does not already exist. We create the -// methods in a closure to avoid creating global variables. - -if (!Prado.JSON) { - Prado.JSON = {}; -} - -(function () { - "use strict"; - - function f(n) { - // Format integers to have at least two digits. - return n < 10 ? '0' + n : n; - } - - if (typeof Date.prototype.toJSON !== 'function') { - - Date.prototype.toJSON = function (key) { - - return isFinite(this.valueOf()) ? - this.getUTCFullYear() + '-' + - f(this.getUTCMonth() + 1) + '-' + - f(this.getUTCDate()) + 'T' + - f(this.getUTCHours()) + ':' + - f(this.getUTCMinutes()) + ':' + - f(this.getUTCSeconds()) + 'Z' : null; - }; - - String.prototype.toJSON = - Number.prototype.toJSON = - Boolean.prototype.toJSON = function (key) { - return this.valueOf(); - }; - } - - var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, - escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, - gap, - indent, - meta = { // table of character substitutions - '\b': '\\b', - '\t': '\\t', - '\n': '\\n', - '\f': '\\f', - '\r': '\\r', - '"' : '\\"', - '\\': '\\\\' - }, - rep; - - - function quote(string) { - -// If the string contains no control characters, no quote characters, and no -// backslash characters, then we can safely slap some quotes around it. -// Otherwise we must also replace the offending characters with safe escape -// sequences. - - escapable.lastIndex = 0; - return escapable.test(string) ? '"' + string.replace(escapable, function (a) { - var c = meta[a]; - return typeof c === 'string' ? c : - '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); - }) + '"' : '"' + string + '"'; - } - - - function str(key, holder) { - -// Produce a string from holder[key]. - - var i, // The loop counter. - k, // The member key. - v, // The member value. - length, - mind = gap, - partial, - value = holder[key]; - -// If the value has a toJSON method, call it to obtain a replacement value. - - if (value && typeof value === 'object' && - typeof value.toJSON === 'function') { - value = value.toJSON(key); - } - -// If we were called with a replacer function, then call the replacer to -// obtain a replacement value. - - if (typeof rep === 'function') { - value = rep.call(holder, key, value); - } - -// What happens next depends on the value's type. - - switch (typeof value) { - case 'string': - return quote(value); - - case 'number': - -// JSON numbers must be finite. Encode non-finite numbers as null. - - return isFinite(value) ? String(value) : 'null'; - - case 'boolean': - case 'null': - -// If the value is a boolean or null, convert it to a string. Note: -// typeof null does not produce 'null'. The case is included here in -// the remote chance that this gets fixed someday. - - return String(value); - -// If the type is 'object', we might be dealing with an object or an array or -// null. - - case 'object': - -// Due to a specification blunder in ECMAScript, typeof null is 'object', -// so watch out for that case. - - if (!value) { - return 'null'; - } - -// Make an array to hold the partial results of stringifying this object value. - - gap += indent; - partial = []; - -// Is the value an array? - - if (Object.prototype.toString.apply(value) === '[object Array]') { - -// The value is an array. Stringify every element. Use null as a placeholder -// for non-JSON values. - - length = value.length; - for (i = 0; i < length; i += 1) { - partial[i] = str(i, value) || 'null'; - } - -// Join all of the elements together, separated with commas, and wrap them in -// brackets. - - v = partial.length === 0 ? '[]' : gap ? - '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']' : - '[' + partial.join(',') + ']'; - gap = mind; - return v; - } - -// If the replacer is an array, use it to select the members to be stringified. - - if (rep && typeof rep === 'object') { - length = rep.length; - for (i = 0; i < length; i += 1) { - if (typeof rep[i] === 'string') { - k = rep[i]; - v = str(k, value); - if (v) { - partial.push(quote(k) + (gap ? ': ' : ':') + v); - } - } - } - } else { - -// Otherwise, iterate through all of the keys in the object. - - for (k in value) { - if (Object.prototype.hasOwnProperty.call(value, k)) { - v = str(k, value); - if (v) { - partial.push(quote(k) + (gap ? ': ' : ':') + v); - } - } - } - } - -// Join all of the member texts together, separated with commas, -// and wrap them in braces. - - v = partial.length === 0 ? '{}' : gap ? - '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}' : - '{' + partial.join(',') + '}'; - gap = mind; - return v; - } - } - -// If the JSON object does not yet have a stringify method, give it one. - - if (typeof Prado.JSON.stringify !== 'function') { - Prado.JSON.stringify = function (value, replacer, space) { - -// The stringify method takes a value and an optional replacer, and an optional -// space parameter, and returns a JSON text. The replacer can be a function -// that can replace values, or an array of strings that will select the keys. -// A default replacer method can be provided. Use of the space parameter can -// produce text that is more easily readable. - - var i; - gap = ''; - indent = ''; - -// If the space parameter is a number, make an indent string containing that -// many spaces. - - if (typeof space === 'number') { - for (i = 0; i < space; i += 1) { - indent += ' '; - } - -// If the space parameter is a string, it will be used as the indent string. - - } else if (typeof space === 'string') { - indent = space; - } - -// If there is a replacer, it must be a function or an array. -// Otherwise, throw an error. - - rep = replacer; - if (replacer && typeof replacer !== 'function' && - (typeof replacer !== 'object' || - typeof replacer.length !== 'number')) { - throw new Error('JSON.stringify'); - } - -// Make a fake root object containing our value under the key of ''. -// Return the result of stringifying the value. - - return str('', {'': value}); - }; - } - - -// If the JSON object does not yet have a parse method, give it one. - - if (typeof Prado.JSON.parse !== 'function') { - Prado.JSON.parse = function (text, reviver) { - -// The parse method takes a text and an optional reviver function, and returns -// a JavaScript value if the text is a valid JSON text. - - var j; - - function walk(holder, key) { - -// The walk method is used to recursively walk the resulting structure so -// that modifications can be made. - - var k, v, value = holder[key]; - if (value && typeof value === 'object') { - for (k in value) { - if (Object.prototype.hasOwnProperty.call(value, k)) { - v = walk(value, k); - if (v !== undefined) { - value[k] = v; - } else { - delete value[k]; - } - } - } - } - return reviver.call(holder, key, value); - } - - -// Parsing happens in four stages. In the first stage, we replace certain -// Unicode characters with escape sequences. JavaScript handles many characters -// incorrectly, either silently deleting them, or treating them as line endings. - - text = String(text); - cx.lastIndex = 0; - if (cx.test(text)) { - text = text.replace(cx, function (a) { - return '\\u' + - ('0000' + a.charCodeAt(0).toString(16)).slice(-4); - }); - } - -// In the second stage, we run the text against regular expressions that look -// for non-JSON patterns. We are especially concerned with '()' and 'new' -// because they can cause invocation, and '=' because it can cause mutation. -// But just to be safe, we want to reject all unexpected forms. - -// We split the second stage into 4 regexp operations in order to work around -// crippling inefficiencies in IE's and Safari's regexp engines. First we -// replace the JSON backslash pairs with '@' (a non-JSON character). Second, we -// replace all simple value tokens with ']' characters. Third, we delete all -// open brackets that follow a colon or comma or that begin the text. Finally, -// we look to see that the remaining characters are only whitespace or ']' or -// ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval. - - if (/^[\],:{}\s]*$/ - .test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@') - .replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']') - .replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) { - -// In the third stage we use the eval function to compile the text into a -// JavaScript structure. The '{' operator is subject to a syntactic ambiguity -// in JavaScript: it can begin a block or an object literal. We wrap the text -// in parens to eliminate the ambiguity. - - j = eval('(' + text + ')'); - -// In the optional fourth stage, we recursively walk the new structure, passing -// each name/value pair to a reviver function for possible transformation. - - return typeof reviver === 'function' ? - walk({'': j}, '') : j; - } - -// If the text is not JSON parseable, then a SyntaxError is thrown. - - throw new SyntaxError('JSON.parse'); - }; - } -}()); diff --git a/framework/Web/Javascripts/source/prado/controls/controls.js b/framework/Web/Javascripts/source/prado/controls/controls.js index d2e796e1..354bb5f5 100644 --- a/framework/Web/Javascripts/source/prado/controls/controls.js +++ b/framework/Web/Javascripts/source/prado/controls/controls.js @@ -261,7 +261,7 @@ Prado.WebUI.PostBackControl = jQuery.klass(Prado.WebUI.Control, { if(typeof(onclicked) == "boolean") doPostBack = onclicked; } - if(doPostBack && !Prado.Element.isDisabled(src)) + if(doPostBack && !jQuery(src).is(':disabled')) this.onPostBack(options,event); if(typeof(onclicked) == "boolean" && !onclicked) event.stopPropagation(); diff --git a/framework/Web/Javascripts/source/prado/prado.js b/framework/Web/Javascripts/source/prado/prado.js index a215fbd2..13080866 100644 --- a/framework/Web/Javascripts/source/prado/prado.js +++ b/framework/Web/Javascripts/source/prado/prado.js @@ -17,6 +17,25 @@ var Prado = Registry: {}, }; +Prado.RequestManager = +{ + /** + * Callback request target POST field name. + */ + FIELD_CALLBACK_TARGET : 'PRADO_CALLBACK_TARGET', + /** + * Callback request parameter POST field name. + */ + FIELD_CALLBACK_PARAMETER : 'PRADO_CALLBACK_PARAMETER', + /** + * Callback request page state field name, + */ + FIELD_CALLBACK_PAGESTATE : 'PRADO_PAGESTATE', + + FIELD_POSTBACK_TARGET : 'PRADO_POSTBACK_TARGET', + + FIELD_POSTBACK_PARAMETER : 'PRADO_POSTBACK_PARAMETER', +}; /** * Performs a PostBack using javascript. * @function Prado.PostBack @@ -31,46 +50,72 @@ var Prado = * @... {string} EventTarget - Id of element that triggered PostBack * @... {string} EventParameter - EventParameter for PostBack */ -Prado.PostBack = function(options, event) +Prado.PostBack = jQuery.klass( { - var form = jQuery("#" + options['FormID']).get(0); - var canSubmit = true; + options : { + iscallback: false + }, - if(options['CausesValidation'] && typeof(Prado.Validation) != "undefined") + initialize: function(options, event) { - if(!Prado.Validation.validate(options['FormID'], options['ValidationGroup'], $(options['ID']))) - return event.preventDefault(); - } + jQuery.extend(this.options, options || {}); + this.doPostBack(); + }, - if(options['PostBackUrl'] && options['PostBackUrl'].length > 0) - form.action = options['PostBackUrl']; + getForm : function() + { + return jQuery("#" + this.options['FormID']).get(0); + }, - if(options['TrackFocus']) + getParameters : function() { - var lastFocus = $('PRADO_LASTFOCUS'); - if(lastFocus) + var form = this.getForm(); + var data = {}; + + if(this.options.iscallback) { - var active = document.activeElement; //where did this come from - if(active) - lastFocus.value = active.id; - else - lastFocus.value = options['EventTarget']; + if(typeof(this.options.CallbackParameter) != "undefined") + data[Prado.CallbackRequestManager.FIELD_CALLBACK_PARAMETER] = this.getCallbackParameter(); + if(this.options.EventTarget) + data[Prado.RequestManager.FIELD_CALLBACK_TARGET] = this.options.EventTarget; + } else { + if(this.options.EventTarget) + data[Prado.RequestManager.FIELD_POSTBACK_TARGET] = this.options.EventTarget; + if(this.options.EventParameter) + data[Prado.RequestManager.FIELD_POSTBACK_PARAMETER] = this.options.EventParameter; } - } - $('PRADO_POSTBACK_TARGET').value = options['EventTarget']; - $('PRADO_POSTBACK_PARAMETER').value = options['EventParameter']; - /** - * Since google toolbar prevents browser default action, - * we will always disable default client-side browser action - */ - /*if(options['StopEvent']) */ - event.preventDefault(); - form.submit(); + return jQuery(form).serialize() + '&' + jQuery.param(data); + }, - $('PRADO_POSTBACK_TARGET').value = ''; - $('PRADO_POSTBACK_PARAMETER').value = ''; -}; + doPostBack : function() + { + var form = this.getForm(); + if(this.options['CausesValidation'] && typeof(Prado.Validation) != "undefined") + { + if(!Prado.Validation.validate(this.options['FormID'], this.options['ValidationGroup'], $("#" + this.options['ID']))) + return event.preventDefault(); + } + + if(options['PostBackUrl'] && options['PostBackUrl'].length > 0) + form.action = options['PostBackUrl']; + + if(options['TrackFocus']) + { + var lastFocus = $('PRADO_LASTFOCUS'); + if(lastFocus) + { + var active = document.activeElement; //where did this come from + if(active) + lastFocus.value = active.id; + else + lastFocus.value = options['EventTarget']; + } + } + + $(form).trigger('submit'); + } +}); /** * Prado utilities to manipulate DOM elements. @@ -78,17 +123,17 @@ Prado.PostBack = function(options, event) */ Prado.Element = { + /** - * Set the value of a particular element. + * Executes a jQuery method on a particular element. * @function ? * @param {string} element - Element id - * @param {string} value - New element value + * @param {string} method - method name + * @param {string} value - method parameter */ - setValue : function(element, value) + j: function(element, method, param) { - var el = jQuery("#" + element).get(0); - if(el && typeof(el.value) != "undefined") - el.value = value; + jQuery("#" + element)[method](param); }, /** @@ -112,35 +157,6 @@ Prado.Element = }, /** - * Trigger a click event on a DOM element. - * @function ? - * @param {string} element - Element id - */ - click : function(element) - { - var el = jQuery("#" + element).get(0); - if(el) - el.click(); - }, - - /** - * Check if an DOM element is disabled. - * @function {boolean} ? - * @param {string} element - Element id - * @returns true if element is disabled - */ - isDisabled : function(element) - { - if(!element.attributes['disabled']) //FF - return false; - var value = element.attributes['disabled'].nodeValue; - if(typeof(value)=="string") - return value.toLowerCase() == "disabled"; - else - return value == true; - }, - - /** * Sets an attribute of a DOM element. * @function ? * @param {string} element - Element id @@ -149,10 +165,10 @@ Prado.Element = */ setAttribute : function(element, attribute, value) { - var el = jQuery("#" + element).get(0); + var el = jQuery("#" + element); if(!el) return; if((attribute == "disabled" || attribute == "multiple" || attribute == "readonly" || attribute == "href") && value==false) - el.removeAttribute(attribute); + el.removeAttr(attribute); else if(attribute.match(/^on/i)) //event methods { try @@ -163,11 +179,23 @@ Prado.Element = catch(e) { debugger; - throw "Error in evaluating '"+value+"' for attribute "+attribute+" for element "+element.id; + throw "Error in evaluating '"+value+"' for attribute "+attribute+" for element "+element; } } else - el.setAttribute(attribute, value); + el.attr(attribute, value); + }, + + scrollTo : function(element, options) + { + var op = { + duration : 500, + offset : 50 + }; + jQuery.extend(op, options || {}); + $('html, body').animate({ + scrollTop: $("#"+element).offset().top - op.offset + }, op.duration); }, /** @@ -240,19 +268,6 @@ Prado.Element = }, /** - * Set focus (delayed) on a particular element. - * @function ? - * @param {string} element - Element id - */ - focus : function(element) - { - var obj = jQuery("#" + element).get(0); - if(typeof(obj) != "undefined" && typeof(obj.focus) != "undefined") - setTimeout(function(){ obj.focus(); }, 100); - return false; - }, - - /** * Replace a DOM element either with given content or * with content from a CallBack response boundary * using a replacement method. @@ -271,14 +286,9 @@ Prado.Element = content = result; } if(typeof(element) == "string") - { - if(jQuery("#" + element).get(0)) - method.toFunction().apply(this,[element,""+content]); - } + method.toFunction().apply(this,[element,""+content]); else - { method.toFunction().apply(this,[""+content]); - } }, /** @@ -353,25 +363,6 @@ Prado.Element = throw e; } }, - - /** - * Set CSS style with Camelized keys. - * See <a href="http://www.prototypejs.org/api/element/setstyle" target="_blank">Prototype's - * Element.setStyle</a> for details. - * @function ? - * @param {string|element} element - DOM element or element id - * @param {object} styles - Object with style properties/values - */ - setStyle : function (element, styles) - { - var s = {} - // Camelize all styles keys - for (var property in styles) - { - s[property.camelize()]=styles[property].camelize(); - } - Element.setStyle(element, s); - } }; jQuery.extend(String.prototype, { |