AjaxTCR Library Source
var AjaxTCR = { } ;
AjaxTCR . comm = {
UNSENT : 0 ,
OPEN : 1 ,
SENT : 2 ,
LOADING : 3 ,
DONE : 4 ,
DEFAULT_REQUEST_METHOD : " GET " ,
DEFAULT_ASYNC : true ,
DEFAULT_PREVENT_CACHE : false ,
DEFAULT_CONTENT_TYPE : " application/x-www-form-urlencoded " ,
DEFAULT_CONTENT_TRANSFER_ENCODING : " " ,
DEFAULT_TRANSPORT_INDICATOR : true ,
DEFAULT_TIMEOUT : 0 ,
DEFAULT_RETRIES : 0 ,
DEFAULT_SHOW_PROGRESS : false ,
DEFAULT_PROGRESS_INTERVAL : 1000 ,
DEFAULT_ENFORCE_ORDER : false ,
DEFAULT_CACHE_RESPONSE : false ,
DEFAULT_USE_RAW : true ,
DEFAULT_ONEWAY : false ,
DEFAULT_REQUEST_SIGNATURE : " X-Signature " ,
DEFAULT_SIGNED_RESPONSE : false ,
DEFAULT_TRANSPORT : " xhr " ,
DEFAULT_TRANSPORT_HEADER : " X-Requested-By " ,
DEFAULT_XHR_TRANSPORT_VALUE : " XHR " ,
DEFAULT_IFRAME_TRANSPORT_VALUE : " iframe " ,
DEFAULT_IMAGE_TRANSPORT_VALUE : " image " ,
DEFAULT_SCRIPT_TRANSPORT_VALUE : " HTMLScriptTag " ,
DEFAULT_FALLBACK : true ,
DEFAULT_FALLBACK_TRANSPORT : " iframe " ,
DEFAULT_INSERTION_METHOD : " replace " ,
DEFAULT_CACHE_TEMPLATE : true ,
DEFAULT_TEMPLATE_RENDER : " client " ,
TEMPLATE_SERVER_DEFINED : " dynamic " ,
_requestID : 0 ,
_requestsOutstanding : 0 ,
_networkErrorStatus : new Array ( 0 , 408 , 504 , 3507 , 12002 , 12007 , 12029 , 12030 , 12031 , 12152 ) ,
setDefault : function ( option , value ) {
AjaxTCR . comm [ option ] = value ;
} ,
getDefault : function ( option ) {
return AjaxTCR . comm [ option ]
} ,
sendRequest : function ( url , options ) {
var request = new Object ( ) ;
request . requestID = ++ AjaxTCR . comm . _requestID ;
request . method = AjaxTCR . comm . DEFAULT_REQUEST_METHOD ;
request . async = AjaxTCR . comm . DEFAULT_ASYNC ;
request . preventCache = AjaxTCR . comm . DEFAULT_PREVENT_CACHE ;
request . requestContentType = AjaxTCR . comm . DEFAULT_CONTENT_TYPE ;
request . requestContentTransferEncoding = AjaxTCR . comm . DEFAULT_CONTENT_TRANSFER_ENCODING ;
request . payload = " " ;
request . headers = new Array ( ) ;
request . transportIndicator = AjaxTCR . comm . DEFAULT_TRANSPORT_INDICATOR ;
request . onSuccess = function ( ) { } ;
request . onFail = function ( ) { } ;
request . onCreate = null ;
request . onOpen = null ;
request . onSent = null ;
request . onLoading = null ;
request . onReceived = null ;
request . abort = false ;
request . inProgress = true ;
request . received = false ;
request . showProgress = AjaxTCR . comm . DEFAULT_SHOW_PROGRESS ;
request . progressInterval = AjaxTCR . comm . DEFAULT_PROGRESS_INTERVAL ;
request . onProgress = function ( ) { } ;
request . progressTimerID = null ;
request . timespent = 0 ;
request . timeout = AjaxTCR . comm . DEFAULT_TIMEOUT ;
request . onTimeout = function ( ) { } ;
request . timeoutTimerID = null ;
request . retries = AjaxTCR . comm . DEFAULT_RETRIES ;
request . retryCount = 1 ;
request . onRetry = function ( ) { } ;
request . inQueue = false ;
request . responseQueueID = 0 ;
request . enforceOrder = AjaxTCR . comm . DEFAULT_ENFORCE_ORDER ;
request . cacheResponse = AjaxTCR . comm . DEFAULT_CACHE_RESPONSE ;
request . fromCache = false ;
request . onPrefetch = function ( ) { } ;
request . isPrefetch = false ;
request . serializeForm = null ;
request . hasFile = false ;
request . outputTarget = null ;
request . useRaw = AjaxTCR . comm . DEFAULT_USE_RAW ;
request . insertionType = AjaxTCR . comm . DEFAULT_INSERTION_METHOD ;
request . oneway = AjaxTCR . comm . DEFAULT_ONEWAY ;
request . username = null ;
request . password = null ;
request . requestSignature = AjaxTCR . comm . DEFAULT_REQUEST_SIGNATURE ;
request . signRequest = null ;
request . signedResponse = AjaxTCR . comm . DEFAULT_SIGNED_RESPONSE ;
request . history = null ;
request . transport = AjaxTCR . comm . DEFAULT_TRANSPORT ;
request . fallback = AjaxTCR . comm . DEFAULT_FALLBACK ;
request . fallbackTransport = AjaxTCR . comm . DEFAULT_FALLBACK_TRANSPORT ;
request . cookieName = null ;
request . template = null ;
request . templateRender = AjaxTCR . comm . DEFAULT_TEMPLATE_RENDER ;
request . cacheTemplate = AjaxTCR . comm . DEFAULT_CACHE_TEMPLATE ;
request . shortTermCacheTemplate = false ;
request . statusIndicator = null ;
for ( option in options )
request [ option ] = options [ option ] ;
if ( request . isPrefetch )
request . cacheResponse = true ;
if ( AjaxTCR . history . _backGuardEnabled == AjaxTCR . history . BACK_GUARD_INITIALIZED )
AjaxTCR . history . _activateBackGuard ( ) ;
if ( request . template && request . template != AjaxTCR . comm . TEMPLATE_SERVER_DEFINED && request . templateRender == " client " )
{
if ( ! AjaxTCR . template . getFromCache ( request . template ) )
{
request . enforceOrder = true ;
AjaxTCR . comm . sendRequest ( request . template , { shortTermCacheTemplate : true , enforceOrder : true } ) ;
}
}
else if ( request . template && request . template != AjaxTCR . comm . TEMPLATE_SERVER_DEFINED && request . templateRender == " server " )
{
if ( request . payload != " " )
request . payload += " & " ;
request . payload += " templateURL= " + request . template ;
}
if ( request . serializeForm )
{
var newPayload = AjaxTCR . data . serializeForm ( request . serializeForm , request . requestContentType ) ;
if ( newPayload == " fileupload " )
request . hasFile = true ;
else
{
if ( request . payload )
{
if ( typeof ( request . payload ) == " object " )
newPayload = AjaxTCR . data . serializeObject ( newPayload , request . payload , request . requestContentType ) ;
else if ( request . requestContentType == AjaxTCR . comm . DEFAULT_CONTENT_TYPE )
newPayload += " & " + request . payload ;
}
request . payload = newPayload ;
if ( request . requestContentType == " application/json " )
request . payload = AjaxTCR . data . encodeJSON ( request . payload ) ;
else if ( request . requestContentType == " text/xml " )
request . payload = AjaxTCR . data . serializeXML ( request . payload ) ;
if ( request . requestContentTransferEncoding == " base64 " )
request . payload = AjaxTCR . data . encode64 ( request . payload ) ;
}
}
if ( request . history )
AjaxTCR . history . init ( function ( ) { } ) ;
if ( request . history && ! request . history . saveResponse )
AjaxTCR . history . addToHistory ( request . history . id , " " , request . history . title , url , options ) ;
if ( request . hasFile )
request . transport = " iframe " ;
request . transport = request . transport . toLowerCase ( ) ;
if ( request . transport == " script " || request . transport == " image " )
request . method = " GET " ;
if ( request . method . toUpperCase ( ) == " GET " && request . payload != " " )
request . url = url + " ? " + request . payload ;
else
request . url = url ;
if ( request . method . toUpperCase ( ) == " POST " )
request . postBody = request . payload ;
else
request . postBody = null ;
if ( request . enforceOrder )
request . responseQueueID = AjaxTCR . comm . queue . _responseQueue . maxID ++;
var cachedResponse = null ;
if ( request . cacheResponse )
{
if ( request . cacheKey == undefined )
request . cacheKey = request . url ;
cachedResponse = AjaxTCR . comm . cache . get ( request . cacheKey ) ;
if ( cachedResponse )
AjaxTCR . comm . cache . _handleCacheResponse ( request , cachedResponse ) ;
}
if ( ! cachedResponse )
AjaxTCR . comm . _makeRequest ( request ) ;
return request ;
} ,
abortRequest : function ( request ) {
request . abort = true ;
request . inProgress = false ;
request . xhr . abort ( ) ;
AjaxTCR . comm . _requestsOutstanding --;
clearTimeout ( request . timeoutTimerID ) ;
request . timeoutTimerID = null ;
if ( request . progressTimerID )
{
clearTimeout ( request . progressTimerID ) ;
request . progressTimerID = null ;
}
if ( request . statusIndicator )
{
AjaxTCR . comm . _removeProgressStatus ( request . statusIndicator ) ;
}
} ,
_createXHR : function ( ) {
try { return new XMLHttpRequest ( ) ; } catch ( e ) { }
try { return new ActiveXObject ( " Msxml2.XMLHTTP.6.0 " ) ; } catch ( e ) { }
try { return new ActiveXObject ( " Msxml2.XMLHTTP.3.0 " ) ; } catch ( e ) { }
try { return new ActiveXObject ( " Msxml2.XMLHTTP " ) ; } catch ( e ) { }
try { return new ActiveXObject ( " Microsoft.XMLHTTP " ) ; } catch ( e ) { }
return null ;
} ,
_makeRequest : function ( request ) {
AjaxTCR . comm . stats . _commResults . totalRequests ++;
if ( ! request . oneway )
AjaxTCR . comm . _initSend ( request ) ;
if ( request . onCreate )
request . onCreate ( request ) ;
if ( request . transport == " xhr " )
AjaxTCR . comm . _sendXHR ( request ) ;
else if ( request . transport == " iframe " )
AjaxTCR . comm . _sendIframe ( request ) ;
else if ( request . transport == " script " )
AjaxTCR . comm . _sendScript ( request ) ;
else if ( request . transport == " image " )
AjaxTCR . comm . _sendImage ( request ) ;
} ,
_sendXHR : function ( request ) {
request . xhr = AjaxTCR . comm . _createXHR ( ) ;
if ( ! request . xhr )
{
AjaxTCR . comm . _fallbackOrError ( request ) ;
return ;
}
try {
request . xhr . open ( request . method , request . url , request . async , request . username , request . password ) ;
}
catch ( e ) {
AjaxTCR . comm . _fallbackOrError ( request ) ;
return ;
}
request . abort = false ;
if ( request . transportIndicator )
{
request . xhr . setRequestHeader ( AjaxTCR . comm . DEFAULT_TRANSPORT_HEADER , AjaxTCR . comm . DEFAULT_XHR_TRANSPORT_VALUE ) ;
request . xhr . setRequestHeader ( " X-Request-Id " , request . requestID ) ;
}
if ( request . signRequest )
request . xhr . setRequestHeader ( request . requestSignature , request . signRequest ) ;
if ( request . method . toUpperCase ( ) == " POST " )
{
request . xhr . setRequestHeader ( " Content-Type " , request . requestContentType ) ;
if ( request . requestContentTransferEncoding != " " )
request . xhr . setRequestHeader ( " Content-Transfer-Encoding " , request . requestContentTransferEncoding ) ;
}
if ( request . preventCache )
request . xhr . setRequestHeader ( " If-Modified-Since " , " Wed, 15 Nov 1995 04:58:08 GMT " ) ;
request . headerObj = { } ;
for ( var i = 0 ; i < request . headers . length ; i ++ )
{
if ( request . headers [ i ] . name . toUpperCase ( ) == " COOKIE " )
document . cookie = request . headers [ i ] . value ;
else if ( request . headerObj [ request . headers [ i ] . name ] === undefined )
request . headerObj [ request . headers [ i ] . name ] = request . headers [ i ] . value ;
else
request . headerObj [ request . headers [ i ] . name ] = request . headers [ i ] . value + " , " + request . headerObj [ request . headers [ i ] . name ] ;
}
for ( var header in request . headerObj )
request . xhr . setRequestHeader ( header , request . headerObj [ header ] ) ;
if ( ! request . oneway )
{
request . xhr . onreadystatechange = function ( ) { AjaxTCR . comm . _handleReadyStateChange ( request ) ; } ;
if ( request . async && request . timeout && request . timeoutTimerID == null )
request . timeoutTimerID = window . setTimeout ( function ( ) { AjaxTCR . comm . _timeoutRequest ( request ) ; } , request . timeout ) ;
}
request . xhr . send ( request . postBody ) ;
} ,
_sendScript : function ( request ) {
var script = document . createElement ( ' script ' ) ;
var callback = function ( ) { AjaxTCR . comm . _handleScriptResponse ( request ) ; } ;
if ( request . transportIndicator )
{
if ( request . url . indexOf ( " ? " ) )
request . url += " & " + AjaxTCR . comm . DEFAULT_TRANSPORT_HEADER + " = " + AjaxTCR . comm . DEFAULT_SCRIPT_TRANSPORT_VALUE ;
else
request . url += " ? " + AjaxTCR . comm . DEFAULT_TRANSPORT_HEADER + " = " + AjaxTCR . comm . DEFAULT_SCRIPT_TRANSPORT_VALUE ;
}
if ( script . addEventListener )
script . addEventListener ( " load " , callback , false ) ;
else
{
script . onreadystatechange = function ( )
{
if ( this . readyState == " complete " )
callback . call ( this ) ;
} ;
}
script . src = request . url ;
script . type = " text/javascript " ;
document . body . appendChild ( script ) ;
} ,
_sendIframe : function ( request ) {
var iframeID = AjaxTCR . util . misc . generateUID ( " AjaxTCRIframe_ " ) ;
if ( window . ActiveXObject )
var iframe = document . createElement ( ' <iframe id=" ' + iframeID + ' " name=" ' + iframeID + ' " /> ' ) ;
else
{
var iframe = document . createElement ( " iframe " ) ;
iframe . id = iframeID ;
iframe . name = iframeID ;
}
iframe . style . height = " 1px " ;
iframe . style . visibility = " hidden " ;
document . body . appendChild ( iframe ) ;
var callback = function ( ) { AjaxTCR . comm . _handleIFrameResponse ( request , iframe ) ; } ;
if ( window . attachEvent )
iframe . attachEvent ( ' onload ' , callback ) ;
else
iframe . addEventListener ( ' load ' , callback , false ) ;
if ( request . hasFile )
{
request . serializeForm . target = iframe . id ;
request . serializeForm . submit ( ) ;
}
else if ( request . method . toUpperCase ( ) == " GET " )
{
if ( request . transportIndicator )
{
if ( request . url . indexOf ( " ? " ) > - 1 )
request . url += " & " + AjaxTCR . comm . DEFAULT_TRANSPORT_HEADER + " = " + AjaxTCR . comm . DEFAULT_IFRAME_TRANSPORT_VALUE ;
else
request . url += " ? " + AjaxTCR . comm . DEFAULT_TRANSPORT_HEADER + " = " + AjaxTCR . comm . DEFAULT_IFRAME_TRANSPORT_VALUE ;
}
iframe . src = request . url ;
}
else
{
var ifrForm = makeIframeForm ( iframe , request ) ;
ifrForm . submit ( ) ;
}
function makeIframeForm ( ifr , request )
{
var url = request . url ;
var payload = request . postBody ;
var ifrDoc = null ;
var ifrWindow = ifr . contentWindow || ifr . contentDocument ;
if ( ifrWindow . document )
ifrDoc = ifrWindow . document ;
else
ifrDoc = ifrWindow ;
if ( ! ifrDoc . body )
{
var html = ifrDoc . createElement ( " HTML " ) ;
ifrDoc . appendChild ( html ) ;
var head = ifrDoc . createElement ( " HEAD " ) ;
html . appendChild ( head ) ;
var body = ifrDoc . createElement ( " BODY " ) ;
html . appendChild ( body ) ;
}
var ifrForm = ifrDoc . createElement ( " FORM " ) ;
ifrForm . action = url ;
ifrForm . method = " post " ;
ifrDoc . body . appendChild ( ifrForm ) ;
var keys = payload . split ( " & " ) ;
for ( var i = 0 ; i < keys . length ; i ++ )
{
var nv = keys [ i ] . split ( " = " ) ;
var ifrText = ifrDoc . createElement ( " INPUT " ) ;
ifrText . type = " text " ;
ifrText . name = nv [ 0 ] ;
ifrText . value = nv [ 1 ] ;
ifrForm . appendChild ( ifrText ) ;
}
if ( request . transportIndicator )
{
var ifrText = ifrDoc . createElement ( " INPUT " ) ;
ifrText . type = " text " ;
ifrText . name = AjaxTCR . comm . DEFAULT_TRANSPORT_HEADER ;
ifrText . value = AjaxTCR . comm . DEFAULT_IFRAME_TRANSPORT_VALUE ;
ifrForm . appendChild ( ifrText ) ;
}
return ifrForm ;
}
} ,
_sendImage : function ( request ) {
var callback = function ( ) { AjaxTCR . comm . _handleImageResponse ( request ) ; } ;
if ( request . transportIndicator )
{
if ( request . url . indexOf ( " ? " ) )
request . url += " & " + AjaxTCR . comm . DEFAULT_TRANSPORT_HEADER + " = " + AjaxTCR . comm . DEFAULT_IMAGE_TRANSPORT_VALUE ;
else
request . url += " ? " + AjaxTCR . comm . DEFAULT_TRANSPORT_HEADER + " = " + AjaxTCR . comm . DEFAULT_IMAGE_TRANSPORT_VALUE ;
}
var img = new Image ( ) ;
img . onload = callback ;
img . src = request . url ;
} ,
_initSend : function ( request ) {
if ( request . statusIndicator )
request . statusIndicator . element = AjaxTCR . comm . _setProgressStatus ( request . statusIndicator ) ;
request . timespent = 0 ;
if ( request . showProgress && request . progressTimerID == null )
request . progressTimerID = window . setTimeout ( function ( ) { AjaxTCR . comm . _progressRequest ( request ) ; } , request . progressInterval ) ;
request . startTime = ( new Date ( ) ) . getTime ( ) ;
AjaxTCR . comm . _requestsOutstanding ++;
} ,
_fallbackOrError : function ( request ) {
if ( request . fallback )
{
request . transport = request . fallbackTransport . toLowerCase ( ) ;
if ( ( request . transport == " script " || request . transport == " image " ) && request . method . toUpperCase ( ) == " POST " )
{
request . method = " GET " ;
request . url = request . url + " ? " + request . postBody ;
request . postBody = null ;
}
if ( request . transport == " iframe " )
AjaxTCR . comm . _sendIframe ( request ) ;
else if ( request . transport == " script " )
AjaxTCR . comm . _sendScript ( request ) ;
else if ( request . transport == " image " )
AjaxTCR . comm . _sendImage ( request ) ;
else
throw " AjaxTCR Error: Unknown fallback transport: " + request . transport ;
}
else
throw " AjaxTCR Error: XHR Creation failed and fallback is not enabled " ;
} ,
_handleIFrameResponse : function ( response , iframe ) {
response . httpStatus = 200 ;
response . httpStatusText = " OK " ;
if ( iframe . contentWindow . document . body )
response . responseText = iframe . contentWindow . document . body . innerHTML ;
if ( iframe . contentWindow . document . XMLDocument )
response . responseXML = iframe . contentWindow . document . XMLDocument ;
else
response . responseXML = iframe . contentWindow . document ;
AjaxTCR . comm . _handleResponse ( response ) ;
} ,
_handleScriptResponse : function ( response ) {
response . httpStatus = 200 ;
response . httpStatusText = " OK " ;
response . responseText = " " ;
response . responseXML = null ;
AjaxTCR . comm . _handleResponse ( response ) ;
} ,
_handleImageResponse : function ( response ) {
response . httpStatus = 200 ;
response . httpStatusText = " OK " ;
if ( response . cookieName )
response . responseText = AjaxTCR . comm . cookie . get ( response . cookieName ) ;
else
response . responseText = document . cookie ;
response . responseXML = null ;
AjaxTCR . comm . _handleResponse ( response ) ;
} ,
_timeoutRequest : function ( request ) {
if ( request . xhr . readyState != AjaxTCR . comm . DONE && request . xhr . readyState != AjaxTCR . comm . UNSENT )
{
AjaxTCR . comm . abortRequest ( request ) ;
AjaxTCR . comm . stats . _commResults . totalTimeouts ++;
if ( request . retries )
AjaxTCR . comm . _retryRequest ( request ) ;
else
{
request . onTimeout ( request ) ;
AjaxTCR . comm . queue . _checkRequestQueue ( request ) ;
}
}
} ,
_progressRequest : function ( request ) {
if ( ! request . abort && ! request . received )
{
request . timespent = Math . round ( ( request . timespent + ( parseInt ( request . progressInterval ) / 1000 ) ) * 1000 ) / 1000 ;
request . onProgress ( request ) ;
clearTimeout ( request . progressTimerID ) ;
request . progressTimerID = null ;
request . progressTimerID = window . setTimeout ( function ( ) { AjaxTCR . comm . _progressRequest ( request ) ; } , request . progressInterval ) ;
}
} ,
_retryRequest : function ( request ) {
request . retryCount ++;
if ( request . retryCount <= request . retries )
{
AjaxTCR . comm . stats . _commResults . totalRetries ++;
AjaxTCR . comm . _makeRequest ( request ) ;
request . onRetry ( request ) ;
}
else
{
request . onTimeout ( request ) ;
AjaxTCR . comm . queue . _checkRequestQueue ( request ) ;
}
} ,
_handleResponse : function ( response ) {
response . endTime = ( new Date ( ) ) . getTime ( ) ;
response . totalTime = ( response . endTime - response . startTime ) ;
response . received = true ;
if ( response . timeoutTimerID )
{
clearTimeout ( response . timeoutTimerID ) ;
response . timeoutTimerID = null ;
}
if ( response . progressTimerID )
{
clearTimeout ( response . progressTimerID ) ;
response . progressTimerID = null ;
}
AjaxTCR . comm . _requestsOutstanding --;
if ( ! response . fromCache && response . cacheResponse && response . httpStatus == 200 && ! response . fail )
AjaxTCR . comm . cache . add ( response . cacheKey , response . responseText ) ;
if ( response . shortTermCacheTemplate && response . httpStatus == 200 && ! response . fail )
AjaxTCR . template . addToCache ( response . url , response . responseText ) ;
if ( response . history && response . history . saveResponse )
AjaxTCR . history . addToHistory ( response . history . id , " " , response . history . title , " " , response ) ;
if ( response . statusIndicator )
AjaxTCR . comm . _removeProgressStatus ( response . statusIndicator ) ;
if ( response . enforceOrder )
AjaxTCR . comm . queue . _handleQueue ( response ) ;
else
AjaxTCR . comm . _handleCallbacks ( response ) ;
AjaxTCR . comm . queue . _checkRequestQueue ( response ) ;
} ,
_handleCallbacks : function ( response ) {
response . inProgress = false ;
if ( response . template && response . templateRender == " client " )
{
var template = null ;
if ( response . template != AjaxTCR . comm . TEMPLATE_SERVER_DEFINED )
{
template = AjaxTCR . template . getFromCache ( response . template ) ;
if ( ! ( response . cacheTemplate ) )
AjaxTCR . template . removeFromCache ( response . template ) ;
}
else
{
var returnedObject = AjaxTCR . data . decodeJSON ( response . responseText ) ;
if ( returnedObject . templateURL && returnedObject . templateText )
{
template = returnedObject . templateText ;
if ( response . cacheTemplate )
AjaxTCR . template . addToCache ( returnedObject . templateURL , returnedObject . templateText ) ;
}
else if ( returnedObject . templateText )
template = returnedObject . templateText ;
else if ( returnedObject . templateURL )
{
var template = AjaxTCR . template . getFromCache ( returnedObject . templateURL ) ;
if ( ! template )
{
var templateRequest = AjaxTCR . comm . sendRequest ( returnedObject . templateURL , { async : false } ) ;
var template = templateRequest . responseText ;
if ( response . cacheTemplate && template )
AjaxTCR . template . addToCache ( returnedObject . templateURL , template ) ;
}
}
}
if ( template )
{
try {
var translatedResponse = AjaxTCR . template . translateString ( template , response . responseText ) ;
if ( translatedResponse )
{
response . rawResponseText = response . responseText ;
response . responseText = translatedResponse ;
}
}
catch ( e ) { }
}
}
if ( response . outputTarget && response . useRaw && ( response . transport == " xhr " || response . transport == " iframe " ) )
{
var outputTarget = response . outputTarget ;
if ( outputTarget && typeof ( outputTarget ) == " string " )
outputTarget = document . getElementById ( outputTarget ) ;
if ( response . fail )
outputTarget . innerHTML = response . fail ;
else
{
var span = document . createElement ( " span " ) ;
span . innerHTML = response . responseText ;
var newParent = span ;
switch ( response . insertionType . toLowerCase ( ) )
{
case ( " insertbefore " ) :
var parent = outputTarget . parentNode ;
parent . insertBefore ( span , outputTarget ) ;
break ;
case ( " insertafter " ) :
var parent = outputTarget . parentNode ;
AjaxTCR . util . DOM . insertAfter ( parent , span , outputTarget ) ;
break ;
case ( " firstchild " ) :
var elm = outputTarget . firstChild ;
while ( elm != null && elm . nodeType != 1 )
elm = elm . nextSibling ;
if ( elm != null )
outputTarget . insertBefore ( span , elm ) ;
else
outputTarget . appendChild ( span ) ;
break ;
case ( " lastchild " ) :
outputTarget . appendChild ( span ) ;
break ;
default :
outputTarget . innerHTML = response . responseText ;
newParent = outputTarget ;
break ;
}
}
}
if ( response [ " on " + response . httpStatus ] && ! response . fail )
response [ " on " + response . httpStatus ] ( response ) ;
if ( response . retries )
{
for ( var i = 0 ; i < AjaxTCR . comm . _networkErrorStatus . length ; i ++ )
{
if ( response . httpStatus == AjaxTCR . comm . _networkErrorStatus [ i ] )
{
AjaxTCR . comm . _retryRequest ( response ) ;
return ;
}
}
}
if ( response . httpStatus == 200 )
{
if ( response . fail )
AjaxTCR . comm . _handleFail ( response , response . fail ) ;
else if ( response . responseContentType && response . transport == " xhr " )
{
var responseContentType = response . xhr . getResponseHeader ( " Content-Type " ) ;
responseContentType = responseContentType . substring ( 0 , responseContentType . indexOf ( " ; " ) ) ;
if ( responseContentType != response . responseContentType )
AjaxTCR . comm . _handleFail ( response , " Wrong Content-Type: " + responseContentType ) ;
else if ( response . responseContentType == " text/xml " && ( response . responseXML == null || response . responseXML . childNodes . length == 0 || response . responseXML . childNodes [ 0 ] . nodeName == " parsererror " ) )
AjaxTCR . comm . _handleFail ( response , " Invalid XML Data " ) ;
else
AjaxTCR . comm . _handleSuccess ( response ) ;
}
else
AjaxTCR . comm . _handleSuccess ( response ) ;
}
else
AjaxTCR . comm . _handleFail ( response , response . httpStatus + " " + response . httpStatusText ) ;
response = null ;
} ,
_handleFail : function ( response , message ) {
AjaxTCR . comm . stats . _commResults . totalFails ++;
response . fail = message ;
var fail = { } ;
fail . url = response . url ;
fail . status = response . httpStatus ;
fail . message = message ;
AjaxTCR . comm . stats . _commResults . requestFails . push ( fail ) ;
response . onFail ( response , message ) ;
} ,
_handleSuccess : function ( response ) {
AjaxTCR . comm . stats . _commResults . totalSuccesses ++;
if ( response . isPrefetch )
response . onPrefetch ( response ) ;
else
response . onSuccess ( response ) ;
} ,
_handleReadyStateChange : function ( response ) {
if ( response . abort )
return ;
if ( response . xhr . readyState == AjaxTCR . comm . OPEN && response . onOpen )
response . onOpen ( response ) ;
else if ( response . xhr . readyState == AjaxTCR . comm . SENT && response . onSent )
response . onSent ( response ) ;
else if ( response . xhr . readyState == AjaxTCR . comm . LOADING && response . onLoading )
response . onLoading ( response ) ;
else if ( response . xhr . readyState == AjaxTCR . comm . DONE )
{
if ( response . signedResponse )
{
var signature = response . xhr . getResponseHeader ( " Content-MD5 " ) ;
var verifySignature = AjaxTCR . data . encodeMD5 ( response . xhr . responseText ) ;
if ( signature != verifySignature )
response . fail = " Response Packet Compromised. " ;
}
if ( response . onReceived && ! response . fail )
response . onReceived ( response ) ;
try { response . httpStatus = response . xhr . status ; response . httpStatusText = response . xhr . statusText } catch ( e ) { response . httpStatus = 3507 ; response . httpStatusText = " Unknown Loss " ; }
response . responseText = response . xhr . responseText ;
response . responseXML = response . xhr . responseXML ;
AjaxTCR . comm . _handleResponse ( response ) ;
}
} ,
_setStatus : function ( statusIndicator ) {
if ( statusIndicator . target )
{
if ( typeof ( statusIndicator . target ) == " string " )
statusIndicator . target = document . getElementById ( statusIndicator . target ) ;
if ( statusIndicator . type == " text " )
{
var statusDiv = document . createElement ( " div " ) ;
statusDiv . innerHTML = statusIndicator . text ;
statusIndicator . target . appendChild ( statusDiv ) ;
statusIndicator . element = statusDiv ;
}
else if ( statusIndicator . type == " image " )
{
var statusImg = document . createElement ( " img " ) ;
statusImg . id = " progressBar " ;
if ( statusIndicator . border )
statusImg . border = statusIndicator . border ;
statusImg . src = statusIndicator . imgSrc ;
statusIndicator . target . appendChild ( statusImg ) ;
statusIndicator . element = statusImg ;
}
}
} ,
_setProgressStatus : function ( statusIndicator ) {
if ( statusIndicator . progress )
return AjaxTCR . comm . _setStatus ( statusIndicator . progress ) ;
} ,
_removeStatus : function ( statusIndicator ) {
if ( statusIndicator . element )
{
statusIndicator . element . parentNode . removeChild ( statusIndicator . element ) ;
statusIndicator . element = null ;
}
} ,
_removeProgressStatus : function ( statusIndicator ) {
if ( statusIndicator . progress )
AjaxTCR . comm . _removeStatus ( statusIndicator . progress ) ;
}
} ;
AjaxTCR . comm . cache = {
_cache : new Array ( ) ,
_cacheOptions : {
size : 100 ,
algorithm : " LRU " ,
expires : 60
} ,
add : function ( key , val ) {
if ( AjaxTCR . comm . cache . _cache . length >= AjaxTCR . comm . cache . _cacheOptions . size )
{
var algorithm = AjaxTCR . comm . cache . _cacheOptions . algorithm ;
if ( algorithm == " FIFO " )
AjaxTCR . comm . cache . _cache . splice ( 0 , 1 ) ;
else if ( algorithm == " LFU " )
{
var removeIndex = - 1 ;
for ( var i = 0 ; i < AjaxTCR . comm . cache . _cache . length ; i ++ )
{
if ( removeIndex == - 1 || AjaxTCR . comm . cache . _cache [ removeIndex ] . totalAccessed > AjaxTCR . comm . cache . _cache [ i ] . totalAccessed )
removeIndex = i ;
}
AjaxTCR . comm . cache . _cache . splice ( removeIndex , 1 ) ;
}
else if ( algorithm == " LRU " )
{
var removeIndex = - 1 ;
for ( var i = 0 ; i < AjaxTCR . comm . cache . _cache . length ; i ++ )
{
if ( removeIndex == - 1 || AjaxTCR . comm . cache . _cache [ removeIndex ] . lastAccessed > AjaxTCR . comm . cache . _cache [ i ] . lastAccessed )
removeIndex = i ;
}
AjaxTCR . comm . cache . _cache . splice ( removeIndex , 1 ) ;
}
}
var item = AjaxTCR . comm . cache . _createCacheItem ( key , val ) ;
AjaxTCR . comm . cache . _cache . push ( item ) ;
} ,
clear : function ( ) {
AjaxTCR . comm . cache . _cache = new Array ( ) ;
} ,
get : function ( key ) {
var cacheObject = null ;
for ( var i = 0 ; i < AjaxTCR . comm . cache . _cache . length ; i ++ )
{
if ( AjaxTCR . comm . cache . _cache [ i ] . key == key )
{
cacheObject = AjaxTCR . comm . cache . _cache [ i ] ;
break ;
}
}
if ( cacheObject )
{
cacheObject . lastAccessed = new Date ( ) ;
cacheObject . totalAccessed ++;
if ( AjaxTCR . comm . cache . _cacheOptions . expires != - 1 )
{
var timeAdded = cacheObject . added ;
var now = new Date ( ) ;
now . setMinutes ( now . getMinutes ( ) - AjaxTCR . comm . cache . _cacheOptions . expires ) ;
if ( now > timeAdded )
{
AjaxTCR . comm . cache . remove ( item . key ) ;
cacheObject = null ;
}
}
}
if ( cacheObject )
return cacheObject . value ;
else
return null ;
} ,
getAll : function ( ) {
return AjaxTCR . comm . cache . _cache ;
} ,
getSize : function ( ) {
return AjaxTCR . comm . cache . _cache . length ;
} ,
remove : function ( key ) {
for ( var i = 0 ; i < AjaxTCR . comm . cache . _cache . length ; i ++ )
{
if ( AjaxTCR . comm . cache . _cache [ i ] . key == key )
{
AjaxTCR . comm . cache . _cache . splice ( i , 1 ) ;
break ;
}
}
} ,
setOptions : function ( cacheOptions ) {
for ( option in cacheOptions )
AjaxTCR . comm . cache . _cacheOptions [ option ] = cacheOptions [ option ] ;
} ,
_handleCacheResponse : function ( response , responseText ) {
response . xhr = { } ;
response . xhr . responseText = response . responseText = responseText ;
response . xhr . responseXML = response . responseXML = null ;
if ( responseText . indexOf ( " <?xml " ) > - 1 )
response . xhr . responseXML = response . responseXML = AjaxTCR . data . serializeXMLString ( responseText ) ;
response . xhr . status = response . httpStatus = 200 ;
response . xhr . statusText = response . httpStatusText = " OK " ;
response . fromCache = true ;
AjaxTCR . comm . _handleResponse ( response ) ;
} ,
_createCacheItem : function ( key , val ) {
var cacheObject = { } ;
cacheObject . key = key ;
cacheObject . value = val ;
cacheObject . lastAccessed = new Date ( ) ;
cacheObject . added = new Date ( ) ;
cacheObject . totalAccessed = 1 ;
return cacheObject ;
}
} ;
AjaxTCR . comm . queue = {
_responseQueue : { queue : new Array ( ) , currentIndex : 0 , maxID : 0 } ,
_requestQueue : new Array ( ) ,
_requestQueueID : 0 ,
requestQueueConcurrentRequests : 1 ,
add : function ( url , options , priority ) {
if ( options )
options . inQueue = true ;
else
options = { inQueue : true } ;
if ( ! priority )
options . priority = " normal " ;
else
options . priority = priority . toLowerCase ( ) ;
options . requestQueueID = ++ AjaxTCR . comm . queue . _requestQueueID ;
if ( AjaxTCR . comm . stats . getRequestCount ( " active " ) >= AjaxTCR . comm . queue . requestQueueConcurrentRequests )
{
var request = { url : url , options : options } ;
if ( options . priority == " next " )
AjaxTCR . comm . queue . _requestQueue . unshift ( request ) ;
else if ( priority && priority == " faster " )
{
var set = false ;
for ( var i = 0 ; i < AjaxTCR . comm . queue . _requestQueue . length ; i ++ )
{
if ( AjaxTCR . comm . queue . _requestQueue [ i ] . options . priority == " normal " )
{
AjaxTCR . comm . queue . _requestQueue . splice ( i , 0 , request ) ;
set = true ;
break ;
}
}
if ( ! set )
AjaxTCR . comm . queue . _requestQueue . push ( request ) ;
}
else
AjaxTCR . comm . queue . _requestQueue . push ( request ) ;
}
else
AjaxTCR . comm . sendRequest ( url , options ) ;
return options . requestQueueID ;
} ,
clear : function ( ) {
AjaxTCR . comm . queue . _requestQueue . length = 0 ;
} ,
get : function ( ID ) {
for ( var i = 0 ; i < AjaxTCR . comm . queue . _requestQueue . length ; i ++ )
{
if ( AjaxTCR . comm . queue . _requestQueue [ i ] . options . requestQueueID == ID )
return AjaxTCR . comm . queue . _requestQueue [ i ] ;
}
return null ;
} ,
getAll : function ( ) {
return AjaxTCR . comm . queue . _requestQueue ;
} ,
getPosition : function ( ID ) {
for ( var i = 0 ; i < AjaxTCR . comm . queue . _requestQueue . length ; i ++ )
{
if ( AjaxTCR . comm . queue . _requestQueue [ i ] . options . requestQueueID == ID )
return i ;
}
return - 1 ;
} ,
getSize : function ( ) {
return AjaxTCR . comm . queue . _requestQueue . length ;
} ,
remove : function ( ID ) {
for ( var i = 0 ; i < AjaxTCR . comm . queue . _requestQueue . length ; i ++ )
{
if ( AjaxTCR . comm . queue . _requestQueue [ i ] . options . requestQueueID == ID )
{
var ret = AjaxTCR . comm . queue . _requestQueue [ i ] ;
AjaxTCR . comm . queue . _requestQueue . splice ( i , 1 ) ;
return ret ;
}
}
return false ;
} ,
_checkRequestQueue : function ( response ) {
if ( response . inQueue && AjaxTCR . comm . queue . _requestQueue . length > 0 )
{
var nextRequest = AjaxTCR . comm . queue . _requestQueue . shift ( ) ;
AjaxTCR . comm . sendRequest ( nextRequest . url , nextRequest . options ) ;
}
} ,
_handleQueue : function ( response ) {
AjaxTCR . comm . queue . _responseQueue . queue [ response . responseQueueID ] = response ;
while ( AjaxTCR . comm . queue . _responseQueue . queue [ AjaxTCR . comm . queue . _responseQueue . currentIndex ] != undefined )
{
AjaxTCR . comm . _handleCallbacks ( AjaxTCR . comm . queue . _responseQueue . queue [ AjaxTCR . comm . queue . _responseQueue . currentIndex ] ) ;
AjaxTCR . comm . queue . _responseQueue . currentIndex ++;
}
}
} ;
AjaxTCR . comm . stats = {
_commResults : {
totalRequests : 0 ,
totalTimeouts : 0 ,
totalRetries : 0 ,
totalSuccesses : 0 ,
totalFails : 0 ,
requestFails : new Array ( ) } ,
collect : function ( url ) {
var sendConnectionStats = function ( ) {
var results = AjaxTCR . comm . stats . get ( ) ;
if ( results . totalRequests > 0 )
{
var payload = AjaxTCR . data . encodeJSON ( results ) ;
AjaxTCR . comm . sendRequest ( url , { method : " POST " , payload : payload , requestContentType : " application/json " , oneway : true } ) ;
}
} ;
if ( window . attachEvent )
window . attachEvent ( ' onunload ' , sendConnectionStats ) ;
else
window . addEventListener ( ' unload ' , sendConnectionStats , false ) ;
} ,
get : function ( ) {
return AjaxTCR . comm . stats . _commResults ;
} ,
getRequestCount : function ( type ) {
if ( type == " queued " )
return AjaxTCR . comm . queue . getSize ( ) ;
else if ( type == " active " )
return AjaxTCR . comm . _requestsOutstanding ;
else
return ( AjaxTCR . comm . queue . getSize ( ) + AjaxTCR . comm . _requestsOutstanding ) ;
}
} ;
AjaxTCR . comm . cookie = {
get : function ( name ) {
var fullname = name + " = " ;
var cookies = document . cookie . split ( ' ; ' ) ;
for ( var i = 0 ; i < cookies . length ; i ++ )
{
var cookieNV = cookies [ i ] ;
while ( cookieNV . charAt ( 0 ) == ' ' )
cookieNV = cookieNV . substring ( 1 ) ;
if ( cookieNV . indexOf ( fullname ) == 0 )
return cookieNV . substring ( fullname . length ) ;
}
return null ;
} ,
set : function ( key , value , expires , path ) {
if ( ! path )
path = " / " ;
document . cookie = key + " = " + value + " ; expires= " + expires + " ; path= " + path ;
} ,
remove : function ( key , path ) {
if ( ! path )
path = " / " ;
var now = new Date ( ) ;
now . setYear ( now . getYear ( ) - 1 ) ;
var expires = now . toGMTString ( ) ;
document . cookie = key + " =; expires= " + expires + " ; path= " + path ;
}
} ;
AjaxTCR . history = {
BACK_GUARD_DISABLED : 0 ,
BACK_GUARD_INITIALIZED : 1 ,
BACK_GUARD_ENABLED : 2 ,
_currentState : " " ,
_onStateChangeCallback : function ( ) { } ,
_iframeSrc : " blank.html " ,
_historyEnabled : false ,
_history : new Array ( ) ,
_historyPosition : 0 ,
_backGuardEnabled : 0 ,
_backGuardMessage : " Are you sure you wish to end your session? " ,
init : function ( onStateChangeCallback , initState ) {
if ( AjaxTCR . history . _historyEnabled )
return ;
else
AjaxTCR . history . _historyEnabled = true ;
AjaxTCR . history . _onStateChangeCallback = onStateChangeCallback ;
if ( ! ( navigator . userAgent . toLowerCase ( ) . indexOf ( " msie " ) >- 1 ) )
AjaxTCR . history . _checkHash ( ) ;
else
AjaxTCR . history . _checkHashIE ( ) ;
if ( ! window . location . hash )
AjaxTCR . history . addToHistory ( " AjaxTCRinit " , initState , document . title ) ;
else if ( ( navigator . userAgent . toLowerCase ( ) . indexOf ( " msie " ) >- 1 ) )
AjaxTCR . history . _initIE ( ) ;
} ,
addToHistory : function ( id , data , title , url , options ) {
if ( id != " AjaxTCRinit " )
{
window . location . hash = AjaxTCR . data . encodeValue ( id ) . replace ( /% 2 F / g , ' / ' ) ;;
AjaxTCR . history . _currentState = window . location . hash . substring ( 1 ) ;
}
var optionsString = " " ;
var safeStateName = id . replace ( / [ %\+ ] / g , " " ) ;
if ( title )
document . title = title ;
if ( options )
{
options . url = url ;
if ( navigator . userAgent . toLowerCase ( ) . indexOf ( " msie " ) >- 1 )
options . responseXML = " iebug " ;
optionsString = AjaxTCR . data . encode64 ( AjaxTCR . data . encodeJSON ( options ) ) ;
}
else if ( data )
{
options = { value : data } ;
optionsString = AjaxTCR . data . encode64 ( AjaxTCR . data . encodeJSON ( options ) ) ;
}
AjaxTCR . history . _historyPosition ++;
if ( navigator . userAgent . toLowerCase ( ) . indexOf ( " msie " ) >- 1 )
{
var iframe = document . getElementById ( " ieFix " ) ;
var html = ' <html><head><title>IE History</title><STYLE>.userData {behavior:url(#default#userdata);}</STYLE></head><body><div class="userData" id="persistDiv"></div><div id="currentState"> ' + AjaxTCR . history . _currentState + ' </div></body></html> ' ;
var doc = iframe . contentWindow . document ;
doc . open ( ) ;
doc . write ( html ) ;
doc . close ( ) ;
var persistDiv = doc . getElementById ( " persistDiv " ) ;
AjaxTCR . storage . add ( " request " , optionsString , persistDiv , safeStateName ) ;
if ( title )
AjaxTCR . storage . add ( " title " , title , persistDiv , safeStateName ) ;
AjaxTCR . storage . add ( " position " , AjaxTCR . history . _historyPosition , persistDiv , safeStateName ) ;
}
else if ( safeStateName )
{
AjaxTCR . storage . add ( safeStateName , optionsString ) ;
if ( title )
AjaxTCR . storage . add ( safeStateName + " title " , title ) ;
AjaxTCR . storage . add ( safeStateName + " position " , AjaxTCR . history . _historyPosition ) ;
}
var historyItem = { id : AjaxTCR . history . _currentState , title : title } ;
var diff = AjaxTCR . history . _history . length - AjaxTCR . history . _historyPosition + 1 ;
if ( diff > 0 )
AjaxTCR . history . _history . splice ( AjaxTCR . history . _historyPosition - 1 , diff ) ;
AjaxTCR . history . _history . push ( historyItem ) ;
} ,
getAll : function ( ) {
return AjaxTCR . history . _history ;
} ,
getPosition : function ( ) {
return AjaxTCR . history . _historyPosition ;
} ,
enableBackGuard : function ( message , immediate ) {
if ( AjaxTCR . history . _backGuardEnabled )
return ;
if ( message != null && typeof ( message ) != " undefined " )
AjaxTCR . history . _backGuardMessage = message ;
if ( immediate )
AjaxTCR . history . _activateBackGuard ( ) ;
else
AjaxTCR . history . _backGuardEnabled = AjaxTCR . history . BACK_GUARD_INITIALIZED ;
} ,
_activateBackGuard : function ( ) {
var message = AjaxTCR . history . _backGuardMessage ;
window . onbeforeunload = function ( ) { return message ; }
AjaxTCR . history . _backGuardEnabled = AjaxTCR . history . BACK_GUARD_ENABLED ;
} ,
_initIE : function ( ) {
var iframe = document . getElementById ( " ieFix " ) ;
var html = ' <html><head><title>IE History</title><STYLE>.userData {behavior:url(#default#userdata);}</STYLE></head><body><div class="userData" id="persistDiv"></div><div id="currentState"> ' + window . location . hash . substring ( 1 ) ; + ' </div></body></html> ' ;
var doc = iframe . contentWindow . document ;
doc . open ( ) ;
doc . write ( html ) ;
doc . close ( ) ;
} ,
_checkHashIE : function ( ) {
var iframe = document . getElementById ( " ieFix " ) ;
if ( ! iframe . contentWindow || ! iframe . contentWindow . document )
{
setTimeout ( _checkHashIE , 10 ) ;
return ;
}
var doc = iframe . contentWindow . document ;
var keyObj = doc . getElementById ( " currentState " ) ;
var key = " " ;
if ( keyObj )
key = keyObj . innerText ;
if ( key != AjaxTCR . history . _currentState )
{
AjaxTCR . history . _currentState = key ;
window . location . hash = key ;
var persistDiv = doc . getElementById ( " persistDiv " ) ;
var safeStateName = AjaxTCR . history . _currentState . replace ( / [ %\+ ] / g , " " ) ;
if ( ! safeStateName )
safeStateName = " AjaxTCRinit " ;
var title = AjaxTCR . storage . get ( " title " , persistDiv , safeStateName ) ;
if ( title )
document . title = title ;
AjaxTCR . history . _historyPosition = AjaxTCR . storage . get ( " position " , persistDiv , safeStateName ) ;
if ( AjaxTCR . history . _historyPosition > AjaxTCR . history . _history . length )
{
AjaxTCR . history . _historyPosition = 1 ;
AjaxTCR . storage . add ( " position " , AjaxTCR . history . _historyPosition , persistDiv , safeStateName ) ;
var historyItem = { id : AjaxTCR . history . _currentState , title : title } ;
AjaxTCR . history . _history . push ( historyItem ) ;
}
var optionsString = AjaxTCR . storage . get ( " request " , persistDiv , safeStateName ) ;
AjaxTCR . history . _handleHistoryCallback ( optionsString ) ;
}
setTimeout ( " AjaxTCR.history._checkHashIE(); " , 500 ) ;
} ,
_checkHash : function ( ) {
if ( ( window . location . hash != " # " + AjaxTCR . history . _currentState ) && window . location . hash != AjaxTCR . history . _currentState )
{
AjaxTCR . history . _currentState = window . location . hash . substring ( 1 ) ;
var safeStateName = AjaxTCR . history . _currentState . replace ( / [ %\+ ] / g , " " ) ;
if ( ! safeStateName )
safeStateName = " AjaxTCRinit " ;
var title = AjaxTCR . storage . get ( safeStateName + " title " ) ;
if ( title )
document . title = title . value ;
AjaxTCR . history . _historyPosition = AjaxTCR . storage . get ( safeStateName + " position " ) . value ;
if ( AjaxTCR . history . _historyPosition > AjaxTCR . history . _history . length )
{
AjaxTCR . history . _historyPosition = 1 ;
AjaxTCR . storage . add ( safeStateName + " position " , AjaxTCR . history . _historyPosition ) ;
var historyItem = { id : AjaxTCR . history . _currentState , title : title } ;
AjaxTCR . history . _history . push ( historyItem ) ;
}
var results = AjaxTCR . storage . get ( safeStateName ) ;
if ( results )
AjaxTCR . history . _handleHistoryCallback ( results . value ) ;
else
AjaxTCR . history . _onStateChangeCallback ( AjaxTCR . data . decodeValue ( AjaxTCR . history . _currentState ) ) ;
}
setTimeout ( " AjaxTCR.history._checkHash(); " , 500 ) ;
} ,
_handleHistoryCallback : function ( optionsString ) {
if ( optionsString && optionsString != " " )
{
var str = AjaxTCR . data . decode64 ( optionsString ) ;
var options = AjaxTCR . data . decodeJSON ( AjaxTCR . data . decode64 ( optionsString ) ) ;
if ( options . history )
{
if ( options . history . saveResponse )
{
options . history = null ;
AjaxTCR . comm . cache . _handleCacheResponse ( options , options . responseText ) ;
}
else
{
options . history = null ;
AjaxTCR . comm . sendRequest ( options . url , options ) ;
}
}
else
AjaxTCR . history . _onStateChangeCallback ( AjaxTCR . data . decodeValue ( AjaxTCR . history . _currentState ) , options . value ) ;
}
else
AjaxTCR . history . _onStateChangeCallback ( AjaxTCR . data . decodeValue ( AjaxTCR . history . _currentState ) ) ;
}
} ;
AjaxTCR . storage = {
DEFAULT_MAX_COOKIE_SIZE : 4000 ,
init : function ( ) {
if ( navigator . userAgent . toLowerCase ( ) . indexOf ( " msie " ) >- 1 )
{
var persistDiv = document . createElement ( " div " ) ;
persistDiv . id = " AjaxTCRPersistDiv " ;
persistDiv . style . behavior = " url(#default#userData) " ;
document . body . appendChild ( persistDiv ) ;
return persistDiv ;
}
return null ;
} ,
add : function ( key , value , persistObj , store ) {
var setFlag = 0 ;
if ( navigator . userAgent . toLowerCase ( ) . indexOf ( " msie " ) >- 1 )
{
if ( ! store )
store = " AjaxTCRStore " ;
if ( persistObj )
{
var allitemsString = AjaxTCR . storage . get ( " AjaxTCRAllItems " , persistObj , store ) ;
if ( ! allitemsString )
var allitemsObj = { } ;
else
var allitemsObj = AjaxTCR . data . decodeJSON ( allitemsString ) ;
allitemsObj [ key ] = value ;
allitemsString = AjaxTCR . data . encodeJSON ( allitemsObj ) ;
persistObj . setAttribute ( " AjaxTCRAllItems " , allitemsString ) ;
persistObj . setAttribute ( key , value ) ;
persistObj . save ( store ) ;
setFlag = 1 ;
}
}
else if ( typeof ( globalStorage ) != " undefined " )
{
try {
var storage = globalStorage [ document . domain ] ;
storage . setItem ( key , value ) ;
setFlag = 1 ;
}
catch ( e ) { }
}
if ( ! setFlag )
{
var allitemsString = AjaxTCR . storage . get ( " AjaxTCRAllItems " ) ;
if ( ! allitemsString )
var allitemsObj = new Array ( ) ;
else
var allitemsObj = AjaxTCR . data . decodeJSON ( allitemsString ) ;
allitemsObj . push ( key ) ;
allitemsString = AjaxTCR . data . encodeJSON ( allitemsObj ) ;
var now = new Date ( ) ;
now . setMonth ( now . getMonth ( ) + 1 ) ;
var expires = now . toGMTString ( ) ;
var pieces = Math . floor ( allitemsString . length / AjaxTCR . storage . DEFAULT_MAX_COOKIE_SIZE + 1 ) ;
for ( var i = 0 ; i < pieces ; i ++ )
AjaxTCR . comm . cookie . set ( " AjaxTCRAllItems " + i . toString ( ) , allitemsString . substring ( i * AjaxTCR . storage . DEFAULT_MAX_COOKIE_SIZE , AjaxTCR . storage . DEFAULT_MAX_COOKIE_SIZE ) , expires ) ;
var pieces = Math . floor ( value . length / AjaxTCR . storage . DEFAULT_MAX_COOKIE_SIZE + 1 ) ;
for ( var i = 0 ; i < pieces ; i ++ )
AjaxTCR . comm . cookie . set ( key + i . toString ( ) , value . substring ( i * AjaxTCR . storage . DEFAULT_MAX_COOKIE_SIZE , AjaxTCR . storage . DEFAULT_MAX_COOKIE_SIZE ) , expires ) ;
}
} ,
get : function ( key , persistObj , store ) {
if ( navigator . userAgent . toLowerCase ( ) . indexOf ( " msie " ) >- 1 )
{
if ( ! store )
store = " AjaxTCRStore " ;
if ( persistObj )
{
persistObj . load ( store ) ;
return persistObj . getAttribute ( key ) ;
}
}
else if ( typeof ( globalStorage ) != " undefined " )
{
try {
var storage = globalStorage [ document . domain ] ;
return storage . getItem ( key ) ;
}
catch ( e ) { }
}
var i = 0 ;
var fullvalue = " " ;
do
{
var val = AjaxTCR . comm . cookie . get ( key + i . toString ( ) ) ;
if ( val )
fullvalue += val ;
i ++;
} while ( val ) ;
if ( fullvalue != " " )
return fullvalue ;
return null ;
} ,
getAll : function ( persistObj , store ) {
if ( navigator . userAgent . toLowerCase ( ) . indexOf ( " msie " ) >- 1 )
{
if ( ! store )
store = " AjaxTCRStore " ;
if ( persistObj )
{
var allitems = AjaxTCR . storage . get ( " AjaxTCRAllItems " , persistObj , store ) ;
return AjaxTCR . data . decodeJSON ( allitems ) ;
}
}
else if ( typeof ( globalStorage ) != " undefined " )
{
try {
var storage = globalStorage [ document . domain ] ;
return storage ;
}
catch ( e ) { }
}
var allitems = AjaxTCR . storage . get ( " AjaxTCRAllItems " ) ;
if ( allitems )
{
var items = { } ;
var keys = AjaxTCR . data . decodeJSON ( allitems ) ;
for ( var i = 0 ; i < keys . length ; i ++ )
items [ keys [ i ] ] = AjaxTCR . storage . get ( keys [ i ] ) ;
return items ;
}
return null ;
} ,
clear : function ( persistObj , store ) {
var allItems = AjaxTCR . storage . getAll ( persistObj , store ) ;
for ( var i in allItems )
AjaxTCR . storage . remove ( i , persistObj , store ) ;
} ,
remove : function ( key , persistObj , store ) {
var removeFlag = 0 ;
if ( navigator . userAgent . toLowerCase ( ) . indexOf ( " msie " ) >- 1 )
{
if ( ! store )
store = " AjaxTCRStore " ;
if ( persistObj )
{
var allitems = AjaxTCR . storage . get ( " AjaxTCRAllItems " , persistObj , store ) ;
if ( allitems )
{
allitems = AjaxTCR . data . decodeJSON ( allitems ) ;
if ( allitems [ key ] )
delete allitems [ key ] ;
allitems = AjaxTCR . data . encodeJSON ( allitems ) ;
persistObj . setAttribute ( " AjaxTCRAllItems " , allitems ) ;
}
persistObj . removeAttribute ( key ) ;
persistObj . save ( store ) ;
removeFlag = 1 ;
}
}
else if ( typeof ( globalStorage ) != " undefined " )
{
try {
var storage = globalStorage [ document . domain ] ;
delete storage [ key ] ;
removeFlag = 1 ;
}
catch ( e ) { }
}
if ( ! removeFlag )
{
var allitems = AjaxTCR . storage . get ( " AjaxTCRAllItems " , persistObj , store ) ;
if ( allitems )
{
allitems = AjaxTCR . data . decodeJSON ( allitems ) ;
for ( var i = allitems . length - 1 ; i >= 0 ; i -- )
{
if ( allitems [ i ] == key )
delete allitems [ i ] ;
}
var allitemsString = AjaxTCR . data . encodeJSON ( allitems ) ;
var loops = Math . floor ( allitemsString . length / AjaxTCR . storage . DEFAULT_MAX_COOKIE_SIZE + 1 ) ;
var now = new Date ( ) ;
now . setMonth ( now . getMonth ( ) + 1 ) ;
var expires = now . toGMTString ( ) ;
for ( var i = 0 ; i < loops ; i ++ )
AjaxTCR . comm . cookie . set ( " AjaxTCRAllItems " + i . toString ( ) , allitemsString . substring ( i * AjaxTCR . storage . DEFAULT_MAX_COOKIE_SIZE , AjaxTCR . storage . DEFAULT_MAX_COOKIE_SIZE ) , expires ) ;
var i = 0 ;
do
{
var val = AjaxTCR . comm . cookie . get ( key + i . toString ( ) ) ;
if ( val )
AjaxTCR . comm . cookie . remove ( key + i . toString ( ) ) ;
i ++;
} while ( val ) ;
}
}
}
} ;
AjaxTCR . template = {
_libraryIncluded : false ,
_cache : new Array ( ) ,
translateString : function ( template , data ) {
var myTemplateObj = TrimPath . parseTemplate ( template ) ;
var result = myTemplateObj . process ( AjaxTCR . data . decodeJSON ( data ) ) ;
return result ;
} ,
translateFile : function ( templatefilename , data , cache ) {
if ( typeof ( cache ) == " undefined " )
cache = true ;
var template = AjaxTCR . template . getFromCache ( templatefilename ) ;
if ( ! template )
{
var templateRequest = AjaxTCR . comm . sendRequest ( templatefilename , { async : false , cacheResponse : cache } ) ;
var template = templateRequest . responseText ;
if ( cache && template )
AjaxTCR . template . addToCache ( templatefilename , template ) ;
}
if ( typeof ( data ) == " string " )
data = AjaxTCR . data . decodeJSON ( data ) ;
var myTemplateObj = TrimPath . parseTemplate ( template ) ;
var result = myTemplateObj . process ( data ) ;
return result ;
} ,
addToCache : function ( key , val ) {
var item = AjaxTCR . template . _createCacheItem ( key , val ) ;
AjaxTCR . template . _cache . push ( item ) ;
} ,
cache : function ( key , val ) {
if ( val )
AjaxTCR . template . addToCache ( key , val ) ;
else
{
var options = { cacheTemplate : true ,
onSuccess : function ( response ) {
if ( response . responseText )
AjaxTCR . template . addToCache ( response . url , response . responseText ) ;
}
} ;
AjaxTCR . comm . sendRequest ( key , options ) ;
}
} ,
cacheBundle : function ( url ) {
var options = { cacheTemplate : true ,
onSuccess : AjaxTCR . template . _parseTemplateBundle } ;
AjaxTCR . comm . sendRequest ( url , options ) ;
} ,
clearCache : function ( ) {
AjaxTCR . template . _cache = new Array ( ) ;
} ,
getFromCache : function ( key ) {
var cacheObject = null ;
for ( var i = 0 ; i < AjaxTCR . template . _cache . length ; i ++ )
{
if ( AjaxTCR . template . _cache [ i ] . key == key )
{
cacheObject = AjaxTCR . template . _cache [ i ] ;
break ;
}
}
if ( cacheObject )
return cacheObject . value ;
else
return null ;
} ,
removeFromCache : function ( key ) {
for ( var i = 0 ; i < AjaxTCR . template . _cache . length ; i ++ )
{
if ( AjaxTCR . template . _cache [ i ] . key == key )
{
AjaxTCR . template . _cache . splice ( i , 1 ) ;
break ;
}
}
} ,
_createCacheItem : function ( key , val ) {
var cacheObject = { } ;
cacheObject . key = key ;
cacheObject . value = val ;
return cacheObject ;
} ,
_includeLibrary : function ( ) {
if ( ! AjaxTCR . template . _libraryIncluded )
document . write ( ' <sc ' + ' ript type="text/javascript" src="http://ajaxref.com/lib/trimpath/template.js"></sc ' + ' ript> ' ) ;
AjaxTCR . template . _libraryIncluded = true ;
} ,
_parseTemplateBundle : function ( response ) {
var bundle = response . responseText ;
var re = /\ s *\<!--\ s * Template - Begin ( [ \ w \ W ] *? ) \<!--\ s * Template - End \ s *--\>\ s */ ig ;
var matches = bundle . match ( re ) ;
for ( var i = 0 ; i < matches . length ; i ++ )
{
var parts = /\ s *\<!--\ s * Template - Begin \ s * URL = [ ' "]([^ ' " ]*)[' " ] \ s *--\> ( [ \ w \ W ] *? ) \<!--\ s * Template - End \ s *--\>\ s */ i ;
var data = parts . exec ( matches [ i ] ) ;
if ( data )
AjaxTCR . template . addToCache ( data [ 1 ] , data [ 2 ] ) ;
}
}
} ;
AjaxTCR . data = {
encodeValue : function ( val ) {
var encodedVal ;
if ( ! encodeURIComponent )
{
encodedVal = escape ( val ) ;
encodedVal = encodedVal . replace ( /@/ g , ' %40 ' ) ;
encodedVal = encodedVal . replace ( /\
encodedVal = encodedVal . replace ( /\+/ g , ' %2B ' ) ;
}
else
{
encodedVal = encodeURIComponent ( val ) ;
encodedVal = encodedVal . replace ( /~/ g , ' %7E ' ) ;
encodedVal = encodedVal . replace ( /!/ g , ' %21 ' ) ;
encodedVal = encodedVal . replace ( /\ ( / g , ' %28 ' ) ;
encodedVal = encodedVal . replace ( /\ ) / g , ' %29 ' ) ;
encodedVal = encodedVal . replace ( / ' /g, ' % 27 ' );
}
/* clean up the spaces and return */
return encodedVal.replace(/\%20/g, ' + ' );
} ,
/**
* Public method to decode passed string values from a URL safe string.
*
* @param {string} val - the value to decode
* @return {string} a string that is properly reversed from the proper x-www-urlencoded format
*/
decodeValue : function(val) {
var decodedVal;
if (!decodeURIComponent)
{
decodedVal = val;
/* fix the omissions */
decodedVal = decodedVal.replace(/\%40/g, ' @ ' );
decodedVal = decodedVal.replace(/\%2F/g, ' / ' );
decodedVal = decodedVal.replace(/\%2B/g, ' + ' );
decodedVal = unescape(val);
}
else
{
/* fix the omissions */
decodedVal = val;
decodedVal = decodedVal.replace(/\%7E/g, ' ~ ' );
decodedVal = decodedVal.replace(/\%21/g, ' ! ' );
decodedVal = decodedVal.replace(/\%28/g, ' ( ' );
decodedVal = decodedVal.replace(/\%29/g, ' ) ' );
decodedVal = decodedVal.replace(/\%27/g, " ' " );
decodedVal = decodeURIComponent(val);
}
/* clean up the spaces and return */
return decodedVal.replace(/\+/g,' ');
} ,
/**
* Public method to convert tag characters to < and > and change \n to <br />
*
* @param {string} str String to modify
* @return {string} The str value with the conversions in place
*/
encodeAsHTML : function(str) {
var convertedString = str.replace(/<([^>]*)>/g, " & lt ;$ 1 & gt ; " )
convertedString = convertedString.replace(/ \n /g, " < br /> " );
return convertedString;
},
/**
* Public method to encode passed string values into base64.
*
* @param {string} inputStr A string value to encode
* @return {string} The inputStr value encoded in base64
*/
encode64 : function(inputStr)
{
var b64 = " ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789 +/= " ;
var outputStr = " " ;
var i = 0;
while (i<inputStr.length)
{
var byte1 = inputStr.charCodeAt(i++);
var byte2 = inputStr.charCodeAt(i++);
var byte3 = inputStr.charCodeAt(i++);
var enc1 = byte1 >> 2;
var enc2 = ((byte1 & 3) << 4) | (byte2 >> 4);
var enc3, enc4;
if (isNaN(byte2))
enc3 = enc4 = 64;
else
{
enc3 = ((byte2 & 15) << 2) | (byte3 >> 6);
if (isNaN(byte3))
enc4 = 64;
else
enc4 = byte3 & 63;
}
outputStr += b64.charAt(enc1) + b64.charAt(enc2) + b64.charAt(enc3) + b64.charAt(enc4);
}
return outputStr;
},
/**
* Public method to decode passed string values from base64.
*
* @param {string} inputStr A string in base64 format
* @return {string} The decoded string
*/
decode64 : function(inputStr)
{
var b64 = " ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789 +/= " ;
var outputStr = " " ;
var i = 0;
inputStr = inputStr.replace(/[^A-Za-z0-9\+\/\=]/g, " " );
while (i<inputStr.length)
{
var dec1 = b64.indexOf(inputStr.charAt(i++));
var dec2 = b64.indexOf(inputStr.charAt(i++));
var dec3 = b64.indexOf(inputStr.charAt(i++));
var dec4 = b64.indexOf(inputStr.charAt(i++));
var byte1 = (dec1 << 2) | (dec2 >> 4);
var byte2 = ((dec2 & 15) << 4) | (dec3 >> 2);
var byte3 = ((dec3 & 3) << 6) | dec4;
outputStr += String.fromCharCode(byte1);
if (dec3 != 64)
outputStr += String.fromCharCode(byte2);
if (dec4 != 64)
outputStr += String.fromCharCode(byte3);
}
return outputStr;
},
/**
* Public method to create a serialized payload based on the contents of a form and the specified encoding value.
* trigger and evt are optional and used to firm up the accuracy between what the browser would send and what we send.
*
* @param {object} form The form to be serialized
* @param {string} encoding The encoding of the result. Options are " application / json " , " application / x - www - form - urlencoded " , " text / plain " , " text / xml "
* @param {object} trigger The element that caused the submission of the form. input type= " button " fields will only be included in the payload if they triggered the submission.
* @param {object} evt In the case that a input type= " image " caused the submission, if the evt is passed in, the coordinates of the click will be put in the payload
* @return {string} The payload serialized according to the specified encoding.
*/
serializeForm : function(form, encoding, trigger, evt) {
if (typeof(form) == " string " )
{
var formObject = document.forms[form];
if (formObject == null)
formObject = document.getElementById(form);
form = formObject;
}
var x=0,y=0;
if (trigger && trigger.type == " image " && trigger.name)
{
if (window.event)
{
x = window.event.offsetX;
y = window.event.offsetY;
}
else if (evt.target)
{
var coords = {x: 0, y: 0 };
var elmt = trigger;
while (elmt)
{
coords.x += elmt.offsetLeft;
coords.y += elmt.offsetTop;
elmt = elmt.offsetParent;
}
x = evt.clientX + window.scrollX - coords.x - 1 ;
y = evt.clientY + window.scrollY - coords.y - 1;
}
}
var formValues = AjaxTCR.data._beginEncode(encoding);
for (var i =0; i < form.elements.length; i++)
{
var currentField = form.elements[i];
var fieldName = currentField.name;
var fieldType = currentField.type;
/* Disabled and unnamed fields are not sent by browsers so ignore them */
if ((!currentField.disabled) && fieldName)
{
switch (fieldType)
{
case " text " :
case " password " :
case " hidden " :
case " textarea " : formValues = AjaxTCR.data._encode(formValues, fieldName, currentField.value, encoding);
break;
case " radio " :
case " checkbox " : if (currentField.checked)
formValues = AjaxTCR.data._encode(formValues, fieldName, currentField.value, encoding);
break;
case 'select-one':
case 'select-multiple': for (var j=0; j< currentField.options.length; j++)
if (currentField.options[j].selected)
{
formValues = AjaxTCR.data._encode(formValues, fieldName, (currentField.options[j].value != null && currentField.options[j].value != " " ) ? currentField.options[j].value : currentField.options[j].text , encoding);
}
break;
case " file " : if (currentField.value)
return " fileupload " ;
else
formValues = AjaxTCR.data._encode(formValues, fieldName, currentField.value, encoding);
break;
case " submit " : if (currentField == trigger)
formValues = AjaxTCR.data._encode(formValues, fieldName, currentField.value, encoding);
break;
default: continue; /* everything else like fieldset you don't want */
}
}
}
if (trigger && trigger.type == " image " && trigger.name)
{
/* this is where we need to insert the trigger image information */
formValues = AjaxTCR.data._encode(formValues, trigger.name + " . x " , x, encoding);
formValues = AjaxTCR.data._encode(formValues, trigger.name + " . y " , y, encoding);
formValues = AjaxTCR.data._encode(formValues, trigger.name, trigger.value, encoding);
}
/* Clean up payload string */
formValues = AjaxTCR.data._completeEncoding(formValues, encoding);
return formValues;
},
/**
* Public method to create/modify a serialized object based on an object
* @param {object} payload the current object that will be appended to.
* @param {object} obj is the object to add to the payload
* @param {string} encoding The encoding of the result. Options are " application / json " , " application / x - www - form - urlencoded " , " text / plain " , " text / xml "
* @return {object} The new payload with the object included
*/
serializeObject : function(payload, obj, encoding){
/* Take care of any necessary bits if payload isn't empty */
payload = AjaxTCR.data._continueEncoding(payload, encoding);
/* encode each value in the object */
for (var key in obj)
payload = AjaxTCR.data._encode(payload, key, obj[key], encoding);
/* Clean up payload string */
payload = AjaxTCR.data._completeEncoding(payload, encoding);
return payload;
},
/**
* private method to encode one name/value pair and add it to a payload.
*
* @private
* @param {object} payload is current object that will be appended to. It can be null.
* @param {string} fieldName The name of the item to encode
* @param {string} fieldValue The value of the item to encode
* @param {string} encoding The encoding of the result. Options are " application / json " , " application / x - www - form - urlencoded " , " text / plain " , " text / xml "
* @return {object} The new payload with the new name/value pair included
*/
_encode : function(payload, fieldName, fieldValue, encoding){
switch(encoding)
{
case " application / json " :
payload[fieldName] = fieldValue;
break;
case " application / x - www - form - urlencoded " :
payload+=AjaxTCR.data.encodeValue(fieldName)+ " = " +AjaxTCR.data.encodeValue(fieldValue)+ " & "
break;
case " text / plain " :
payload+=fieldName.replace(/,/g, " % 2 C " ) + " = " + fieldValue.replace(/,/g, " % 2 C " ) + " , "
break;
case " text / xml " :
var node = payload.createElement(fieldName);
node.appendChild(payload.createTextNode(fieldValue));
payload.lastChild.appendChild(node);
break;
}
return payload;
},
/**
* private method to create the base for the encoding object
*
* @private
* @param {string} encoding The encoding of the result. Options are " application / json " , " application / x - www - form - urlencoded " , " text / plain " , " text / xml "
* @return {object} Either an empty string, xml frame, or an empty object depending on type
*/
_beginEncode : function(encoding){
switch(encoding)
{
case " application / json " :
if (payload == null)
payload = {};
break;
case " application / x - www - form - urlencoded " :
if (payload == null)
payload = " " ;
break;
case " text / plain " :
if (payload == null)
payload = " " ;
break;
case " text / xml " :
if (payload == null)
{
var payload = AjaxTCR.data._createXMLDocument();
if (window.navigator.userAgent.indexOf('Opera') == -1)
{
var xmlStmt = payload.createProcessingInstruction( " xml " , " version =\ " 1.0 \" encoding= \" UTF-8 \" " ) ;
payload . appendChild ( xmlStmt ) ;
}
var root = payload . createElement ( " payload " ) ;
payload . appendChild ( root ) ;
}
break ;
}
return payload ;
},
_completeEncoding : function ( payload , encoding ) {
if ( ( encoding == " application/x-www-form-urlencoded " || encoding == " text/plain " ) && payload . length > 0 )
payload = payload . substring ( 0 , payload . length - 1 ) ;
return payload ;
} ,
_continueEncoding : function ( payload , encoding ) {
if ( payload != " " )
{
if ( encoding == " application/x-www-form-urlencoded " )
payload += " & " ;
else if ( encoding == " text/plain " )
payload += " , " ;
}
return payload ;
} ,
_createXMLDocument : function ( ) {
var xmlDoc = null ;
if ( window . ActiveXObject )
{
var versions = [ " Msxml2.DOMDocument.6.0 " , " Msxml2.DOMDocument.3.0 " , " MSXML2.DOMDocument " , " MSXML.DOMDocument " , " Microsoft.XMLDOM " ] ;
for ( var i = 0 ; i < versions . length ; i ++ )
{
try
{
xmlDoc = new ActiveXObject ( versions [ i ] ) ;
break ;
}
catch ( err ) { }
}
}
else
xmlDoc = document . implementation . createDocument ( " " , " " , null ) ;
return xmlDoc ;
} ,
serializeXML : function ( xmlObject ) {
var xmlString = " " ;
if ( typeof XMLSerializer != " undefined " )
xmlString = ( new XMLSerializer ( ) ) . serializeToString ( xmlObject ) ;
else if ( xmlObject . xml )
xmlString = xmlObject . xml ;
return xmlString ;
} ,
serializeXMLString : function ( xmlStr ) {
if ( window . DOMParser )
var xmlDoc = ( new DOMParser ( ) ) . parseFromString ( xmlStr , " text/xml " ) ;
else
{
var xmlDoc = new ActiveXObject ( " Microsoft.XMLDOM " ) ;
xmlDoc . async = " false " ;
xmlDoc . loadXML ( xmlStr ) ;
}
return xmlDoc ;
} ,
decodeJSON : function ( jsonString ) {
var j ;
if ( jsonString . length > 1 && jsonString . substring ( 0 , 2 ) == " /* " )
jsonString = jsonString . substring ( 2 , jsonString . lastIndexOf ( " */ " ) ) ;
try {
j = eval ( ' ( ' + jsonString + ' ) ' ) ;
}
catch ( e ) {
throw new SyntaxError ( ' parseJSON ' ) ;
}
return j ;
} ,
encodeJSON : function ( o ) {
var useHasOwn = { } . hasOwnProperty ? true : false ;
var pad = function ( n ) {
return n < 10 ? ' 0 ' + n : n ;
} ;
var m = {
' \b ' : ' \\ b ' ,
' \t ' : ' \\ t ' ,
' \n ' : ' \\ n ' ,
' \f ' : ' \\ f ' ,
' \r ' : ' \\ r ' ,
' " ' : ' \\ " ' ,
' \\ ' : ' \\ \\ '
} ;
if ( typeof o == ' undefined ' || o === null )
return ' null ' ;
else if ( o instanceof Array )
{
var a = [ ' [ ' ] , b , i , l = o . length , v ;
for ( i = 0 ; i < l ; i += 1 ) {
v = o [ i ] ;
switch ( typeof v ) {
case ' undefined ' :
case ' unknown ' :
break ;
default :
if ( b ) {
a . push ( ' , ' ) ;
}
a . push ( v === null ? " null " : AjaxTCR . data . encodeJSON ( v ) ) ;
b = true ;
}
}
a . push ( ' ] ' ) ;
return a . join ( ' ' ) ;
}
else if ( o instanceof Date )
{
return ' " ' + o . getFullYear ( ) + ' - ' +
pad ( o . getMonth ( ) + 1 ) + ' - ' +
pad ( o . getDate ( ) ) + ' T ' +
pad ( o . getHours ( ) ) + ' : ' +
pad ( o . getMinutes ( ) ) + ' : ' +
pad ( o . getSeconds ( ) ) + ' " ' ;
}
else if ( typeof o == ' string ' )
{
var s = o ;
if ( / [ " \\ \x00-\x1f]/.test(s))
{
return ' " ' + s.replace(/([\x00-\x1f \\ "])/g, function(a, b)
{
var c = m[b];
if(c){
return c;
}
c = b.charCodeAt();
return ' \\ u00 ' +
Math.floor(c / 16).toString(16) +
(c % 16).toString(16);
}) + ' " ';
}
return ' " ' + s + ' " ';
}
else if(typeof o == 'number')
{
return isFinite(o) ? String(o) : " null " ;
}
else if(typeof o == 'boolean')
{
return String(o);
}
else if (typeof o == 'function')
{
//return String(o).replace(/ \n /g, " " );
return '( ' + String(o) + ' )';
}
else
{
var a = ['{'], b, i, v;
for (var i in o) {
try{
if(!useHasOwn || o.hasOwnProperty(i)) {
v = o[i];
switch (typeof v) {
case 'undefined':
// case 'function':
case 'unknown':
break;
case 'function':
if (String(v).indexOf( " [ native code ] " ) > -1)
break;
default:
if(b)
a.push(',');
a.push(AjaxTCR.data.encodeJSON(i), ':', v === null ? " null " : AjaxTCR.data.encodeJSON(v));
b = true;
}
}
}
catch(e){};
}
a.push('}');
return a.join('');
}
},
/**
* encodeMD5(string)
*
* public method to get md5 encode a string
* Based on Version 2.1 Copyright (C) Paul Johnston 1999 - 2002.
* Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
* Distributed under the BSD License
* See http://pajhome.org.uk/crypt/md5 for more info.
*
* @param {string} str The string to encode
* @return {string} A string that is encoded in MD5 format
*/
encodeMD5 : function(str){
var hexcase = 0; /* hex output format. 0 - lowercase; 1 - uppercase */
var b64pad = " " ; /* base-64 pad character. " = " for strict RFC compliance */
var chrsz = 8; /* bits per input character. 8 - ASCII; 16 - Unicode */
var len = str.length * chrsz;
var x = Array();
var mask = (1 << chrsz) - 1;
for(var i = 0; i < len; i += chrsz)
{
x[i>>5] |= (str.charCodeAt(i / chrsz) & mask) << (i%32);
}
/* append padding */
x[len >> 5] |= 0x80 << ((len) % 32);
x[(((len + 64) >>> 9) << 4) + 14] = len;
var a = 1732584193;
var b = -271733879;
var c = -1732584194;
var d = 271733878;
for(var i = 0; i < x.length; i += 16)
{
var olda = a;
var oldb = b;
var oldc = c;
var oldd = d;
a = md5_ff(a, b, c, d, x[i+ 0], 7 , -680876936);
d = md5_ff(d, a, b, c, x[i+ 1], 12, -389564586);
c = md5_ff(c, d, a, b, x[i+ 2], 17, 606105819);
b = md5_ff(b, c, d, a, x[i+ 3], 22, -1044525330);
a = md5_ff(a, b, c, d, x[i+ 4], 7 , -176418897);
d = md5_ff(d, a, b, c, x[i+ 5], 12, 1200080426);
c = md5_ff(c, d, a, b, x[i+ 6], 17, -1473231341);
b = md5_ff(b, c, d, a, x[i+ 7], 22, -45705983);
a = md5_ff(a, b, c, d, x[i+ 8], 7 , 1770035416);
d = md5_ff(d, a, b, c, x[i+ 9], 12, -1958414417);
c = md5_ff(c, d, a, b, x[i+10], 17, -42063);
b = md5_ff(b, c, d, a, x[i+11], 22, -1990404162);
a = md5_ff(a, b, c, d, x[i+12], 7 , 1804603682);
d = md5_ff(d, a, b, c, x[i+13], 12, -40341101);
c = md5_ff(c, d, a, b, x[i+14], 17, -1502002290);
b = md5_ff(b, c, d, a, x[i+15], 22, 1236535329);
a = md5_gg(a, b, c, d, x[i+ 1], 5 , -165796510);
d = md5_gg(d, a, b, c, x[i+ 6], 9 , -1069501632);
c = md5_gg(c, d, a, b, x[i+11], 14, 643717713);
b = md5_gg(b, c, d, a, x[i+ 0], 20, -373897302);
a = md5_gg(a, b, c, d, x[i+ 5], 5 , -701558691);
d = md5_gg(d, a, b, c, x[i+10], 9 , 38016083);
c = md5_gg(c, d, a, b, x[i+15], 14, -660478335);
b = md5_gg(b, c, d, a, x[i+ 4], 20, -405537848);
a = md5_gg(a, b, c, d, x[i+ 9], 5 , 568446438);
d = md5_gg(d, a, b, c, x[i+14], 9 , -1019803690);
c = md5_gg(c, d, a, b, x[i+ 3], 14, -187363961);
b = md5_gg(b, c, d, a, x[i+ 8], 20, 1163531501);
a = md5_gg(a, b, c, d, x[i+13], 5 , -1444681467);
d = md5_gg(d, a, b, c, x[i+ 2], 9 , -51403784);
c = md5_gg(c, d, a, b, x[i+ 7], 14, 1735328473);
b = md5_gg(b, c, d, a, x[i+12], 20, -1926607734);
a = md5_hh(a, b, c, d, x[i+ 5], 4 , -378558);
d = md5_hh(d, a, b, c, x[i+ 8], 11, -2022574463);
c = md5_hh(c, d, a, b, x[i+11], 16, 1839030562);
b = md5_hh(b, c, d, a, x[i+14], 23, -35309556);
a = md5_hh(a, b, c, d, x[i+ 1], 4 , -1530992060);
d = md5_hh(d, a, b, c, x[i+ 4], 11, 1272893353);
c = md5_hh(c, d, a, b, x[i+ 7], 16, -155497632);
b = md5_hh(b, c, d, a, x[i+10], 23, -1094730640);
a = md5_hh(a, b, c, d, x[i+13], 4 , 681279174);
d = md5_hh(d, a, b, c, x[i+ 0], 11, -358537222);
c = md5_hh(c, d, a, b, x[i+ 3], 16, -722521979);
b = md5_hh(b, c, d, a, x[i+ 6], 23, 76029189);
a = md5_hh(a, b, c, d, x[i+ 9], 4 , -640364487);
d = md5_hh(d, a, b, c, x[i+12], 11, -421815835);
c = md5_hh(c, d, a, b, x[i+15], 16, 530742520);
b = md5_hh(b, c, d, a, x[i+ 2], 23, -995338651);
a = md5_ii(a, b, c, d, x[i+ 0], 6 , -198630844);
d = md5_ii(d, a, b, c, x[i+ 7], 10, 1126891415);
c = md5_ii(c, d, a, b, x[i+14], 15, -1416354905);
b = md5_ii(b, c, d, a, x[i+ 5], 21, -57434055);
a = md5_ii(a, b, c, d, x[i+12], 6 , 1700485571);
d = md5_ii(d, a, b, c, x[i+ 3], 10, -1894986606);
c = md5_ii(c, d, a, b, x[i+10], 15, -1051523);
b = md5_ii(b, c, d, a, x[i+ 1], 21, -2054922799);
a = md5_ii(a, b, c, d, x[i+ 8], 6 , 1873313359);
d = md5_ii(d, a, b, c, x[i+15], 10, -30611744);
c = md5_ii(c, d, a, b, x[i+ 6], 15, -1560198380);
b = md5_ii(b, c, d, a, x[i+13], 21, 1309151649);
a = md5_ii(a, b, c, d, x[i+ 4], 6 , -145523070);
d = md5_ii(d, a, b, c, x[i+11], 10, -1120210379);
c = md5_ii(c, d, a, b, x[i+ 2], 15, 718787259);
b = md5_ii(b, c, d, a, x[i+ 9], 21, -343485551);
a = safe_add(a, olda);
b = safe_add(b, oldb);
c = safe_add(c, oldc);
d = safe_add(d, oldd);
}
var binarray = Array(a, b, c, d);
var hex_tab = hexcase ? " 0123456789 ABCDEF " : " 0123456789 abcdef " ;
var str = " " ;
for(var i = 0; i < binarray.length * 4; i++)
{
str += hex_tab.charAt((binarray[i>>2] >> ((i%4)*8+4)) & 0xF) + hex_tab.charAt((binarray[i>>2] >> ((i%4)*8 )) & 0xF);
}
return str;
/*
* Add integers, wrapping at 2^32. This uses 16-bit operations internally
* to work around bugs in some JS interpreters.
*/
function safe_add(x, y)
{
var lsw = (x & 0xFFFF) + (y & 0xFFFF);
var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
return (msw << 16) | (lsw & 0xFFFF);
}
/*
* Bitwise rotate a 32-bit number to the left.
*/
function bit_rol(num, cnt)
{
return (num << cnt) | (num >>> (32 - cnt));
}
/*
* These functions implement the four basic operations the algorithm uses.
*/
function md5_cmn(q, a, b, x, s, t)
{
return safe_add(bit_rol(safe_add(safe_add(a, q), safe_add(x, t)), s),b);
}
function md5_ff(a, b, c, d, x, s, t)
{
return md5_cmn((b & c) | ((~b) & d), a, b, x, s, t);
}
function md5_gg(a, b, c, d, x, s, t)
{
return md5_cmn((b & d) | (c & (~d)), a, b, x, s, t);
}
function md5_hh(a, b, c, d, x, s, t)
{
return md5_cmn(b ^ c ^ d, a, b, x, s, t);
}
function md5_ii(a, b, c, d, x, s, t)
{
return md5_cmn(c ^ (b | (~d)), a, b, x, s, t);
}
}
};
/**
* While the main purpose of the library is communication functions, it was necessary to add in some utility methods.
* The AjaxTCR.util holds these methods.
*
* @class AjaxTCR.util
* @static
*/
AjaxTCR.util = {};
/**
* Several useful utility DOM functions. Many of these are called from other parts of the library.
*
* @class AjaxTCR.util.DOM
* @static
*/
AjaxTCR.util.DOM = {
/** by default enable shorthanding of function names */
enableDOMShorthand : true,
/**
* Find elements by class, will be overriden by native if found
* If startNode is specified, starts the search there, otherwise starts at document.
*
* @param {string} classToFind the string class name to search for
* @param {object} startNode the DOM node to start the search at. Default is the document node.
* @return {array} array of elements that match the given class name.
*/
getElementsByClassName : function(classToFind,startNode){
if (document.getElementsByClassName)
return document.getElementsByClassName(classToFind,startNode);
/* find all the elements within a particular document or in the whole document */
var elements;
if (startNode)
elements = startNode.getElementsByTagName( " * " );
else
elements = document.getElementsByTagName( " * " );
var classElements = new Array();
var classCount = 0;
var pattern = new RegExp( " ( ^|\\ s ) " +classToFind+ " ( \\ s |$ ) " );
/* look over the elements and find those who match the class passed */
for (var i = 0; i < elements.length; i++)
if (pattern.test(elements[i].className) )
classElements[classCount++] = elements[i];
return classElements;
},
/**
* Returns element or element array specified by given string or strings.
*
* @param {object} element(s) strings to search for element.
* @param {object} startNode the DOM node to start the search at. Default is the document node.
* @return {object} if single string, it returns the element. Otherwise it returns an array of elements
*/
getElementsById : function(){
var elements = new Array();
var startNode = document;
var length = arguments.length;
if (typeof(arguments[length-1]) == " object " && arguments[length-1] != document)
{
startNode = arguments[length-1];
length--;
var allElements = startNode.getElementsByTagName( " * " );
for (var j=0; j<allElements.length; j++)
{
for (var i=0;i<length;i++)
{
if (allElements[j].id == arguments[i])
{
elements.push(allElements[j]);
break;
}
}
}
}
else
{
if (arguments[length-1] == document)
length--;
for (var i=0; i<length; i++)
{
var elm = document.getElementById(arguments[i]);
if (elm != null)
elements.push(elm);
}
}
if (elements.length == 1)
return elements[0];
else if (elements.length > 0)
return elements;
else
return null;
},
/**
* Modified version of getElementById to return single node match.
* If startNode is not set to document, it starts the search at the node
* If deepSearch is set to true, it does not use getElementById, but instead loops through the whole structure.
*
* @param {string} id the string to match with the id attribute
* @param {object} startNode the DOM node to start searching in the document
* @param {boolean} deepSearch true if wanted to search node by node instead of document.getElementById
*/
getElementById : function(id, startNode, deepSearch){
if (!startNode)
startNode = document;
if (startNode == document && !deepSearch)
return document.getElementById(id);
else
{
var allElements = startNode.getElementsByTagName( " * " );
for (var j=0; j<allElements.length; j++)
{
if (allElements[j].getAttribute( " id " ) == id)
{
return allElements[j];
break;
}
}
}
},
/**
* Select nodes that match the given selector. The selector is expected to be in CSS format
*
* @param {string} selector string indicating the selection to match
* @param {object} treeRoot DOM element to start search. Default is the document node
* @return array of matching elements
*
*/
getElementsBySelector : function(selector,treeRoot,selectorType){
var matches = new Array();
var parents = new Array();
var savematches = new Array();
if (treeRoot)
{
if (treeRoot.length)
{
for (var i=0;i<treeRoot.length;i++)
parents.push(treeRoot[i]);
}
else
parents.push(treeRoot);
}
else
parents.push(document);
if (!selectorType)
selectorType = " CSS " ;
if (selectorType.toUpperCase() == " CSS " )
{
selector = selector.replace(/([>\+,])/g, " $ 1 " ).replace(/[\s]+/g, " " );
var selectors = selector.split( " " );
while (selectors.length > 0)
{
var curSelector = selectors.shift();
if (curSelector == " " )
continue;
/* check for expressions */
var options = {};
switch(curSelector.charAt(0))
{
case( " > " ):
options.type = " childOnly " ;
break;
case( " + " ):
options.type = " nextSibling " ;
break;
case ( " ~ " ):
options.type = " futureSibling " ;
break;
case( " , " ):
while(matches.length > 0)
savematches.push(matches.shift());
parents.length = 0;
if (treeRoot)
parents.push(treeRoot);
else
parents.push(document);
continue;
break;
}
if (options.type)
{
if (curSelector.length == 1)
curSelector = selectors.shift();
else
curSelector = curSelector.substring(1);
}
/* Check to see if we already looped though. If so, we have a different starting point */
if (matches.length)
{
parents.length = 0;
while(matches.length > 0)
parents.push(matches.shift());
}
/* Check for Pseudo-classes */
if (curSelector.indexOf( " : " ) > -1)
{
var newSelector = curSelector.substring(0, curSelector.indexOf( " : " ));
var optionsType = curSelector.substring(curSelector.indexOf( " : " )+1);
curSelector = newSelector;
options.type = optionsType.toLowerCase();
if (options.type.indexOf( " nth - child " ) == 0)
{
options.childNumber = options.type.substring(10,options.type.length-1);
options.type = " nth - child " ;
}
else if (options.type.indexOf( " not " ) == 0)
{
//use optionsType to preserve case
options.notString = optionsType.substring(4,options.type.length-1).replace(/^\s+|\s+$/g, " " );
options.type = " not " ;
var notSelector = curSelector;
if (notSelector == " * " )
notSelector = " " ;
if (/^[:#\[\.].*/.test(options.notString))
options.notSelector = notSelector + options.notString;
else
options.notSelector = notSelector + " " + options.notString;
options.notObjects = AjaxTCR.util.DOM.getElementsBySelector(options.notSelector, parents);
}
}
/* Check for Attributes */
if (curSelector.indexOf( " [ " ) > -1)
{
var tokens = curSelector.split( " [ " );
curSelector = tokens[0];
options.type = " attribute " ;
options.attribute = tokens[1].substring(0,tokens[1].length-1).toLowerCase();
}
if (curSelector == " " )
curSelector = " * " ;
/* Inspect class selectors */
if (curSelector.indexOf( " . " ) > -1)
{
/* Cases:
* p.class1
* .class2
* div.class1.class2
*/
var classNames = curSelector.split( " . " );
var elementName = classNames.shift();
/* First get the element at the beginning if necessary */
if (elementName != " " )
{
for (var j=0;j<parents.length;j++)
{
var elms = AjaxTCR.util.DOM._getElementsByTagName(parents[j],elementName,options);
for (var k=0;k<elms.length;k++)
{
if (checkFilter(elms[k], parents[j], options))
matches.push(elms[k]);
}
}
}
else if (classNames.length > 0)
{
/* if no element is specified, use getElementsByClassName for the first class */
var firstClass = classNames.shift();
for (var j=0;j<parents.length;j++)
{
var elms = AjaxTCR.util.DOM.getElementsByClassName(firstClass, parents[j]);
for (var k=0;k<elms.length;k++)
{
if (checkFilter(elms[k],parents[j],options))
matches.push(elms[k]);
}
}
}
/* Now get the (rest of the) classes */
for (var j=matches.length-1;j>=0;j--)
{
for (var k=0;k<classNames.length;k++)
{
var pattern = new RegExp( " ( ^|\\ s ) " +classNames[k]+ " ( \\ s |$ ) " );
if (!pattern.test(matches[j].className))
{
matches.splice(j,1);
break;
}
}
}
}
/* Inspect id selectors */
else if (curSelector.indexOf( " # " ) > -1)
{
/* Cases:
* p#id1
* #id2
*/
var idNames = curSelector.split( " # " );
var elementName = idNames[0];
var id = idNames[1];
/* First get the element at the beginning if necessary */
if (elementName != " " )
{
for (var j=0;j<parents.length;j++)
{
var elms = AjaxTCR.util.DOM._getElementsByTagName(parents[j],elementName,options);
for (var k=0;k<elms.length;k++)
{
if (elms[k].id == id && checkFilter(elms[k], parents[j], options))
matches.push(elms[k]);
}
}
}
else
{
for (var j=0;j<parents.length;j++)
{
var elms = AjaxTCR.util.DOM.getElementsById(id, parents[j]);
if (checkFilter(elms, parents[j], options))
matches.push(elms);
}
}
}
/* Simple tagname selects */
else
{
for (var j=0;j<parents.length;j++)
{
var elms =AjaxTCR.util.DOM._getElementsByTagName(parents[j],curSelector,options);
for (var k=0;k<elms.length;k++)
{
if (checkFilter(elms[k], parents[j], options))
matches.push(elms[k]);
}
}
}
}
}
function checkFilter(element, parent, options)
{
var valid = false;
if (element == null)
return false;
else if (!options.type)
return true;
//handle the case of the parent element being the document
if (parent == document)
{
var allElms = document.getElementsByTagName( " * " );
for (var i=0;i<allElms.length;i++)
{
if( checkFilter(element, allElms[i], options))
{
valid = true;
break;
}
}
return valid;
}
if (options.type == " childOnly " )
valid = (element.parentNode == parent);
else if (options.type == " nextSibling " )
{
var elm = parent.nextSibling;
while (elm != null && elm.nodeType != 1)
elm = elm.nextSibling;
valid = (elm == element);
}
else if (options.type == " futureSibling " )
{
var elm = parent.nextSibling;
while (elm != null)
{
if (elm == element)
{
valid = true;
break;
}
elm = elm.nextSibling;
}
}
else if (options.type == " first - child " )
{
var elm = parent.firstChild;
while (elm != null && elm.nodeType != 1)
elm = elm.nextSibling;
valid = (elm == element);
}
else if (options.type == " last - child " )
{
var elm = parent.lastChild;
while (elm != null && elm.nodeType != 1)
elm = elm.previousSibling;
valid = (elm == element);
}
else if (options.type == " only - child " )
{
var elm = parent.firstChild;
while (elm != null && elm.nodeType != 1)
elm = elm.nextSibling;
if (elm == element)
{
var elm = parent.lastChild;
while (elm != null && elm.nodeType != 1)
elm = elm.previousSibling;
}
valid = (elm == element);
}
else if (options.type == " nth - child " )
{
var count = 0;
var elm = parent.firstChild;
while (elm != null && count < options.childNumber)
{
if (elm.nodeType == 1)
count++;
if (count == options.childNumber)
break;
elm = elm.nextSibling;
}
valid = (elm == element);
}
else if (options.type == " empty " )
valid = (element.childNodes.length == 0);
else if (options.type == " enabled " )
valid = (!element.disabled);
else if (options.type == " disabled " )
valid = (element.disabled);
else if (options.type == " checked " )
valid = (element.checked);
else if (options.type == " selected " )
valid = (element.selected);
else if (options.type == " attribute " )
{
var pattern = /^\s*([\w-]+)\s*([!*$^~=]*)\s*(['| \" ]?)(.*)\3/;
var attRules = pattern.exec(options.attribute);
if (attRules[2] == " " )
valid = element.getAttribute(attRules[1]);
else if (attRules[2] == " = " )
valid = (element.getAttribute(attRules[1]) && element.getAttribute(attRules[1]).toLowerCase() == attRules[4].toLowerCase());
else if (attRules[2] == " ^= " )
valid = (element.getAttribute(attRules[1]) && element.getAttribute(attRules[1]).toLowerCase().indexOf(attRules[4].toLowerCase()) == 0);
else if (attRules[2] == " *= " )
valid = (element.getAttribute(attRules[1]) && element.getAttribute(attRules[1]).toLowerCase().indexOf(attRules[4].toLowerCase()) > -1);
else if (attRules[2] == " $= " )
{
var att =element.getAttribute(attRules[1]);
if (att)
valid = (att.toLowerCase().substring(att.length - attRules[4].length) == attRules[4].toLowerCase());
}
}
else if (options.type == " not " )
{
valid = true;
for (var j=0;j<options.notObjects.length;j++)
{
if (options.notObjects[j] == element)
{
valid = false;
break;
}
}
}
return valid;
}
/* get the results in the correct order */
if (savematches.length)
{