//fix broken pylons checkbox values function fix_checkboxs() { $('INPUT[@type="checkbox"][value="True"]').attr('checked', true); } function show_notifications() { // TODO: get notification url, if notifications were found, add them to notification-placeholder divs $('.notification-placeholder').load() } var refresh_functions = []; function refresh_js() { //## console.log("refreshing javascripts for ajax loaded crap..."); $.each(refresh_functions, function () { if (this == undefined || this == null) { alert("There is error in registered refresh functions please check out whats the problem."); console.log(refresh_functions); } this(); }); fix_checkboxs(); show_notifications(); } // included js files (maybe includes could be controlled with parameters etc) // with includes it is a bit easier to maintain js code, // but still be able to optimize and all custom js stuff to one file /** */ /* */ function get_form_values(form) { var query_str = ""; $(form).find('input,textarea,select').each(function() { // add only checked radio buttons and checkboxes if ((this.type != 'radio' && this.type != 'checkbox') || this.checked) { if (query_str != "") { query_str += '&'; } query_str += this.name + '=' + encodeURIComponent(this.value); } }); return query_str; } /* */ function get_parameter(parameter, element, default_value) { var ret_val = default_value; if (element == undefined || element == null || element.length == 0) { alert('Error: element undefined when trying to get parameter: ' + parameter); } $.each($(element).attr('class').split(' '), function () { if (this.substr(0,parameter.length) == parameter) { ret_val = this.substr(parameter.length); } //console.log(ret_val); }); return ret_val; } function show_popup_message(message, timeout) { if (timeout == undefined) { timeout = 1500; } $.fancybox({ centerOnScroll: true, showCloseButton: false, content: message, scrolling: 'no', onComplete: function() { setTimeout("$.fancybox.close()", timeout); } }); } //Hide notifications after small time period function hide_notification_and_error(){ $("#notifications").each(function(){ $(this) .animate({opacity:1}, 2000) .fadeOut(600, function() { $(this).remove(); }); }); } /* */ function prevent_ie_cache() { return 'ie_cache_hack=' + Math.random(); } //TODO: maybe one should just keep track of last url that was loaded for element and reload it //if update url is not set function ajax_action_forms_refresh_url_from_element(elem) { var refresh_url_link = $(elem).find('a.ajax-update-url').get(0); if (refresh_url_link == undefined) { refresh_url = window.location; } else { refresh_url = refresh_url_link.href; } return refresh_url; } function ajax_action_forms_refresh_url(area_id) { return ajax_action_forms_refresh_url_from_element($('.ajax-refresh-area.area-id-' + area_id).get(0)); } // TODO: rethink this if this does still make sense or can be integrated to use send_ajax_request function // like refresh_area_link function refresh_area(area_id, refresh_url) { $('.ajax-refresh-area.area-id-' + area_id).each(function () { // if refresh url not given guess it if (refresh_url == null || refresh_url == undefined) { refresh_url = ajax_action_forms_refresh_url(area_id); } refresh_url = ('' + refresh_url).split('#')[0]; // TODO: show loaders loader-id (todo: use same ajax function that everything else does) $('.ajax-refresh-area.area-id-' + area_id).load(refresh_url + ' .ajax-refresh-area.area-id-' + area_id + '>*', prevent_ie_cache(), refresh_js); }); } //debug code for showing lates ajax request (IE debugging..) var debug_request = null; //TODO: add debug div to end of page and function which loads last debug_request.responseText to it for IE debugging function show_loading_message(element) { if (element == null || element == undefined) { alert('Error: show_loading_message missing parameter.'); } var loader_id = get_parameter("loader-id-", element, null); var show_loader = get_parameter("show-loader", element, null); var loader_message = null; if (loader_id != null) { loader_message = $('.ajax-action-loading-message.loader-id-' + loader_id); } else if (show_loader != null) { // find loading message from the same level, where is closest refresh area loader_message = $(element).closest('.ajax-refresh-area').prev('.ajax-action-loading-message'); if (loader_message.length == 0) { loader_message = $(element).closest('.ajax-refresh-area').next('.ajax-action-loading-message'); } } // show message if it really was found if (loader_message != null && loader_message.length != 0) { loader_message.show(); } } function hide_loading_message(element) { if (element == null || element == undefined) { alert('Error: hide_loading_message missing parameter.'); } var loader_id = get_parameter("loader-id-", element, null); if (loader_id != null) { loader_message = $('.ajax-action-loading-message.loader-id-' + loader_id); loader_message.hide(); } } function send_ajax_request(method, action_url, action_element, data) { if (data == undefined) data = null; var loader_message = null; show_loading_message(action_element); // select area_id if not set, find area where link is located var area_id = get_parameter("area-id-", action_element, null); if (area_id == null) { refresh_area = $(action_element).closest('.ajax-refresh-area'); area_id = get_parameter("area-id-", refresh_area, null); } if (area_id == null) { alert("Error: Must set class area-id- to " + action_element); } var area_to_reload = $('.ajax-refresh-area.area-id-' + area_id); if (area_to_reload.length == 0) { alert("Error: Element to refresh was not found:" + '.ajax-refresh-area.area-id-' + area_id); } var refresh_from_link = true; var refresh_url = ajax_action_forms_refresh_url(area_id); // TODO: read anchor from action url (you could move to anchor after success) var anchor = $.url.attr("anchor"); if (anchor) { action_url = action_url.split('#' + anchor)[0]; } // for IE debugging (firebug lite does not show ajax calls properly) //console.log("Loading ajax: " + method + " from: " + action_url + " params:" + data); //console.log("refresh url: " + refresh_url + " anchor: " + anchor + " refresh_from_link: " + refresh_from_link + " area-id:" + area_id); // TODO: also disable controls to prevent doubleclicks // TODO: add IE hack parameter to data $.ajax({ type: method, url: action_url, data: data, success: function (msg, textStatus, XMLHttpRequest) { debug_request = XMLHttpRequest; $(action_element).find('.clear-on-success').each(function () { $(this).val(''); $(this).triggerHandler('change'); }); // filter nested areas so only the outer div of nested divs are selected var selector_str = '.ajax-refresh-area.area-id-' + area_id; var refresh_areas = $(selector_str + ":not(" + selector_str + " " + selector_str + ")"); var wrapped_response = $('
' + msg + '
'); refresh_areas.replaceWith(wrapped_response.find('.ajax-refresh-area.area-id-' + area_id)); refresh_js(); hide_loading_message(action_element); // jump to anchor if (anchor != null) { window.location = window.location.href.split('#')[0] + "#" + anchor; } }, error: function (XMLHttpRequest, textStatus, errorThrown) { debug_request = XMLHttpRequest; hide_loading_message(action_element); // TODO: enable controls if they were previously disabled // (on success they will be enabled due to ajax-refresh) // if status is 503 (has error message returned in request) show message show_popup_message('
' + 'Connection failed, could not load data.' + '
'); } }); } function refresh_area_link(link_elem) { var refresh_url = link_elem.href; send_ajax_request('GET', refresh_url, link_elem); } function ajax_framework() { $('.ajax-action:not(.js-already-applied)').each(function() { $(this).addClass('js-already-applied'); if ($(this).is('form')) { $(this).submit(function () { // TODO: check if form onclick works // (should work since this is not click, but submit handler // and onclick confirmation may abort submit before it is sent) var action_element = $(this).closest('form'); var action_url = $(this).get(0).action; var params = get_form_values(this); send_ajax_request("POST", action_url, action_element, params); return false; }); } else { // remove confirmation binding function from element var onclick_action = this.onclick; // IE could not set to undefined this.onclick = null; $(this).click(function() { // run onclick confirmation before our own code if (onclick_action != undefined && onclick_action != null && !onclick_action()) { return false; } var action_element = this; var action_url = this.href; send_ajax_request("GET", action_url, action_element); return false; }); } }); // loads content automatically from link to refresh area id $('a.ajax-load:not(.js-ajax-load-already-applied)').each(function () { $(this).addClass('js-ajax-load-already-applied'); refresh_area_link(this); }); } refresh_functions.push(ajax_framework); /** */ var current_mouse_position_x = 0; var current_mouse_position_y = 0; var minimum_from_bottom = 20; var load_fix_delay = 200; function fix_mouse_position(hover_dest) { // hover_dest = $('div[name=' + hover_dest.attr('name') + ']'); if (current_mouse_position_y + hover_dest.height() > $(window).height() + $(window).scrollTop() - minimum_from_bottom) { current_mouse_position_y = $(window).scrollTop() + $(window).height() - hover_dest.height() - minimum_from_bottom; } hover_dest.css({left:current_mouse_position_x, top:current_mouse_position_y}); } function set_mouse_position(hover_element ,e) { var hover_dest = $('div[name=dest_' + hover_element.attr('name') + ']'); current_mouse_position_x = e.pageX + 10; current_mouse_position_y = e.pageY + 10; fix_mouse_position(hover_dest); } function ajax_hover_position() { $(".ajax_hover").bind("mouseenter mousemove", function(e) { set_mouse_position($(this), e); }); } function ajax_hover_class_hoverAppear() { var src_elem = $(this); var hover_selector = 'div[name=dest_' + src_elem.attr('name') + ']'; // Add div and load data if necessary if ($(hover_selector).length == 0) { $("body").append('
Loading...
'); new_elem = $(hover_selector); // Load content and fix div position after some delay... // need to use unreliable delay, because we cannot get any event from resize after the loaded div is rendered to screen // anyways, this works quite well and mousemove fixes bad positioning afterwards... new_elem.load(src_elem.attr('name'), null, function () { setTimeout("fix_mouse_position(new_elem)", load_fix_delay); refresh_js();}); } $(hover_selector).animate({opacity: "show"}, "fast"); } function ajax_hover_class_hoverDisappear() { var hover_dest = $('div[name=dest_' + $(this).attr('name') + ']'); hover_dest.animate({opacity: "hide"}, "fast"); } //global variable named config is really bad idea with js... var ajax_hover_class_config = { sensitivity: 2, // number = sensitivity threshold (must be 1 or higher) interval: 120, // number = milliseconds for onMouseOver polling interval over: ajax_hover_class_hoverAppear, // function = onMouseOver callback (REQUIRED) timeout: 120, // number = milliseconds delay before onMouseOut out: ajax_hover_class_hoverDisappear // function = onMouseOut callback (REQUIRED) }; function ajax_hover_class() { $(".ajax_hover:not(.js-ajax-hover-applied)").each(function () { $(this).addClass('js-ajax-hover-applied'); $(this).hoverIntent(ajax_hover_class_config); }); ajax_hover_position(); } refresh_functions.push(ajax_hover_class); /** */ function multi_select_class() { $('.multi_select').each(function () { var scrollable = $(this).hasClass('scrollable'); var searchable = $(this).hasClass('searchable'); // IE fix to make boxes a bit wider to no need to wrap elements var fixed_width = $(this).width() + 30; var generated_id = '#' + $(this).attr('id') + "_checklist"; $(this).toChecklist({ addScrollBar : scrollable, addSearchBox : searchable, showCheckboxes : true, showSelectedItems : false, submitDataAsArray : false }); $(generated_id).width(fixed_width); }); } refresh_functions.push(multi_select_class); /** */ /** */ function quicksearch_table_class() { jQuery("table.quicksearch_table").each(function() { var tryFocus = ! $.browser.msie; // wrap table to div and add pager div after table (if not already added) if (jQuery(this).parent().attr('id') != "quicksearch_table_outer_div_to_not_rerun_js_for_this") { jQuery(this).wrap('
'); jQuery("tbody tr").quicksearch({ position: 'before', labelText : 'Etsi', attached: this, loaderText: 'Haetaan tuloksia', focusOnLoad: tryFocus }); } }); } refresh_functions.push(quicksearch_table_class); /** * Requires: * * jquery.js * jquery.metadata.js * jquery.tablesorter.js * jquery.tablesorter.pager.js * * Still missing: (would be nice with pager) * http://www.jdempster.com/category/code/jquery/tablesortercookiewidget/ */ jQuery.tablesorter.addParser({ id: 'date', is: function(s) { return false; }, // don't auto detect format: function(s) { var splitted, day, month, year; if (s.search('/') == -1) { splitted = s.split('.'); day = 10 + splitted[0]; month = 10 + splitted[1]; year = splitted[2]; } else { splitted = s.split('/'); day = 10 + splitted[1]; month = 10 + splitted[0]; year = splitted[2]; } return year + month + day; }, type: 'numeric' }); /** * jQuery zebra widget does not apply odd even classes when table is loaded with ajax call. * For some reason this works better. */ $.tablesorter.addWidget({ // give the widget a id id: "zebraFix", format: function(table) { $("tbody tr",table).removeClass("odd even"); for(var i=0; i < table.tBodies[0].rows.length; i++) { var row = table.tBodies[0].rows[i]; if((i%2) == 0) { $(row).addClass('even'); } else { $(row).addClass('odd'); } } } }); //NOTE: THESE TABLE SORTERS WILL CHOCKE ON EMPTY LISTS... so make sure there is at least one empty row and columns //Use following markup to use date sorter. and remember to import jquery.metadata.js //Date function sort_table_class() { // if there is client table in page.. jQuery("table.sort_table").each(function() { if (this.tBodies.length == 0) { alert('Table sorter error: table body must be wrapped in tags.'); } jQuery(this).tablesorter({ //add backround color to every other row (defined as .odd class in table.css) widgets: ['zebraFix']}); }); } /** * Adds sort_table class which makes those tables sorted with javascript. * * first First button could be set to be image etc. * prev same * next same * last same * * pagesizes page sizes html. * e.g. * * * pager_form Whole pager form to add after table. * * e.g.
*/ function paged_sort_table_class(first, prev, next, last, pagesizes, pager_form) { // default values if (first == undefined) first = '
first
'; if (prev == undefined) prev = ''; if (next == undefined) next = ''; if (last == undefined) last = '
last
'; if (pagesizes == undefined) { pagesizes = '' + ' '; } if (pager_form == undefined) { pager_form = '
' + first + prev + '' + next + last + pagesizes + '
'; } var pager_id = 0; // if there is client table in page.. jQuery("table.paged_sort_table").each(function() { if (this.tBodies.length == 0) { alert('Table sorter error: table body must be wrapped in tags.'); } // generate id for pager pager_id = pager_id + 1; var pager_id_str = 'sorted_table_pager' + pager_id; // wrap table to div and add pager div after table (if not already added) if (jQuery(this).parent().attr('id') != "sorted_table_outer") { jQuery(this).wrap('
'); jQuery(this).parent().prepend('
' + pager_form + '
'); //pick only ones with matching class declaration jQuery(this).tablesorter({ widthFixed: true, //add backround color to every other row (defined as .odd class in table.css) widgets: ['zebra']}).tablesorterPager({positionFixed : false, container: $('#' + pager_id_str)}); } }); } refresh_functions.push(sort_table_class); refresh_functions.push(paged_sort_table_class); /** */ function show_selected_div(field) { var sel = $(field).val(); var prefix = $(field).attr('name'); //##console.log("Sel: " + sel + " Prefix: " + prefix); //## animations are used to increase usability. With animation (0.5 seconds) //## user has time to see, what actually changed in form. //## If animations are disabled, user just see that something changed, //## but cannot distinguish what really happened. $(".show_selected_field_" + prefix + ":not(.invert)").hide(); $(".show_selected_field_" + prefix + ".invert").show('fast'); $(".show_selected_field_" + prefix + "_" + sel + ":not(.invert)").show('fast'); $(".show_selected_field_" + prefix + "_" + sel + ".invert").hide(); } function show_selected() { $(".show_selected_div").each(function() { if (!this.js_already_applied) { this.js_already_applied = true; show_selected_div(this); $(this).change(function() { show_selected_div(this); }); } }); } refresh_functions.push(show_selected); //TODO: make safe for running multiple times function check_all_rows_class() { jQuery(".check_all_rows").click(function() { var checked_status = this.checked; jQuery(this).parent().parent().find('input').each(function() { this.checked = checked_status; }); }); } refresh_functions.push(check_all_rows_class); /** */ function update_poll_url(poll_url, success_string) { $.ajax({ url: poll_url, cache: false, success: function(html) { // find if name string is found from loaded file if (html.indexOf(success_string) != -1) { window.location.reload(true); } } }); } function poll_url_class() { $(".poll_url").each(function () { jQuery(this).hide(); poll_url = jQuery(this).attr('href'); success_str = jQuery(this).attr('name'); setInterval("update_poll_url('"+poll_url+"','"+success_str+"')", 4000); }); } refresh_functions.push(poll_url_class); /** * Introduces class which allows showing wordpress frontpage as carousel. * * requires: jquery-1.2 -> In html use following div - a construct where a href loads frontpage of wordpress, e.g. return urllib2.urlopen(g.blog_url).read()
Käy katsomassa uustiset waraamo blogista
NOTE: disaabled with IE earlier than 7.0 */ var global_carousel_prev_button_text_value = '»'; var global_carousel_next_button_text_value = '«'; function hide_show_element(elem) { if (elem.attr('disabled') == "true") { elem.hide('fast'); } else { elem.show('fast'); } } function hide_show_buttons() { hide_show_element($('div.jcarousel-next')); hide_show_element($('div.jcarousel-prev')); } function set_li_height_wp_blog_view_func(carousel, li, index, state) { /* * Currently use static height var height = $(li).children('div').height(); if (height != null) { height = Math.min(370, height + 50); $(li).css('height', 420); // uncomment, if 420 should be minimum height and // bigger posts will be resized to content size //$(li).css('height', height); } */ //console.log('setting stuff height '); $(li).css('height', 420); hide_show_buttons(); } function unset_li_height_wp_blog_view_func(carousel, li, index, state) { //console.log('unsetting stuff height '); $(li).css('height', null); hide_show_buttons(); } //Chrome needs this kind of init or it will not load stuff correctly. //e.g. next / prev buttons will not work. function wp_carousel_class_carousel_init(carousel, state) { carousel.prev(); } function load_carousel_wp_blog_view_func() { /* Disable with older IE */ if ($.browser.msie && $.browser.version < 7.0) { return; } $(this).wrapInner(''); $('div.post').each(function() { // convert ul li lists from blog posts to *
lists $(this).find('ul').each(function () { $(this).find('li').each(function () { //$(this).replaceWith("* " + $(this).text() + "
"); }); // remove ul tag and replace with inner html //$(this).($(this).html()); // Just remove failing ul -li lists for now.. TODO: fix above to work with IE 7 $(this).remove(); }); $(this).wrap('
  • '); }); $(this).jcarousel({ size: 10, visible : 1, scroll : 1, buttonPrevHTML: '
    ' + global_carousel_prev_button_text_value + '
    ', buttonNextHTML: '
    ' + global_carousel_next_button_text_value + '
    ', animSpeed:'slow', initCallback: wp_carousel_class_carousel_init, itemVisibleInCallback: set_li_height_wp_blog_view_func, itemVisibleOutCallback: unset_li_height_wp_blog_view_func}); $('div.jcarousel-next').after('
    '); } function wp_blog_view_class() { $('div.wp_blog_view').each(function() { // get next and prev link texts global_carousel_prev_button_text_value = $(this).find('div.prev_button_text').text(); global_carousel_next_button_text_value = $(this).find('div.next_button_text').text(); var blog_source = $(this).children('a').attr('href'); $(this).load(blog_source + " .post", null, load_carousel_wp_blog_view_func); }); } refresh_functions.push(wp_blog_view_class); function enable_do_not_repeat_action() { var no_repeat_box = "input#repeat_days_0"; // if do not repeat checkbox is set, uncheck others jQuery("input#repeat_days_0").click(function() { var checked_status = ! this.checked; jQuery("#repeat_days_checklist > ul > li > input").not(no_repeat_box).each(function() { this.checked = checked_status; if (checked_status) { $(this).closest('li').addClass('checked'); } else { $(this).closest('li').removeClass('checked'); } }); }); // if any other checkbox is clicked, uncheck do not repeat box jQuery("#repeat_days_checklist > ul > li > input").not(no_repeat_box).click(function() { jQuery(no_repeat_box).each(function() { this.checked = false; $(this).closest('li').removeClass('checked'); }); }); } function enable_calendar_tool_links() { jQuery("div#calendar_tool_links a#show_nighttime").show(); jQuery("div#calendar_tool_links a#hide_nighttime").show(); jQuery("div#calendar_tool_links a#hide_nighttime").addClass('inactive'); jQuery("div#calendar_tool_links a#hide_nighttime").click(function(event) { event.preventDefault(); jQuery("div.nighttime").hide(); jQuery("div#calendar_tool_links a#hide_nighttime").addClass('inactive'); jQuery("div#calendar_tool_links a#show_nighttime").removeClass('inactive'); }); jQuery("div#calendar_tool_links a#show_nighttime").click(function(event) { event.preventDefault(); jQuery("div.nighttime").show(); jQuery("div#calendar_tool_links a#hide_nighttime").removeClass('inactive'); jQuery("div#calendar_tool_links a#show_nighttime").addClass('inactive'); }); } function set_worker_calendar_ajax() { /* AJAX for the service calendar. */ /*target action to links in next and prev divs*/ enable_calendar_tool_links(); jQuery("div.nighttime").hide(); } refresh_functions.push(set_worker_calendar_ajax); refresh_functions.push(enable_do_not_repeat_action); function get_ajax_url(src_url) { var ajax_url = src_url; if (ajax_url.indexOf("?") == -1) { ajax_url = ajax_url + '?ajax=1'; } else { ajax_url = ajax_url + '&ajax=1'; } var IE_cache_hack_parameter = '&ie_hack=' + Math.random(); return ajax_url + IE_cache_hack_parameter; } function show_ajax_loading() { /* Empty notifications */ jQuery('#notifications,#errors').remove(); /* Show loader text */ jQuery("#loading_overlay").show(); } function on_event_calendar_event_click(event) { /* * * event has at least Date,URL and Title properties * */ show_ajax_loading(); jQuery("div#calendar").load(get_ajax_url(event.URL), refresh_js); return false; } function align_fancybox_to_top() { $('#fancybox-wrap').css('top','100px'); } function set_service_calendar_ajax() { jQuery("#loading_overlay").hide(); /* AJAX for the service calendar. */ jQuery("select").filter("#js_serviceSelect,#js_workerSelect,#js_categorySelect,.js-choose-resource").change(function() { // NOTE: this selects return url of all selects to be action of #js_chooseServiceForm var options = { target: '#calendar', url : get_ajax_url(jQuery("#js_chooseServiceForm").attr('action')), success : refresh_js }; show_ajax_loading(); jQuery(this).parent().parent().ajaxSubmit(options); return false; }); // hide the submit buttons in the JS enabled version jQuery("input").filter("#js_chooseService,#js_chooseWorker,#js_chooseCategory",".js-resource-select").hide(); jQuery("input").filter("#js_chooseCalendarDate").change(function() { var options = { target: '#calendar', url : get_ajax_url(jQuery("#js_chooseCalendarDateForm").attr('action')), success : refresh_js }; // this is pretty fragile show_ajax_loading(); jQuery(this).parent().parent().ajaxSubmit(options); return false; }); jQuery("#calendar a.calendar_navigation_link").click(function() { show_ajax_loading(); jQuery("div#calendar").load(get_ajax_url(jQuery(this).attr('href')), refresh_js); return false; }); // toggle calendar cells some times... cells_to_toggle = jQuery(".cell.hide_by_default"); cells_to_toggle.hide(); jQuery("#show_whole_calendar").click(function () { cells_to_toggle.toggle(); }); $(".tooltip").hide(); $(".has_tooltip").each(function () { // calculate which side of element tooltip should be applied var tooltip_left = $(this).position()['left']; // does not work with IE, before element is exposed once.. so hard code to 500 should be enough. var tooltip_width = $(this).next(".tooltip").width(); tooltip_width = 500; var align='right'; if (tooltip_left >= tooltip_width) { align='left'; } $(this).tooltip({ // custom positioning position: ['center', align], // move tooltip a little bit to the right offset: [15, 0], // there is no delay when the mouse is moved out of the trigger delay: 0 }); }); // when loading fancybox align it to top, because center will be too down when iframe length is big.. $(".fancybox_align_top").fancybox({ 'onComplete' : function() { align_fancybox_to_top(); $.fancybox.resize(); } }); $(".fancybox").fancybox({ 'onComplete' : function() { $.fancybox.resize(); } }); ajax_hover_class(); // init event calendar event_calendar_class(on_event_calendar_event_click); } refresh_functions.push(set_service_calendar_ajax); function date_to_request(date) { return date.getFullYear() + "," + (date.getMonth()+1) + "," + date.getDate(); } var selected_graphs = {}; function dataSetEnabled(set_name, utilization_data) { var ret_val = false; $.each(utilization_data, function () { if (this['label'] == set_name && this['data'].length > 0) { ret_val = true; return; } }); return ret_val; } function redraw_plot(utilization_data) { var mode = $('select#mode')[0].value; var multiplier = 1; if (mode == 'weekly') { multiplier = 7; } else if (mode == 'monthly') { multiplier = 28; } else if (mode == 'yearly') { multiplier = 365; } $.plot($("#utilization_graph"), utilization_data, { series: {bars : { show: true, barWidth: 86400000.0*multiplier }}, xaxis: {mode: "time", timeformat: "%d.%m"}, yaxis: { min: 0}, legend: {container: "#utilization_graph_legend"}, grid: { hoverable: true, clickable: true } } ); // add click handlers to legend for enabling and disabling datasets $('td.legendLabel').each(function() { var label = this.innerHTML; if (dataSetEnabled(label, utilization_data)) { $(this).after(''); } else { $(this).after(''); } $(this).parent().click(function () { $.each(utilization_data, function () { if (this['label'] == label) { selected_graphs[label] = ! selected_graphs[label]; var print_link = $('div.print-link a')[0].href; if (selected_graphs[label]) { $('div.print-link a')[0].href = print_link + encodeURIComponent(label + "+;+"); } else { $('div.print-link a')[0].href = print_link.replace(encodeURIComponent(label + "+;+"), ""); } var temp = this['data']; this['data'] = this['data_disabled']; this['data_disabled'] = temp; } }); redraw_plot(utilization_data); }); }); } function showTooltip(x, y, contents) { $('
    ' + contents + '
    ').css( { position: 'absolute', display: 'none', top: y + 5, left: x + 5, border: '1px solid #fdd', padding: '2px', 'background-color': '#fee', opacity: 0.80 }).appendTo("body").fadeIn(200); } function reload_graph_js() { if ($('div.utilization-summary-component').size() > 0 && $('div.utilization-summary-component').width() > 0) { var refresh_url = $('div.utilization-summary-component').find('a.refresh-url')[0].href; // ajax refresh div $('input#start:not(.js-applied),input#end:not(.js-applied),select#mode:not(.js-applied),select#type:not(.js-applied)').each(function () { $(this).addClass('js-applied'); $(this).change(function () { var start_date = $.datepicker.parseDate('mm/dd/yy', $('input#start')[0].value); var end_date = $.datepicker.parseDate('mm/dd/yy', $('input#end')[0].value); var mode = $('select#mode')[0].value; var type = $('select#type')[0].value; if (start_date > end_date) { start_date = end_date; } params = "?start=" + date_to_request(start_date) + "&end=" + date_to_request(end_date) + "&mode=" + mode + "&type=" + type; $('div.utilization-summary-component').load(refresh_url + params + ' div.utilization-summary-component', "", refresh_js); }); }); // get data from hidden json element of page var json_data = JSON.parse($('div#graph_data_json')[0].innerHTML, null); var utilization_data = []; // get data from hidden json element of page var preselected_graphs = JSON.parse($('div#selected_graphs_json')[0].innerHTML, null); var after_all_selected = ""; $.each(json_data, function (key) { // keep state during ajax stuff in global js variable if ((selected_graphs[key] == undefined || selected_graphs[key] == false) && preselected_graphs[key] == undefined) { selected_graphs[key] = false; data_set = {label: key, data: [], data_disabled: json_data[key]}; } else { selected_graphs[key] = true; data_set = {label: key, data: json_data[key], data_disabled: []}; after_all_selected += key + "+;+"; } utilization_data.push(data_set); }); // fix print link selection variables $('div.print-link a')[0].href = $('div.print-link a')[0].href + "&selected=" + encodeURIComponent(after_all_selected); redraw_plot(utilization_data); $(window).resize(function() { redraw_plot(utilization_data); }); var previousPoint = null; $("#utilization_graph").bind("plothover", function (event, pos, item) { if (item) { if (previousPoint != item.datapoint) { previousPoint = item.datapoint; $("#tooltip").remove(); var x = new Date(); var unit = item.datapoint[2]; var unit_str = $('input#unit-name')[0].value; var y = '' + item.datapoint[1].toFixed(0) + ' ' + unit_str; x.setTime(item.datapoint[0].toFixed(2)); showTooltip(item.pageX, item.pageY, x.getDate() + '.' + (x.getMonth() + 1) + '.' + x.getFullYear() + " " + item.series.label + ' ' + y); } } else { $("#tooltip").remove(); previousPoint = null; } }); } } refresh_functions.push(reload_graph_js); /** * Adds datepicker for field. * * dp-years-before- Sets limits how many years to the past picker can pick dates. Default * dp-years-after- Sets limits how many years to the future picker can pick dates. */ function add_datepicker() { $('input.datepicker').each(function () { var year_range_start = get_parameter('dp-years-before-', this, '110'); var year_range_end = get_parameter('dp-years-after-', this, '5'); year_range = "-" + year_range_start + ":" + "+" + year_range_end; $(this).datepicker({ dateFormat: 'mm/dd/yy', duration:'', closeAtTop: false, closeAtBottom: false, hideIfNoPrevNext: false, yearRange: year_range, changeMonth: true, changeYear: true, closeText : 'close', firstDay : 1 }); }); } refresh_functions.push(add_datepicker); function slide() { /* go through all slides and their cookies for initial status */ $('.slide').each(function() { if (!this.already_applied) { this.already_applied = true; /* get id element */ var $iid = $(this).attr("id"); var id_string = '#' + $iid + '_slidebox'; /* make an unstylized wrapper around slidebox */ $(id_string).wrap('
    '); var $slidebox = $(this).parent().parent().find("div#slidebox-outer"); /* read hide / show from cookie */ var status = $.cookie(id_string); if (status == 'closed') { $(this).attr("src", "/images/arrow_closed.png"); $slidebox.hide(); } else { $(this).attr("src", "/images/arrow_open.png"); $slidebox.show(); } $(this).click(function() { /* get id of clicked element */ var $iid = $(this).attr("id"); var id_string = '#' + $iid + '_slidebox'; /************************************************************************ * NOTE! parent().parent() so please use that kind of html tree... * or write code for searching first "div#slidebox-outer" after button. ************************************************************************/ var $slidebox = $(this).parent().parent().find("div#slidebox-outer"); /*switch image depending on open/close status*/ if ($(this).attr("src") == "/images/arrow_open.png") { $(this).attr("src", "/images/arrow_closed.png"); $.cookie(id_string, 'closed'); } else { $(this).attr("src", "/images/arrow_open.png"); $.cookie(id_string, 'open'); } /* slide element */ $slidebox.slideToggle(); }); } }); } refresh_functions.push(slide); function stars_rating_onclick(id,stars_coverage) { $('#'+id)[0].value = stars_coverage; $('#'+id+'-current-rating')[0].style.width = stars_coverage+'%'; } /* shows an alert if cookie passing doesn't work */ function check_cookies() { var cookie_string = 'im right here'; $.cookie('waraamo_cookie_test', cookie_string); if ($.cookie('waraamo_cookie_test') != cookie_string) { alert('cookies are not enabled click here to get cookie.'); } $.cookie('waraamo_cookie_test', null); } /** * Adds tabs for ul construct, which is done as ui tabs requires. */ function add_tabs() { $("ul.add-ui-tabs").tabs({ remote: true, cookie : true}); $('.ui-tabs-nav:not(.js-loadbinding-applied)').each(function () { $(this).addClass('js-loadbinding-applied'); $(this).bind('tabsload', function(event, ui) { refresh_js(); }); // because graph tab must be shown before plotting... // maybe could be fixed with use of ajax_framework (like carousell pages in social) $(this).bind('tabsshow', function(event, ui) { reload_graph_js(); }); }); } function change_tab(tab_name) { $("ul.add-ui-tabs").tabs('select', tab_name); } refresh_functions.push(add_tabs); $(function () { refresh_js(); });