Add in change password
[matches/MCTX3420.git] / testing / MCTXWeb / public_html / static / mctx.gui.js
1 /**
2 * MCTX3420 2013 GUI stuff.
3 * Coding style:
4 *  - Always end statements with semicolons
5 *  - Egyptian brackets are highly recommended (*cough*).
6 *  - Don't use synchronous stuff - hook events into callbacks
7 *  - $.fn functions should return either themselves or some useful object
8 *    to allow for chaining of method calls
9 */
10
11 mctx = {};
12 //Don't use this in the final version
13 mctx.location = window.location.pathname;
14 mctx.location = mctx.location.substring(0, mctx.location.lastIndexOf('/')) + "/";
15 //mctx.location = location.protocol + "//" + location.host + "/";
16 mctx.api = location.protocol + "//" + location.host + "/" + "api/";
17 mctx.expected_api_version = 0;
18 mctx.has_control = false;
19 mctx.debug = true;
20
21 mctx.menu = [
22     {'text' : 'Home', href : mctx.location + 'index.html'},
23     {'text' : 'Experiment control', href : mctx.location + 'control.html'},
24     {'text' : 'Pin debugging', href : mctx.location + 'pintest.html'},
25     {'text' : 'Help', href : mctx.location + 'help.html'}
26 ];
27
28 mctx.status = {
29     OK : 1,
30     ERROR : -1,
31     UNAUTHORIZED : -2,
32     NOTRUNNING : -3,
33     ALREADYEXISTS : -4
34 };
35
36 mctx.statusCodesDescription = {
37     "1" : "Ok",
38     "-1" : "General error",
39     "-2" : "Unauthorized",
40     "-3" : "Not running",
41     "-4" : "Already exists"
42 };
43
44 mctx.sensors = {
45     0 : {name : "Strain gauge 1"},
46     1 : {name : "Strain gauge 2"},
47     2 : {name : "Strain gauge 3"},
48     3 : {name : "Strain gauge 4"},
49     4 : {name : "Pressure sensor 1"},
50     5 : {name : "Pressure sensor 2"},
51     6 : {name : "Pressure sensor 3"}
52 };
53
54 mctx.actuators = {
55     0 : {name : "Solenoid 1"},
56     1 : {name : "Solenoid 2"},
57     2 : {name : "Solenoid 3"},
58     3 : {name : "Pressure regulator"}
59 };
60
61 mctx.actuator = {};
62 mctx.actuator.pressure_regulator = 0;
63
64 mctx.strain_gauges = {};
65 mctx.strain_gauges.ids = [0, 1, 2, 3];
66 mctx.strain_gauges.time_limit = 20;
67
68 /**
69 * Logs a message if mctx.debug is enabled. This function takes
70 * a variable number of arguments and passes them 
71 * to alert or console.log (based on browser support).
72 * @returns {undefined}
73 */
74 function debugLog () {
75     if (mctx.debug) {
76         if (typeof console === "undefined" || typeof console.log === "undefined") {
77             for (var i = 0; i < arguments.length; i++) {
78                 alert(arguments[i]);
79             }
80         } else {
81             try {
82               console.log.apply(this, arguments);
83             } catch (e) {
84               //Chromie
85               for (var i = 0; i < arguments.length; i++) {
86                 console.log(arguments[i]);
87               }
88             }
89         }
90     }
91 }
92
93 /**
94 * Writes the current date to wherever it's called.
95 */
96 function getDate() {
97     document.write((new Date()).toDateString());
98 }
99
100 /**
101 * Should be run before the load of any GUI page.
102 * To hook events to be called after this function runs,
103 * use the 'always' method, e.g runBeforeLoad().always(function() {my stuff});
104 * @param {type} isLoginPage
105 * @returns The return value of calling $.ajax
106 */
107 function runBeforeLoad(isLoginPage) {
108     return $.ajax({
109         url : mctx.api + "identify"
110     }).done(function (data) {
111         if (data.logged_in && isLoginPage) {
112             if (mctx.debug) {
113                 debugLog("Redirect disabled!");
114             } else {
115                 window.location = mctx.location;
116             }
117         } else if (!data.logged_in && !isLoginPage) {
118             if (mctx.debug) {
119                 debugLog("Redirect disabled!");
120             } else {
121                 //Note: this only clears the nameless cookie
122                 document.cookie = ""; 
123                 window.location = mctx.location + "login.html";
124             }
125         } else {
126             mctx.friendlyName = data.user_name;
127         }
128         
129         $(document).ready(function () {
130           //Show the content!
131           $("#content").css("display", "block");
132           
133           //Set the welcome bar
134           var name = " " + (mctx.friendlyName ? mctx.friendlyName : "");
135           $("#welcome-container").text("Welcome"+ name + "!");
136           $("#logout-container").css("display", "block");
137           //$("#menu-container").populateNavbar();
138
139           $("#logout").click(function () {
140             $("#logout").logout();
141           });\r
142           \r
143           $("#change-password").click(function () {\r
144             window.open("users/user_change_details.php");\r
145           });
146           
147           //Enable the error log, if present
148           $("#errorlog").setErrorLog();
149         });
150     }).fail(function (jqHXR) {
151         if (mctx.debug) {
152             debugLog("Failed to ident server. Is API running?")
153         } else if (!isLoginPage) {
154             window.location = mctx.location + "login.html";
155         }
156     }).always(function () {
157         
158     });
159 }
160
161 /**
162  * Populates the navigation menu.
163  */
164 $.fn.populateNavMenu = function() {
165     var root = $("<ul/>")
166     for (var i = 0; i < mctx.menu.length; i++) {
167         var item = mctx.menu[i];
168         var entry = $("<li/>").append(
169             $("<a/>", {text : item.text, href: item.href})
170         );
171         root.append(entry);
172     }
173     $(this).append(root);
174     return this;
175 }
176
177 /**
178 * Performs a login attempt.
179 * @returns The AJAX object of the login request */
180 $.fn.login = function () {
181     var username = this.find("input[name='username']").val();
182     var password = this.find("input[name='pass']").val();
183     var out = this.find("#result");
184     var redirect = function () {
185         window.location.href = mctx.location;
186     };
187
188     out.removeAttr("class");
189     out.text("Logging in...");
190
191     return $.ajax({
192         url : mctx.api + "bind",
193         type : "POST",
194         data : {user: username, pass : password}
195     }).done(function (data) {
196         if (data.status < 0) {
197             mctx.has_control = false;
198             out.attr("class", "fail");
199             out.text("Login failed: " + data.description);
200         } else {
201             //todo: error check
202             mctx.has_control = true;
203             out.attr("class", "pass");
204             out.text("Login ok!");
205             setTimeout(redirect, 800);      
206         }
207     }).fail(function (jqXHR) {
208         mctx.has_control = false;
209         out.attr("class", "fail");
210         out.text("Login request failed - connection issues.")
211     });
212 };
213
214 /**
215 * Performs a logout request. The nameless cookie is
216 * always cleared and the browser redirected to the login page,
217 * independent of whether or not logout succeeded.
218 * @returns  The AJAX object of the logout request.
219 */
220 $.fn.logout = function () {
221     return $.ajax({
222         url : mctx.api + "unbind"
223     }).always(function () {
224         //Note: this only clears the nameless cookie
225         document.cookie = ""; 
226         window.location = mctx.location + "login.html";
227     });
228 };
229
230 /**
231 * Sets the error log to continuously update.
232 * @returns itself */
233 $.fn.setErrorLog = function () {
234     var url = mctx.api + "errorlog";
235     var outdiv = this;
236
237     if ($(this).length <= 0) {
238       //No error log, so do nothing.
239       return;
240     }
241
242     var updater = function () {
243         $.ajax({url : url}).done(function (data) {
244             outdiv.text(data);
245             outdiv.scrollTop(
246               outdiv[0].scrollHeight - outdiv.height()
247             );
248             setTimeout(updater, 3000);
249         }).fail(function (jqXHR) {
250             if (jqXHR.status === 502 || jqXHR.status === 0) {
251                 outdiv.text("Failed to retrieve the error log.");
252             }
253             setTimeout(updater, 10000); //poll at slower rate
254         });
255     };
256
257     updater();
258     return this;
259 };
260
261 $.fn.checkStatus = function(data) {
262   if (data.status !== mctx.status.OK) {
263     $(this).text(data.description).removeClass("pass").addClass("fail");
264     return false;
265   }
266   $(this).removeClass("fail");
267   return true;
268 };
269
270 $(document).ready(function () {
271   //Enable the hide/show clicks
272   $("#sidebar-hide").click(function () {
273     $("#sidebar").hide();
274     $("#sidebar-show").show();
275     return this;
276   });
277
278   $("#sidebar-show").click(function () {
279     $("#sidebar-show").hide();
280     $("#sidebar").show();
281     return this;
282   });
283 });
284
285 $(document).ajaxError(function (event, jqXHR) {
286     //console.log("AJAX query failed with: " + jqXHR.status + " (" + jqXHR.statusText + ")");
287 });

UCC git Repository :: git.ucc.asn.au