Removed dep on API
[ninja.git] / application / views / js / common.js
bloba1f932cc71e2765d8f80ca1e9e926180416b06c8
1 var sURL = window.location.pathname + location.search;
2 var _interval = 0;
3 var _save_page_interval = 0;
4 var current_interval = 0;
5 var edit_visible = 0;
6 var _save_scroll = true;
8 $(document).ready(function() {
10         var content_div = $( "body > .container > #content" ),
11                 header_div = $( "body > .container >#header" ),
12                 body = $( "body" );
14         function fit_content () {
15                 var height = body.height() - header_div.outerHeight();
16                 content_div.css( "height", height + "px" );
17         }
19         $(window).bind( "resize", fit_content );
20         fit_content();
22         // make scroll memory cookie to be reset
23         // when actively clicking on a link.
24         $('body').on('click', 'a', function() {
25                 _save_scroll = false;
26         });
28         if ( content_div ) {
29                 content_div.click();
30                 content_div.focus();
31         }
33         // stop widgets from trying to reload once user clicked
34         // on a menu
35         $('#menu a').click(function() {_is_refreshing = true;});
37         if ($.fn.contextMenu) {
38                 $("body").contextMenu({
39                                 menu: 'property_menu', use_prop:true
40                         },
41                         function(action, elem){
42                                 object_action(action, elem.attr('id'));
43                         }, ".obj_properties:not(.white)");
45                 $("body").contextMenu({
46                                 menu: 'svc_property_menu', use_prop:true
47                         },
48                         function(action, elem){
49                                 object_action(action, elem.attr('id'));
50                         },".svc_obj_properties");
51         }
53         // refresh helper code
54         var old_refresh = 0;
55         var refresh_is_paused = false;
56         $("#ninja_refresh_control").bind('change', function() {
57                 if ($("#ninja_refresh_control").attr('checked')) {
58                         // save previous refresh rate
59                         // to be able to restore it later
60                         old_refresh = current_interval;
61                         $('#ninja_refresh_lable').css('font-weight', 'bold');
62                         ninja_refresh(0);
63                         refresh_is_paused = true;
64                 } else {
65                         // restore previous refresh rate
66                         ninja_refresh(old_refresh);
67                         refresh_is_paused = false;
68                         $('#ninja_refresh_lable').css('font-weight', '');
69                 }
70         });
71         if ($('#ninja_refresh_edit').text()!=='') {
72                 create_slider('ninja_page_refresh');
73                 $('#ninja_page_refresh_slider').on('slidechange', function() {
74                         var delay = parseInt($('#ninja_page_refresh_value').val(), 10);
75                         $.jGrowl(sprintf(_page_refresh_msg, delay), { header: _success_header });
76                         ninja_refresh(delay);
77                 });
78         }
79         $('#ninja_refresh_edit').bind('click', function() {
80                 if (!edit_visible) {
81                         $('#ninja_page_refresh_slider').show();
82                         edit_visible = 1;
83                 } else {
84                         $('#ninja_page_refresh_slider').hide();
85                         edit_visible = 0;
86                 }
87         });
88         // -- end refresh helper code
90         // listview refresh helper code
91         $("#listview_refresh_control").bind('change', function() {
92                 if ($("#listview_refresh_control").attr('checked')) {
93                         // save previous refresh rate
94                         // to be able to restore it later
95                         $('#listview_refresh_lable').css('font-weight', 'bold');
96                         clearTimeout(lsfilter_storage.list.autorefresh_timer);
97                         $.jGrowl(_listview_refresh_paused_msg, { header: _success_header });
98                 } else {
99                         // restore previous refresh rate
100                         $('#listview_refresh_lable').css('font-weight', '');
101                         lsfilter_storage.list.start_autorefresh_timer();
102                         $.jGrowl(_listview_refresh_unpaused_msg, { header: _success_header });
103                 }
104         });
105         $("#listview_refresh_value").bind('change', function() {
106                 $("#listview_refresh_slider").slider("value", this.value);
107         });
108         if ($('#listview_refresh_edit').text()!=='') {
109                 create_slider('listview_refresh');
110                 $('#listview_refresh_slider').on('slidechange', function() {
111                         var delay = parseInt($('#listview_refresh_value').val(), 10);
112                         $.jGrowl(sprintf(_listview_refresh_msg, delay), { header: _success_header });
113                         clearTimeout(lsfilter_storage.list.autorefresh_timer);
114                         if (delay > 0) {
115                                 lsfilter_storage.list.config.autorefresh_enabled = true;
116                         } else {
117                                 lsfilter_storage.list.config.autorefresh_enabled = false;
118                         }
119                         lsfilter_storage.list.config.autorefresh_delay = delay * 1000;
120                         lsfilter_storage.list.start_autorefresh_timer();
121                 });
122         }
123         // -- end listview refresh helper code
125         $('.host_comment').each(function() {
126                 var anchor = $(this);
127                 var obj_name = anchor.data('obj_name');
128                 if (!obj_name) {
129                         return false;
130                 }
133                 // Remove the tooltip of the inner element since it overlays qtip
134                 anchor.find('span').attr('title', '');
136                 anchor.qtip($.extend(true, {}, qtip_default, {
137                         content: {
138                                 text: function(ev, api) {
139                                         $.ajax({
140                                                 url: _site_domain + _index_page + "/ajax/fetch_comments/",
141                                                 data: {host: obj_name}
142                                         })
143                                         .done(function(html) {
144                                                 api.set('content.text', html);
145                                         })
146                                         .fail(function(xhr, status, error) {
147                                                 api.set('content.text', status + ': ' + error);
148                                         });
150                                         return '<img src="' + _site_domain + loading_img + '" alt="' + _loading_str + '" />';
151                                 }
152                         }
153                 }));
154         });
156         $(".helptext_target").each(function(){
157                 // split the id into controller, key
158                 var controller = $(this).data('helptext-controller');
159                 var key = $(this).data('helptext-key');
160                 bind_helptext($(this), controller, key);
161         });
162         $('body').on('click', ".helptext_target", function() {return false;});
164         $('#multi_action_select').bind('change', function() {
165                 multi_action_select($(this).find('option:selected').val());
166         });
168         $('.select_all_items_service').live('click', function() {
169                 if ($(this).attr('checked')) {
170                         $(this).parents('table').find(".item_select_service input[type='checkbox']").not('.select_all_items_service').each(function() {
171                                 if (!$(this).attr('disabled') && !$(this).is(':hidden')) {
172                                         $(this).attr('checked', true);
173                                 }
174                                 else if ($(this).is(':hidden')) {
175                                         $(this).attr('checked', false);
176                                 }
177                         });
178                 } else {
179                         $(this).parents('table').find(".item_select_service input[type='checkbox']").not('.select_all_items_service').each(function() {
180                                 $(this).attr('checked', false);
181                         });
182                 }
183         });
184         // Toggle visibility for quick menu items
185         $("#page_settings_icon, #global_notifications_icon").click(function() {
186                 var menu_item = $(this);
187                 var li = menu_item.parents('li');
188                 var submenu = $('#'+menu_item[0].id.replace(/_icon$/, ''));
189                 if (submenu.is(':hidden')) {
190                         li.addClass("selected");
191                         submenu
192                                 .show()
193                                 .css('top', '49px')
194                                 .css('left', (menu_item.offset().left - 10) + 'px');
196                 } else {
197                         li.removeClass("selected");
198                         submenu.hide();
199                 }
200                 return false;
201         });
203         // are we using keyboard commands or not
204         if (_keycommands_active) {
205                 if (typeof _keycommand_forward !== 'undefined' && _keycommand_forward !== '') {
206                         jQuery(document).bind('keydown', _keycommand_forward, function (evt){
207                                 if (typeof $('.nextpage').attr('href') != 'undefined') {
208                                         // reset scroll memory to start at top for next page
209                                         _save_scroll = false;
210                                         self.location.href=$('.nextpage').attr('href');
211                                 }
212                                 return false;
213                         });
214                 }
216                 if (typeof _keycommand_back !== 'undefined' && _keycommand_back !== '') {
217                         jQuery(document).bind('keydown', _keycommand_back, function (evt){
218                                 if (typeof $('.prevpage').attr('href') != 'undefined') {
219                                         // reset scroll memory to start at top for previous page
220                                         _save_scroll = false;
221                                         self.location.href=$('.prevpage').attr('href');
222                                 }
223                                 return false;
224                         });
225                 }
227                 if (typeof _keycommand_search !== 'undefined' && _keycommand_search !== '') {
228                         jQuery(document).bind('keydown', _keycommand_search, function (evt){$('#query').focus(); return false; });
229                 }
231                 if (typeof _keycommand_pause !== 'undefined' && _keycommand_pause !== '') {
232                         jQuery(document).bind('keydown', _keycommand_pause, function (evt){
233                                 toggle_refresh();
234                                 return false;
235                         });
236                 }
237         }
239         /**
240         *       Toggle page refresh and show a jGrowl message to user about state
241         */
242         function toggle_refresh()
243         {
244                 if ($("#ninja_refresh_control").attr('checked')) {
245                         // restore previous refresh rate
246                         ninja_refresh(old_refresh);
247                         refresh_is_paused = false;
248                         $('#ninja_refresh_lable').css('font-weight', '');
249                         $("#ninja_refresh_control").attr('checked', false);
251                         // inform user
252                         $.jGrowl(_refresh_unpaused_msg, { header: _success_header });
253                 } else {
254                         // Prevent message from showing up when no pause is available
255                         if ($("#ninja_page_refresh").html() === null) {
256                                 return false;
257                         }
259                         $("#ninja_refresh_control").attr('checked', true);
260                         // save previous refresh rate
261                         // to be able to restore it later
262                         old_refresh = current_interval;
263                         $('#ninja_refresh_lable').css('font-weight', 'bold');
264                         ninja_refresh(0);
265                         refresh_is_paused = true;
267                         // inform user
268                         $.jGrowl(_refresh_paused_msg, { header: _success_header });
269                 }
270         }
272         $('#multi_object_submit_service').click(function() {
273                 // check that we have any selected items
274                 if (!$('.item_select_service input[name=object_select\\[\\]]').is(':checked')) {
275                         show_message("multi_object_submit_progress_service", _nothing_selected_error);
276                         return false;
277                 }
279                 // Check if we actually set an action
280                 if ($('#multi_action_select_service').val() === "") {
281                         show_message("multi_object_submit_progress_service", _no_action_error);
282                         return false;
283                 }
285                 show_progress("multi_object_submit_progress_service", _wait_str);
286         });
288         $('#multi_object_submit').click(function() {
289                 // check that we have any selected items
290                 if (!$('.item_select input[name=object_select\\[\\]]').is(':checked')) {
291                         show_message("multi_object_submit_progress", _nothing_selected_error);
292                         return false;
293                 }
295                 // Check if we actually set an action
296                 if ($('#multi_action_select').val() === "") {
297                         show_message("multi_object_submit_progress", _no_action_error);
298                         return false;
299                 }
301                 show_progress("multi_object_submit_progress", _wait_str);
302         });
306 function _(text)
308         // console.log('To translate: '+ text);
309         return text;
312 var loadimg_sml = new Image(16,16);
313 loadimg_sml.src = _site_domain + 'application/media/images/loading_small.gif';
316 *       cache the progress indicator image to show faster...
318 var Image1 = new Image(16,16);
319 Image1.src = _site_domain + 'application/media/images/loading.gif';
322 *       Show a progress indicator to inform user that something
323 *       is happening...
325 function show_progress(the_id, info_str, size_str) {
326         switch (size_str) {
327                 case "small": case "tiny":
328                         size_str = loadimg_sml.src;
329                         break;
330                 case "large": case "big":
331                         size_str = Image1.src;
332                         break;
333                 default:
334                         size_str = loadimg_sml.src;
335                         break;
336         }
337         $("#" + the_id).html('<img id="progress_image_id" src="' + size_str + '"> <em>' + info_str +'</em>').show();
340 function show_message(the_id, info_str) {
341         $("#" + the_id).html('<em>' + info_str +'</em>').show();
344 function switch_image(html_id, src)
346         $('#' + html_id).attr('src', src);
349 function object_action(action,the_id)
351         var parts = the_id.split('|');
352         var type = false;
353         var name = false;
354         var service = false;
355         switch(parts.length) {
356                 case 0: case 1:
357                         return false;
358                 case 2: // host or groups
359                         name = parts[1];
360                         break;
361                 case 3: // service
362                         name = parts[1];
363                         service = parts[2];
364                         break;
365                 case 4: // service
366                         name = parts[1];
367                         service = parts[3];
368                         break;
369         }
371         type = parts[0];
373         var cmd = false;
374         switch(action) {
375                 case 'schedule_host_downtime':
376                 case 'schedule_svc_downtime':
377                 case 'del_host_downtime':
378                 case 'del_svc_downtime':
379                 case 'acknowledge_host_problem':
380                 case 'acknowledge_svc_problem':
381                 case 'disable_host_svc_notifications':
382                 case 'disable_host_check':
383                 case 'disable_svc_check':
384                 case 'enable_host_check':
385                 case 'enable_svc_check':
386                 case 'schedule_host_check':
387                 case 'schedule_host_svc_checks':
388                 case 'schedule_svc_check':
389                 case 'add_host_comment':
390                 case 'add_svc_comment':
391                         cmd = action.toUpperCase();
392                         break;
393                 case 'remove_acknowledgement':
394                         cmd = type == 'host' ? 'REMOVE_HOST_ACKNOWLEDGEMENT' : 'REMOVE_SVC_ACKNOWLEDGEMENT';
395                         break;
396                 case 'disable_notifications':
397                         cmd = type == 'host' ? 'DISABLE_HOST_NOTIFICATIONS' : 'DISABLE_SVC_NOTIFICATIONS';
398                         break;
399                 case 'enable_notifications':
400                         cmd = type == 'host' ? 'ENABLE_HOST_NOTIFICATIONS' : 'ENABLE_SVC_NOTIFICATIONS';
401                         break;
402         }
404         // return if we couldn't figure out what command to run
405         if (cmd === false) {
406                 return false;
407         }
409         var target = _site_domain + _index_page + '/command/submit?cmd_typ=' + cmd + '&host_name=' + name;
410         if (service !== false) {
411                 target += '&service=' + service;
412         }
413         self.location.href = target;
417 *       Handle multi select of different actions
419 function multi_action_select(action, type)
421         // start by enabling all checkboxes in case
422         // they have been previously disabled
423         var field = 'item_select';
424         var prop_field = 'obj_prop';
425         if (type == 'service') {
426                 $(".item_select_service input[type='checkbox']").attr('disabled', false);
427                 field = 'item_select_service';
428                 prop_field = 'obj_prop_service';
429         } else {
430                 $(".item_select input[type='checkbox']").attr('disabled', false);
431         }
433         if (action === '')
434                 return false;
436         var ACKNOWLEDGED = 1;
437         var NOTIFICATIONS_ENABLED = 2;
438         var CHECKS_ENABLED = 4;
439         var SCHEDULED_DT = 8;
441         $('.' + prop_field).each(function() {
442                 var that = $(this);
443                 var test = false;
444                 switch (action) {
445                         case 'ACKNOWLEDGE_HOST_PROBLEM':
446                         case 'ACKNOWLEDGE_SVC_PROBLEM':
447                                 test = that.text() & ACKNOWLEDGED || !(that.text() & 16);
448                                 break;
449                         case 'REMOVE_HOST_ACKNOWLEDGEMENT':
450                         case 'REMOVE_SVC_ACKNOWLEDGEMENT':
451                                 test = !(that.text() & ACKNOWLEDGED);
452                                 break;
453                         case 'DISABLE_HOST_NOTIFICATIONS':
454                         case 'DISABLE_SVC_NOTIFICATIONS':
455                                 test = that.text() & NOTIFICATIONS_ENABLED;
456                                 break;
457                         case 'ENABLE_HOST_NOTIFICATIONS':
458                         case 'ENABLE_SVC_NOTIFICATIONS':
459                                 test = !(that.text() & NOTIFICATIONS_ENABLED);
460                                 break;
461                         case 'ENABLE_HOST_CHECK':
462                         case 'ENABLE_SVC_CHECK':
463                                 test = !(that.text() & CHECKS_ENABLED);
464                                 break;
465                         case 'DISABLE_HOST_CHECK':
466                         case 'DISABLE_SVC_CHECK':
467                                 test = that.text() & CHECKS_ENABLED;
468                                 break;
469                         case 'DEL_HOST_DOWNTIME':
470                         case 'DEL_SVC_DOWNTIME':
471                                 test = !(that.text() & SCHEDULED_DT);
472                                 break;
473                 }
474                 if (test) {
475                         that.closest('tr').find("." + field + " input[type='checkbox']").attr('disabled', true).attr('checked', false);
476                 }
477         });
480 function create_slider(the_id)
482         var last_update_request = false;
483         var id = $('#' + the_id + '_value');
484         var key = id.data('key');
485         var interval = id.val();
486         $("#" + the_id + "_slider").slider({
487                 value: interval,
488                 min: 0,
489                 max: 500,
490                 step: 10,
491                 slide: function(event, ui) {
492                         $("#" + the_id + "_value").val(ui.value);
493                 },
494                 stop: function(event, ui) {
495                         interval = ui.value;
496                         if(last_update_request !== false) {
497                                 last_update_request.abort();
498                         }
499                         last_update_request = $.ajax(
500                                 _site_domain + _index_page + "/ajax/save_page_setting/",
501                                 {
502                                         data: {
503                                                 page: '*',
504                                                 setting: interval,
505                                                 type: key
506                                         },
507                                         complete: function() {
508                                                 last_update_request = false;
509                                                 id.val(interval);
510                                         },
511                                         type: 'POST'
512                                 }
513                         );
514                 }
515         });
516         id.val($("#" + the_id + "_slider").slider("value"));
519 function ninja_refresh(val)
521         if (_interval) {
522                 clearInterval(_interval);
523         }
524         var refresh_val = (val === null) ? _refresh : val;
525         current_interval = refresh_val;
526         if (val>0) {
527                 _interval = setInterval( "refresh()", refresh_val*1000 );
528         }
531 function jgrowl_message(message_str, header_str)
533         if (message_str!=='') {
534                 $.jGrowl(message_str, { header: header_str });
535         }
539 // ===========================================================
540 // code for remembering scroll position between page reloads
541 // adapted from http://www.huntingground.freeserve.co.uk/main/mainfram.htm?../scripts/cookies/scrollpos.htm
542 // ===========================================================
544 cookieName = "page_scroll";
545 expdays = 5;
547 function setCookie(name, value, expires, path, domain, secure) {
548         if (!expires) {
549                 expires = new Date();
550         }
551         document.cookie = name + "=" + escape(value) +
552         ((expires === null) ? "" : "; expires=" + expires.toGMTString()) +
553         ((path === null) ? "" : "; path=" + path) +
554         ((domain === null) ? "" : "; domain=" + domain) +
555         ((secure === null) ? "" : "; secure");
558 function getCookie(name) {
559         var arg = name + "=";
560         var alen = arg.length;
561         var clen = document.cookie.length;
562         var i = 0;
563         while (i < clen) {
564                 var j = i + alen;
565                 if (document.cookie.substring(i, j) == arg){
566                         return getCookieVal(j);
567                 }
568                 i = document.cookie.indexOf(" ", i) + 1;
569                 if (i === 0) {
570                         break;
571                 }
572         }
573         return null;
576 function getCookieVal(offset) {
577         var endstr = document.cookie.indexOf (";", offset);
578         if (endstr == -1) {
579                 endstr = document.cookie.length;
580         }
581         return unescape(document.cookie.substring(offset, endstr));
584 function deleteCookie(name,path,domain) {
585         document.cookie = name + "=" + ((path === null) ? "" : "; path=" + path) + ((domain === null) ? "" : "; domain=" + domain) + "; expires=Thu, 01-Jan-00 00:00:01 GMT";
588 function saveScroll() {
589         var expdate = new Date();
590         expdate.setTime (expdate.getTime() + (expdays*24*60*60*1000)); // expiry date
592         if (!_save_scroll) {
593                 // reset scroll memory to top
594                 setCookie(cookieName,'0_0',expdate);
595                 return;
596         }
598         var x = $(window).scrollLeft();
599         var y = $(window).scrollTop();
600         Data = x + "_" + y;
602         setCookie(cookieName,Data,expdate);
605 $(window).bind('beforeunload', saveScroll);
607 function loadScroll() { // added function
608         inf = getCookie(cookieName);
609         if(!inf) {
610                 return;
611         }
612         var ar = inf.split("_");
613         if (ar.length == 2) {
614                 $(window).scrollLeft(parseInt(ar[0], 10));
615                 $(window).scrollTop(parseInt(ar[1], 10));
616         }
619 $(window).bind('load', loadScroll);
621 function trigger_cb_on_nth_call(cb, n) {
622         return function() {
623                 if (--n <= 0)
624                         cb();
625         };
628 function bind_helptext(element, controller, key) {
629         element.qtip($.extend(true, {}, qtip_default, {
630                 content: {
631                         text: function(ev, api) {
632                                 $.ajax({
633                                         url: _site_domain + _index_page + "/ajax/get_translation/",
634                                         data: {controller: controller, key: key},
635                                         type: 'POST',
636                                 })
637                                 .done(function(html) {
638                                         api.set('content.text', html);
639                                 })
640                                 .fail(function(xhr, status, error) {
641                                         api.set('content.text', status + ': ' + error);
642                                 });
644                                 return '<img src="' + _site_domain + loading_img + '" alt="' + _loading_str + '" />';
645                         }
646                 }
647         }));