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