Adds error listener to alert user. Formats code.
[mkjsf-moved-to-github.git] / src / META-INF / resources / pz2utils / listeners.js
1 var renderTargetsReqVar;\r
2 var renderOnRecordTargetsReqVar;\r
3 \r
4 // Renders UI elements listed in 'renderWhileActiveclients', optionally doing\r
5 // another update round-trip to Pazpar2 when done.\r
6 function renderTargets(doRefresh) {\r
7   // console.log('rendering ' + renderWhileActiveclients);\r
8   var sourcecomp = document.getElementById("pz2watch:activeclientsField");\r
9   jsf.ajax.request(sourcecomp, null, {\r
10     render : renderWhileActiveclients\r
11   });\r
12   if (doRefresh) {\r
13     // console.log('Will do another ajax request after a timeout in order to\r
14     // render: pz2watch:activeclientsField');\r
15     renderTargetsReqVar = setTimeout(function() {\r
16       // console.log('Making request for pz2watch:activeclientsField');\r
17       jsf.ajax.request(sourcecomp, null, {\r
18         render : "pz2watch:activeclientsField"\r
19       });\r
20     }, 500);\r
21   } else {\r
22     // console.log("No further updates from server requested");\r
23   }\r
24 }\r
25 \r
26 // Renders UI elements listed in 'renderWhileActiveclientsRecord', optionally\r
27 // doing\r
28 // another record request when done.\r
29 function renderOnRecordTargets(doRefresh) {\r
30   // console.log('rendering ' + renderWhileActiveclientsRecord);\r
31   var sourcecomp = document.getElementById("pz2watch:activeclientsFieldRecord");\r
32   jsf.ajax.request(sourcecomp, null, {\r
33     render : renderWhileActiveclientsRecord\r
34   });\r
35   if (doRefresh) {\r
36     // console.log('Will do another ajax request after a timeout in order to\r
37     // render: pz2watch:activeclientsFieldRecord');\r
38     renderOnRecordTargetsReqVar = setTimeout(function() {\r
39       // console.log('Making request for pz2watch:activeclientsFieldRecord');\r
40       jsf.ajax.request(sourcecomp, null, {\r
41         render : "pz2watch:activeclientsFieldRecord"\r
42       });\r
43     }, 1000);\r
44   } else {\r
45     // console.log("No further updates from server requested");\r
46   }\r
47 }\r
48 \r
49 // Listens for browser initiated changes to 'window.location.hash' and sends the\r
50 // hash\r
51 // changes to the back-end (to have the back-end pull up a previous Pazpar2\r
52 // state)\r
53 function windowlocationhashListener() {\r
54   if (trackHistory) {\r
55     // console.log("browser hash update detected");\r
56     var stateKey = document.getElementById("pz2watch:windowlocationhash");\r
57     if (window.location.hash != stateKey.value) {\r
58       // console.log("updating stateKey with new browser hash: " +\r
59       // window.location.hash);\r
60       stateKey.value = window.location.hash;\r
61       if (!stateKey.value)\r
62         window.location.hash = '#1';\r
63       stateKey.onchange();\r
64     } else {\r
65       // console.log("State hash already has the value of the new browser hash -\r
66       // not updating state hash");\r
67     }\r
68   }\r
69 }\r
70 \r
71 // Listens for ViewExpiredException message. Reloads the current page, stripped\r
72 // of\r
73 // it's jsessionid and hash content\r
74 function viewExpirationListener(data) {\r
75   if (data.status === "success" && data.responseXML) {\r
76     var errorElements = data.responseXML.getElementsByTagName("error-name");\r
77     if (errorElements.length > 0) {\r
78       var errorname = errorElements.item(0).textContent\r
79           || errorElements.item(0).text;\r
80       if (errorname === "class javax.faces.application.ViewExpiredException") {\r
81         var newloc = window.location.protocol + "//" + window.location.host\r
82             + window.location.pathname.replace(/;jsessionid.*/, '');\r
83         alert('Sorry, this session has expired. A new one will be loaded.');\r
84         window.location.replace(newloc);\r
85       }\r
86     }\r
87   }\r
88 \r
89 }\r
90 \r
91 function errorListener(data) {\r
92   // alert(data.toSource());\r
93   if (data.source.name === "pz2watch:activeclientsField") {\r
94     alert("This occurred when polling: ["\r
95         + data.description\r
96         + "]. The page could be in an inconsistent state after this. We apologize for the inconvenience.");\r
97   } else {\r
98     var pattern = /viewId.*could not be restored./;\r
99     if (pattern.test(data.description)) {\r
100       // ignore - caught by view expiration listener\r
101     } else {\r
102       alert("An error ["\r
103           + data.description\r
104           + "] was triggered by ["\r
105           + data.source.name\r
106           + "]. The page could be in an inconsistent state after this. We apologize for the inconvenience.");\r
107     }\r
108   }\r
109 }\r
110 \r
111 // Composite listener, invoking all field update listeners\r
112 function fieldUpdateListener(data) {\r
113   if (data.status === "success") {\r
114     var updates = data.responseXML.getElementsByTagName("update");\r
115     for ( var i = 0, max = updates.length; i < max; i++) {\r
116       var lsnri = fieldListeners.getListener(updates[i].getAttribute("id"));\r
117       if (lsnri) {\r
118         lsnri.invoke(updates[i]);\r
119       }\r
120     }\r
121   }\r
122 }\r
123 \r
124 var Pz2listeners = function() {\r
125   var lsnrs = {};\r
126   this.addListener = function(key, lsnr) {\r
127     lsnrs[key] = lsnr;\r
128   };\r
129   this.getListener = function(key) {\r
130     return lsnrs[key];\r
131   };\r
132 };\r
133 \r
134 var fieldListeners = new Pz2listeners();\r
135 \r
136 // Listens for back-end initiated changes to the state key and updates\r
137 // window.location.hash with changes, to record them in browsing history\r
138 var StateListener = function() {\r
139   this.invoke = function(field) {\r
140     var stateKeyDoc = StringtoXML(field.textContent || field.text);\r
141     var stateKeyValue = stateKeyDoc.childNodes[0].getAttribute("value");\r
142     // console.log('Application hash update detected. New value: ' +\r
143     // stateKeyValue);\r
144     if (stateKeyValue !== window.location.hash) {\r
145       window.location.hash = stateKeyValue;\r
146       // console.log("Browsers hash updated accordingly.");\r
147     } else {\r
148       // console.log("Browsers hash already has the value of the state hash. Not\r
149       // updating browser hash.");\r
150     }\r
151   };\r
152 };\r
153 \r
154 // Listens for updates to general 'activeclients' field, then invokes\r
155 // renderTargets\r
156 var ActiveclientsListener = function() {\r
157   this.invoke = function(field) {\r
158     var updateDoc = StringtoXML(field.textContent || field.text);\r
159     var activeClientsValue = (updateDoc.childNodes[0].textContent || updateDoc.childNodes[0].text);\r
160     // console.log('Activeclients response detected: ' + activeClientsValue);\r
161     clearTimeout(renderTargetsReqVar);\r
162     if (activeClientsValue > '0') {\r
163       renderTargets(true);\r
164     } else {\r
165       renderTargets(false);\r
166     }\r
167   };\r
168 };\r
169 \r
170 // Listens for updates to record 'activeclients' field, then invokes\r
171 // renderOnRecordTargets\r
172 var ActiveclientsRecordListener = function() {\r
173   this.invoke = function(field) {\r
174     var updateDoc = StringtoXML(field.textContent || field.text);\r
175     var activeClientsRecordValue = (updateDoc.childNodes[0].textContent || updateDoc.childNodes[0].text);\r
176     console.log('Activeclients response for record detected: '\r
177         + activeClientsRecordValue);\r
178     clearTimeout(renderOnRecordTargetsReqVar);\r
179     if (activeClientsRecordValue > '0') {\r
180       renderOnRecordTargets(true);\r
181     } else {\r
182       console.log('Active clients is 0, final rendering');\r
183       renderOnRecordTargets(false);\r
184     }\r
185   };\r
186 };\r
187 \r
188 // Inserts field update listeners, state listeners, view expired listener\r
189 // into Ajax response handling\r
190 jsf.ajax.addOnEvent(fieldUpdateListener);\r
191 jsf.ajax.addOnEvent(viewExpirationListener);\r
192 jsf.ajax.addOnError(errorListener);\r
193 \r
194 function StringtoXML(text) {\r
195   var doc;\r
196   if (window.ActiveXObject) {\r
197     doc = new ActiveXObject('Microsoft.XMLDOM');\r
198     doc.async = false;\r
199     doc.loadXML(text);\r
200   } else {\r
201     var parser = new DOMParser();\r
202     doc = parser.parseFromString(text, 'text/xml');\r
203   }\r
204   return doc;\r
205 }\r
206 \r
207 // Sets up field update listeners\r
208 var setUpListeners = function() {\r
209   // console.log("Starts tracking activeclientsField, for 'show' and 'record'");\r
210   fieldListeners.addListener("pz2watch:activeclientsField",\r
211       new ActiveclientsListener());\r
212   fieldListeners.addListener("pz2watch:activeclientsFieldRecord",\r
213       new ActiveclientsRecordListener());\r
214   if (trackHistory) {\r
215     // console.log("Starts tracking windowlocationhash field");\r
216     fieldListeners.addListener("pz2watch:windowlocationhash",\r
217         new StateListener());\r
218     // console.log("Setting listener for browser onhashchange");\r
219     window.onload = window.onhashchange = windowlocationhashListener;\r
220   }\r
221 };