<commit_before>function stylesheet(props, trackValueRatio, themeData) {
  const { disabled, ...activeStates } = props;
  const { hasFocus, hasHover, isPressed } = activeStates;

  const thumbPseudoElements = {
    microsoft: "::-ms-thumb",
    mozilla: "::-moz-range-thumb",
    webkit: "::-webkit-slider-thumb"
  };

  const trackPseudoElements = {
    microsoft: "::-ms-track",
    mozilla: "::-moz-range-track",
    webkit: "::-webkit-slider-runnable-track"
  };

  const trackProgressPseudoElements = {
    // WebKit does not have a pseudo element to target this styling, so we achieve it with fancy styling on track
    // ::-webkit-slider-runnable-track
    microsoft: "::-ms-fill-lower",
    mozilla: "::-moz-range-progress"
  };

  function browserSpecificPseudoElementRules(
    browserPseudoElements,
    rules,
    singleBrowserInclusions
  ) {
    const styles = {};

    Object.entries(browserPseudoElements).forEach(browserPseudoElement => {
      let pseudoElementRules = rules;

      const browser = browserPseudoElement[0];
      const pseudoElement = browserPseudoElement[1];

      if (singleBrowserInclusions && singleBrowserInclusions[browser]) {
        pseudoElementRules = {
          ...rules,
          ...singleBrowserInclusions[browser]
        };
      }

      styles[`&${pseudoElement}`] = pseudoElementRules;
    });

    return styles;
  }

  const baseRules = {
    WebkitAppearance: "none" /* Hides platform-native styling */,
    width: "100%" /* Specific width is required for Firefox. */,
    backgroundColor: "transparent" /* Otherwise white in Chrome */,
    boxSizing: "content-box",
    height: "20px",
    margin: 0,
    position: "relative",
    outline: "none",

    "&::-ms-tooltip": {
      display: "none"
    },

    "&::-moz-focus-outer": {
      border: 0
    }
  };

  const thumbDisabledRules = disabled
    ? {
        opacity: themeData["component.disabled.opacity"]
      }
    : {};

  const thumbStateRules = () => {
    const isInActiveState = Object.values(activeStates).every(
      stateValue => !stateValue
    );

    if (disabled || isInActiveState) {
      return {};
    }

    let stateKey;

    if (hasFocus) stateKey = "focused";
    if (hasHover) stateKey = "hover";
    if (isPressed) stateKey = "pressed";

    return {
      backgroundColor: themeData[`slider.${stateKey}.thumb.color`],
      boxShadow: `0 0 0 ${themeData[`slider.${stateKey}.halo.width`]} ${
        themeData[`slider.${stateKey}.halo.color`]
      }`
    };
  };

  const thumbRules = browserSpecificPseudoElementRules(
    thumbPseudoElements,
    {
      ...{
        boxSizing: "content-box",
        height: themeData["slider.thumb.minHeight"],
        width: themeData["slider.thumb.minWidth"],
        backgroundColor: themeData["slider.thumb.backgroundColor"],
        border: 0,
        borderRadius: 0,
        boxShadow: `0 0 0 ${themeData["slider.halo.width"]} ${
          themeData["slider.halo.color"]
        }`,
        position: "relative",
        top: "50%",
        transitionDuration: "0.3s",
        transitionProperty: "box-shadow",
        transitionTimingFunction: "cubic-bezier(0.4, 0, 0.2, 1)",
        WebkitAppearance: "none" /* Hides platform-native styling */
      },

      ...thumbStateRules()
    },
    {
      mozilla: {
        ...thumbDisabledRules
      },
      webkit: {
        transform: "translateY(-50%)"
      }
    }
  );

  const trackDisabledRules = disabled
    ? {
        opacity: themeData["component.disabled.opacity"]
      }
    : {};

  const trackValueWidth = `calc((0.5 * ${themeData["slider.thumb.width"]})
  + (${trackValueRatio} * (100% - ${themeData["slider.thumb.width"]})))`;

  const trackRules = browserSpecificPseudoElementRules(
    trackPseudoElements,
    {
      width: "100%",
      height: themeData["slider.track.width"],
      border: "none",
      backgroundColor: themeData["slider.track.color"],
      color: "transparent",
      outline: "none",

      ...trackDisabledRules
    },
    {
      // WebKit does not have a built-in way to target the progress/lower fill of a slider track.
      // This produces the same visual effect.
      webkit: {
        backgroundColor: themeData["slider.track.color"],
        backgroundImage: `linear-gradient(${themeData["slider.value.color"]}, ${
          themeData["slider.value.color"]
        })`,
        backgroundPosition: 0,
        backgroundSize: `${trackValueWidth} 100%`,
        backgroundRepeat: "no-repeat"
      }
    }
  );

  const trackProgressRules = browserSpecificPseudoElementRules(
    trackProgressPseudoElements,
    {
      border: "none",
      backgroundColor: themeData["slider.value.color"]
    },
    {
      mozilla: {
        ...trackDisabledRules
      }
    }
  );

  return {
    slider: {
      ...baseRules,
      ...thumbRules,
      ...trackRules,
      ...trackProgressRules
    }
  };
}

export default stylesheet;
<commit_msg>fix: slider knob missing border radius<commit_after>function stylesheet(props, trackValueRatio, themeData) {
  const { disabled, ...activeStates } = props;
  const { hasFocus, hasHover, isPressed } = activeStates;

  const thumbPseudoElements = {
    microsoft: "::-ms-thumb",
    mozilla: "::-moz-range-thumb",
    webkit: "::-webkit-slider-thumb"
  };

  const trackPseudoElements = {
    microsoft: "::-ms-track",
    mozilla: "::-moz-range-track",
    webkit: "::-webkit-slider-runnable-track"
  };

  const trackProgressPseudoElements = {
    // WebKit does not have a pseudo element to target this styling, so we achieve it with fancy styling on track
    // ::-webkit-slider-runnable-track
    microsoft: "::-ms-fill-lower",
    mozilla: "::-moz-range-progress"
  };

  function browserSpecificPseudoElementRules(
    browserPseudoElements,
    rules,
    singleBrowserInclusions
  ) {
    const styles = {};

    Object.entries(browserPseudoElements).forEach(browserPseudoElement => {
      let pseudoElementRules = rules;

      const browser = browserPseudoElement[0];
      const pseudoElement = browserPseudoElement[1];

      if (singleBrowserInclusions && singleBrowserInclusions[browser]) {
        pseudoElementRules = {
          ...rules,
          ...singleBrowserInclusions[browser]
        };
      }

      styles[`&${pseudoElement}`] = pseudoElementRules;
    });

    return styles;
  }

  const baseRules = {
    WebkitAppearance: "none" /* Hides platform-native styling */,
    width: "100%" /* Specific width is required for Firefox. */,
    backgroundColor: "transparent" /* Otherwise white in Chrome */,
    boxSizing: "content-box",
    height: "20px",
    margin: 0,
    position: "relative",
    outline: "none",

    "&::-ms-tooltip": {
      display: "none"
    },

    "&::-moz-focus-outer": {
      border: 0
    }
  };

  const thumbDisabledRules = disabled
    ? {
        opacity: themeData["component.disabled.opacity"]
      }
    : {};

  const thumbStateRules = () => {
    const isInActiveState = Object.values(activeStates).every(
      stateValue => !stateValue
    );

    if (disabled || isInActiveState) {
      return {};
    }

    let stateKey;

    if (hasFocus) stateKey = "focused";
    if (hasHover) stateKey = "hover";
    if (isPressed) stateKey = "pressed";

    return {
      backgroundColor: themeData[`slider.${stateKey}.thumb.color`],
      boxShadow: `0 0 0 ${themeData[`slider.${stateKey}.halo.width`]} ${
        themeData[`slider.${stateKey}.halo.color`]
      }`
    };
  };

  const thumbRules = browserSpecificPseudoElementRules(
    thumbPseudoElements,
    {
      ...{
        boxSizing: "content-box",
        height: themeData["slider.thumb.minHeight"],
        width: themeData["slider.thumb.minWidth"],
        backgroundColor: themeData["slider.thumb.backgroundColor"],
        border: 0,
        borderRadius: "1px",
        boxShadow: `0 0 0 ${themeData["slider.halo.width"]} ${
          themeData["slider.halo.color"]
        }`,
        position: "relative",
        top: "50%",
        transitionDuration: "0.3s",
        transitionProperty: "box-shadow",
        transitionTimingFunction: "cubic-bezier(0.4, 0, 0.2, 1)",
        WebkitAppearance: "none" /* Hides platform-native styling */
      },

      ...thumbStateRules()
    },
    {
      mozilla: {
        ...thumbDisabledRules
      },
      webkit: {
        transform: "translateY(-50%)"
      }
    }
  );

  const trackDisabledRules = disabled
    ? {
        opacity: themeData["component.disabled.opacity"]
      }
    : {};

  const trackValueWidth = `calc((0.5 * ${themeData["slider.thumb.width"]})
  + (${trackValueRatio} * (100% - ${themeData["slider.thumb.width"]})))`;

  const trackRules = browserSpecificPseudoElementRules(
    trackPseudoElements,
    {
      width: "100%",
      height: themeData["slider.track.width"],
      border: "none",
      backgroundColor: themeData["slider.track.color"],
      color: "transparent",
      outline: "none",

      ...trackDisabledRules
    },
    {
      // WebKit does not have a built-in way to target the progress/lower fill of a slider track.
      // This produces the same visual effect.
      webkit: {
        backgroundColor: themeData["slider.track.color"],
        backgroundImage: `linear-gradient(${themeData["slider.value.color"]}, ${
          themeData["slider.value.color"]
        })`,
        backgroundPosition: 0,
        backgroundSize: `${trackValueWidth} 100%`,
        backgroundRepeat: "no-repeat"
      }
    }
  );

  const trackProgressRules = browserSpecificPseudoElementRules(
    trackProgressPseudoElements,
    {
      border: "none",
      backgroundColor: themeData["slider.value.color"]
    },
    {
      mozilla: {
        ...trackDisabledRules
      }
    }
  );

  return {
    slider: {
      ...baseRules,
      ...thumbRules,
      ...trackRules,
      ...trackProgressRules
    }
  };
}

export default stylesheet;
<|endoftext|>


<commit_before>var imap_delete_action = function() {
    $('.imap_debug_data').empty();
    event.preventDefault();
    var form = $(this).parent();
    var id = form.find('#imap_server_id');
    Hm_Ajax.request(
        form.serializeArray(),
        function(res) {
            if (res.deleted_server_id > -1 ) {
                form.parent().remove();
            }
        },
        {'imap_delete': 1}
    );
};

var imap_save_action = function() {
    $('.imap_debug_data').empty();
    event.preventDefault();
    var form = $(this).parent();
    var id = form.find('#imap_server_id');
    Hm_Ajax.request(
        form.serializeArray(),
        function(res) {
            if (res.just_saved_credentials) {
                form.find('.credentials').attr('disabled', true);
                form.find('.save_imap_connection').hide();
                form.find('.imap_password').val('');
                form.find('.imap_password').attr('placeholder', '[saved]');
                form.append('<input type="submit" value="Forget" class="forget_imap_connection" />');
                $('.forget_imap_connection').on('click', imap_forget_action);
            }
        },
        {'imap_save': 1}
    );
};

var imap_forget_action = function() {
    $('.imap_debug_data').empty();
    event.preventDefault();
    var form = $(this).parent();
    var id = form.find('#imap_server_id');
    Hm_Ajax.request(
        form.serializeArray(),
        function(res) {
            if (res.just_forgot_credentials) {
                form.find('.credentials').attr('disabled', false);
                form.find('.imap_password').val('');
                form.find('.imap_password').attr('placeholder', 'Password');
                form.append('<input type="submit" value="Save" class="save_imap_connection" />');
                $('.save_imap_connection').on('click', imap_save_action);
                $('.forget_imap_connection', form).remove();
            }
        },
        {'imap_forget': 1}
    );
};

var imap_test_action = function() {
    $('.imap_debug_data').empty();
    $('.imap_folder_data').empty();
    Hm_Notices.show({0: 'Testing connection...'});
    event.preventDefault();
    var form = $(this).parent();
    var id = form.find('#imap_server_id');
    Hm_Ajax.request(
        form.serializeArray(),
        false,
        {'imap_connect': 1}
    );
};

var update_unread_message_display = function(res) {
    var ids = res.unread_server_ids.split(',');
    var msg_ids = [];
    if (res.formatted_unread_data && !jQuery.isEmptyObject(res.formatted_unread_data)) {
        $('.empty_list').remove();
    }
    for (index in res.formatted_unread_data) {
        row = res.formatted_unread_data[index][0];
        id = res.formatted_unread_data[index][1];
        if (!$('.'+id).length) {
            $('.message_table tbody').prepend(row);
            $('.'+id).fadeIn(600);
        }
        msg_ids.push(id);
    }
    var count = $('.message_table tbody tr').length;
    for (i=0;i<ids.length;i++) {
        $('.message_table tbody tr[class^=imap_'+ids[i]+'_]').filter(function() {
            var id = this.className;
            if (jQuery.inArray(id, msg_ids) == -1) {
                count--;
                $(this).remove();
            }
        });
    }
    document.title = 'HM3 '+count+' Unread';
    $('.sys_messages').html($('.sys_messages').html()+'.');
};

var imap_unread_update = function(loading) {
    var ids = $('#imap_server_ids').val().split(',');
    if ( ids && ids != '') {
        Hm_Notices.show({0: 'Updating unread messages '});
        for (i=0;i<ids.length;i++) {
            id=ids[i];
            Hm_Ajax.request(
                [{'name': 'hm_ajax_hook', 'value': 'ajax_imap_unread'},
                {'name': 'imap_server_ids', 'value': id}],
                update_unread_message_display,
                [],
                loading,
                set_unread_state
            );
        }
    }
    return false;
};

var toggle_long_headers = function() {
    $('.long_header').toggle(300);
    $('.header_toggle').toggle(0);
    return false;
};

var select_imap_folder = function(path, force) {
    var detail = parse_folder_path(path, 'imap');
    if (detail) {
        if (force) {
            Hm_Notices.show({0: 'Loading messages ...'});
        }
        Hm_Ajax.request(
            [{'name': 'hm_ajax_hook', 'value': 'ajax_imap_folder_display'},
            {'name': 'imap_server_id', 'value': detail.server_id},
            {'name': 'force_update', 'value': force},
            {'name': 'folder', 'value': detail.folder}],
            display_imap_mailbox,
            [],
            false
        );
    }
    return false;
};

var display_imap_mailbox = function(res) {
    Hm_Notices.hide(true);
    var imap_id = res.imap_server_id;
    var msg_ids = [];
    for (index in res.formatted_mailbox_page) {
        row = res.formatted_mailbox_page[index][0];
        id = res.formatted_mailbox_page[index][1];
        if (!$('.'+clean_selector(id)).length) {
            $('.message_table tbody').append(row);
            $('.'+clean_selector(id)).fadeIn(600);
        }
        msg_ids.push(id);
    }
    $('.message_table tbody tr[class^=imap_'+imap_id+'_]').filter(function() {
        var id = this.className;
        if (jQuery.inArray(id, msg_ids) == -1) {
            $(this).fadeOut(600, function() { $('.'+id).remove(); });
        }
    });
    if (res.imap_page_links) {
        $('.imap_page_links').html(res.imap_page_links);
    }
};

var expand_imap_folders = function(path) {
    var detail = parse_folder_path(path, 'imap');
    var list = $('.imap_'+detail.server_id+'_'+clean_selector(detail.folder));
    if ($('li', list).length == 0) {
        $('.expand_link', list).html('-');
        if (detail) {
            Hm_Notices.show({0: 'Loading folder ...'});
            Hm_Ajax.request(
                [{'name': 'hm_ajax_hook', 'value': 'ajax_imap_folder_expand'},
                {'name': 'imap_server_id', 'value': detail.server_id},
                {'name': 'folder', 'value': detail.folder}],
                expand_imap_mailbox,
                [],
                false,
                save_folder_list
            );
        }
    }
    else {
        $('.expand_link', list).html('+');
        $('ul', list).remove();
        save_folder_list();
    }
    return false;
};

var save_folder_list = function() {
    var folders = $('.imap_folders').html();
    $('*', folders).removeClass('selected_menu');
    Hm_Ajax.request(
        [{'name': 'hm_ajax_hook', 'value': 'ajax_imap_save_folder_state'},
        {'name': 'imap_folder_state', 'value': folders}],
        false,
        [],
        true
    );
};
var toggle_rows = function() {
    $(':checkbox').each(function () { this.checked = !this.checked; });
    toggle_msg_controls();
    return false;
};
var expand_imap_mailbox = function(res) {
    $('.'+clean_selector(res.imap_expanded_folder_path)).append(res.imap_expanded_folder_formatted);
};

var display_msg_content = function(res) {
    Hm_Notices.hide(true);
    $('.msg_text').html('');
    $('.msg_text').append(res.msg_gravatar);
    $('.msg_text').append(res.msg_headers);
    $('.msg_text').append(res.msg_text);
    $('.msg_text').append(res.msg_parts);
    document.title = 'HM3 '+$('.content_title').text();
};
var get_message_content = function(msg_part) {
    var uid = $('.msg_uid').val();
    var detail = parse_folder_path(hm_list_path, 'imap');
    if (detail && uid) {
        window.scrollTo(0,0);
        $('.msg_text_inner').html('');
        Hm_Notices.show({0: 'Fetching message ... '});
        Hm_Ajax.request(
            [{'name': 'hm_ajax_hook', 'value': 'ajax_imap_message_content'},
            {'name': 'imap_msg_uid', 'value': uid},
            {'name': 'imap_msg_part', 'value': msg_part},
            {'name': 'imap_server_id', 'value': detail.server_id},
            {'name': 'folder', 'value': detail.folder}],
            display_msg_content,
            [],
            false
        );
    }
    return false;
};

var set_unread_state = function() {
    Hm_Notices.hide(true);
    if ($('.message_table tr').length > 1) {
        $('.message_table').tablesorter({headers: { 3: { sorter: 'dt' } }, sortList: [[3,1],[2,0]]});
    }
    else {
        if (!$('.empty_list').length) {
            $('.message_list').append('
No unread messages found!
');
        }
    }
    var data = $('.message_table tbody');
    data.find('*[style]').attr('style', '');
    var request = function() {
            Hm_Ajax.request(
            [{'name': 'hm_ajax_hook', 'value': 'ajax_imap_save_unread_state'},
            {'name': 'formatted_unread_data', 'value': data.html()}],
            false,
            [],
            true
        );
    };
    setTimeout(request, 1000);
};
var toggle_msg_controls = function() {
    if ($('input:checked').length > 0) {
        $('.msg_controls a').removeClass('disabled_link');
    }
    else {
        $('.msg_controls a').addClass('disabled_link');
    }
};

var update_message_list = function(res) {
};

var imap_message_action = function(action_type) {
    var msg_list = $('.message_list');
    var selected = [];
    $(':checked', msg_list).each(function() {
        selected.push($(this).val());
    });
    if (selected.length > 0) {
        Hm_Notices.show({0: 'Performing message action ...'});
        Hm_Ajax.request(
            [{'name': 'hm_ajax_hook', 'value': 'ajax_imap_message_action'},
            {'name': 'imap_action_type', 'value': action_type},
            {'name': 'imap_message_ids', 'value': selected}],
            update_message_list,
            [],
            false
        );
    }
    return false;
}

if (hm_page_name == 'message_list') {
    $(':checkbox').each(function () { this.checked = false; });
    if (hm_list_path == 'unread') {
        $('.menu_unread').addClass('selected_menu');
        if ($('.message_table tbody tr').length > 0) {
            defer = true;
        }
        else {
            defer = false;
        }
        Hm_Timer.add_job(imap_unread_update, 60, defer);
        $('.message_table tr').fadeIn(100);
    }
    else if (hm_list_path == 'flagged') {
        $('.menu_flagged').addClass('selected_menu');
    }
    else if (hm_list_path.substring(0, 4) == 'imap') {
        $('a:eq(0)', $('.'+clean_selector(hm_list_path))).addClass('selected_menu');
        $('a:eq(1)', $('.'+clean_selector(hm_list_path))).addClass('selected_menu');
        if ($('.message_table tbody tr').length == 0) {
            select_imap_folder(hm_list_path, true);
        }
        $('.message_table tr').fadeIn(100);
    }
    $(':checkbox').click(function() {
        toggle_msg_controls();
    });

}
else if (hm_page_name == 'message') {
    if (hm_list_path.substring(0, 4) == 'imap') {
        if ($('.msg_text').children().length == 0) {
            get_message_content();
        }
        else {
            document.title = 'HM3 '+$('.content_title').text();
        }
    }
}
else if (hm_page_name == 'servers') {
    $('.imap_delete').on('click', imap_delete_action);
    $('.save_imap_connection').on('click', imap_save_action);
    $('.forget_imap_connection').on('click', imap_forget_action);
    $('.test_imap_connect').on('click', imap_test_action);
}
if ($.tablesorter) {
    $.tablesorter.addParser({
        id: 'dt',
        is: function(s) { return false; },
        format: function(s) { return Date.parse(s); },
        type: 'numeric'
    });
}
<commit_msg>fix missing semi-colon in imap js<commit_after>var imap_delete_action = function() {
    $('.imap_debug_data').empty();
    event.preventDefault();
    var form = $(this).parent();
    var id = form.find('#imap_server_id');
    Hm_Ajax.request(
        form.serializeArray(),
        function(res) {
            if (res.deleted_server_id > -1 ) {
                form.parent().remove();
            }
        },
        {'imap_delete': 1}
    );
};

var imap_save_action = function() {
    $('.imap_debug_data').empty();
    event.preventDefault();
    var form = $(this).parent();
    var id = form.find('#imap_server_id');
    Hm_Ajax.request(
        form.serializeArray(),
        function(res) {
            if (res.just_saved_credentials) {
                form.find('.credentials').attr('disabled', true);
                form.find('.save_imap_connection').hide();
                form.find('.imap_password').val('');
                form.find('.imap_password').attr('placeholder', '[saved]');
                form.append('<input type="submit" value="Forget" class="forget_imap_connection" />');
                $('.forget_imap_connection').on('click', imap_forget_action);
            }
        },
        {'imap_save': 1}
    );
};

var imap_forget_action = function() {
    $('.imap_debug_data').empty();
    event.preventDefault();
    var form = $(this).parent();
    var id = form.find('#imap_server_id');
    Hm_Ajax.request(
        form.serializeArray(),
        function(res) {
            if (res.just_forgot_credentials) {
                form.find('.credentials').attr('disabled', false);
                form.find('.imap_password').val('');
                form.find('.imap_password').attr('placeholder', 'Password');
                form.append('<input type="submit" value="Save" class="save_imap_connection" />');
                $('.save_imap_connection').on('click', imap_save_action);
                $('.forget_imap_connection', form).remove();
            }
        },
        {'imap_forget': 1}
    );
};

var imap_test_action = function() {
    $('.imap_debug_data').empty();
    $('.imap_folder_data').empty();
    Hm_Notices.show({0: 'Testing connection...'});
    event.preventDefault();
    var form = $(this).parent();
    var id = form.find('#imap_server_id');
    Hm_Ajax.request(
        form.serializeArray(),
        false,
        {'imap_connect': 1}
    );
};

var update_unread_message_display = function(res) {
    var ids = res.unread_server_ids.split(',');
    var msg_ids = [];
    if (res.formatted_unread_data && !jQuery.isEmptyObject(res.formatted_unread_data)) {
        $('.empty_list').remove();
    }
    for (index in res.formatted_unread_data) {
        row = res.formatted_unread_data[index][0];
        id = res.formatted_unread_data[index][1];
        if (!$('.'+id).length) {
            $('.message_table tbody').prepend(row);
            $('.'+id).fadeIn(600);
        }
        msg_ids.push(id);
    }
    var count = $('.message_table tbody tr').length;
    for (i=0;i<ids.length;i++) {
        $('.message_table tbody tr[class^=imap_'+ids[i]+'_]').filter(function() {
            var id = this.className;
            if (jQuery.inArray(id, msg_ids) == -1) {
                count--;
                $(this).remove();
            }
        });
    }
    document.title = 'HM3 '+count+' Unread';
    $('.sys_messages').html($('.sys_messages').html()+'.');
};

var imap_unread_update = function(loading) {
    var ids = $('#imap_server_ids').val().split(',');
    if ( ids && ids != '') {
        Hm_Notices.show({0: 'Updating unread messages '});
        for (i=0;i<ids.length;i++) {
            id=ids[i];
            Hm_Ajax.request(
                [{'name': 'hm_ajax_hook', 'value': 'ajax_imap_unread'},
                {'name': 'imap_server_ids', 'value': id}],
                update_unread_message_display,
                [],
                loading,
                set_unread_state
            );
        }
    }
    return false;
};

var toggle_long_headers = function() {
    $('.long_header').toggle(300);
    $('.header_toggle').toggle(0);
    return false;
};

var select_imap_folder = function(path, force) {
    var detail = parse_folder_path(path, 'imap');
    if (detail) {
        if (force) {
            Hm_Notices.show({0: 'Loading messages ...'});
        }
        Hm_Ajax.request(
            [{'name': 'hm_ajax_hook', 'value': 'ajax_imap_folder_display'},
            {'name': 'imap_server_id', 'value': detail.server_id},
            {'name': 'force_update', 'value': force},
            {'name': 'folder', 'value': detail.folder}],
            display_imap_mailbox,
            [],
            false
        );
    }
    return false;
};

var display_imap_mailbox = function(res) {
    Hm_Notices.hide(true);
    var imap_id = res.imap_server_id;
    var msg_ids = [];
    for (index in res.formatted_mailbox_page) {
        row = res.formatted_mailbox_page[index][0];
        id = res.formatted_mailbox_page[index][1];
        if (!$('.'+clean_selector(id)).length) {
            $('.message_table tbody').append(row);
            $('.'+clean_selector(id)).fadeIn(600);
        }
        msg_ids.push(id);
    }
    $('.message_table tbody tr[class^=imap_'+imap_id+'_]').filter(function() {
        var id = this.className;
        if (jQuery.inArray(id, msg_ids) == -1) {
            $(this).fadeOut(600, function() { $('.'+id).remove(); });
        }
    });
    if (res.imap_page_links) {
        $('.imap_page_links').html(res.imap_page_links);
    }
};

var expand_imap_folders = function(path) {
    var detail = parse_folder_path(path, 'imap');
    var list = $('.imap_'+detail.server_id+'_'+clean_selector(detail.folder));
    if ($('li', list).length == 0) {
        $('.expand_link', list).html('-');
        if (detail) {
            Hm_Notices.show({0: 'Loading folder ...'});
            Hm_Ajax.request(
                [{'name': 'hm_ajax_hook', 'value': 'ajax_imap_folder_expand'},
                {'name': 'imap_server_id', 'value': detail.server_id},
                {'name': 'folder', 'value': detail.folder}],
                expand_imap_mailbox,
                [],
                false,
                save_folder_list
            );
        }
    }
    else {
        $('.expand_link', list).html('+');
        $('ul', list).remove();
        save_folder_list();
    }
    return false;
};

var save_folder_list = function() {
    var folders = $('.imap_folders').html();
    $('*', folders).removeClass('selected_menu');
    Hm_Ajax.request(
        [{'name': 'hm_ajax_hook', 'value': 'ajax_imap_save_folder_state'},
        {'name': 'imap_folder_state', 'value': folders}],
        false,
        [],
        true
    );
};
var toggle_rows = function() {
    $(':checkbox').each(function () { this.checked = !this.checked; });
    toggle_msg_controls();
    return false;
};
var expand_imap_mailbox = function(res) {
    $('.'+clean_selector(res.imap_expanded_folder_path)).append(res.imap_expanded_folder_formatted);
};

var display_msg_content = function(res) {
    Hm_Notices.hide(true);
    $('.msg_text').html('');
    $('.msg_text').append(res.msg_gravatar);
    $('.msg_text').append(res.msg_headers);
    $('.msg_text').append(res.msg_text);
    $('.msg_text').append(res.msg_parts);
    document.title = 'HM3 '+$('.content_title').text();
};
var get_message_content = function(msg_part) {
    var uid = $('.msg_uid').val();
    var detail = parse_folder_path(hm_list_path, 'imap');
    if (detail && uid) {
        window.scrollTo(0,0);
        $('.msg_text_inner').html('');
        Hm_Notices.show({0: 'Fetching message ... '});
        Hm_Ajax.request(
            [{'name': 'hm_ajax_hook', 'value': 'ajax_imap_message_content'},
            {'name': 'imap_msg_uid', 'value': uid},
            {'name': 'imap_msg_part', 'value': msg_part},
            {'name': 'imap_server_id', 'value': detail.server_id},
            {'name': 'folder', 'value': detail.folder}],
            display_msg_content,
            [],
            false
        );
    }
    return false;
};

var set_unread_state = function() {
    Hm_Notices.hide(true);
    if ($('.message_table tr').length > 1) {
        $('.message_table').tablesorter({headers: { 3: { sorter: 'dt' } }, sortList: [[3,1],[2,0]]});
    }
    else {
        if (!$('.empty_list').length) {
            $('.message_list').append('
No unread messages found!
');
        }
    }
    var data = $('.message_table tbody');
    data.find('*[style]').attr('style', '');
    var request = function() {
            Hm_Ajax.request(
            [{'name': 'hm_ajax_hook', 'value': 'ajax_imap_save_unread_state'},
            {'name': 'formatted_unread_data', 'value': data.html()}],
            false,
            [],
            true
        );
    };
    setTimeout(request, 1000);
};
var toggle_msg_controls = function() {
    if ($('input:checked').length > 0) {
        $('.msg_controls a').removeClass('disabled_link');
    }
    else {
        $('.msg_controls a').addClass('disabled_link');
    }
};

var update_message_list = function(res) {
};

var imap_message_action = function(action_type) {
    var msg_list = $('.message_list');
    var selected = [];
    $(':checked', msg_list).each(function() {
        selected.push($(this).val());
    });
    if (selected.length > 0) {
        Hm_Notices.show({0: 'Performing message action ...'});
        Hm_Ajax.request(
            [{'name': 'hm_ajax_hook', 'value': 'ajax_imap_message_action'},
            {'name': 'imap_action_type', 'value': action_type},
            {'name': 'imap_message_ids', 'value': selected}],
            update_message_list,
            [],
            false
        );
    }
    return false;
};

if (hm_page_name == 'message_list') {
    $(':checkbox').each(function () { this.checked = false; });
    if (hm_list_path == 'unread') {
        $('.menu_unread').addClass('selected_menu');
        if ($('.message_table tbody tr').length > 0) {
            defer = true;
        }
        else {
            defer = false;
        }
        Hm_Timer.add_job(imap_unread_update, 60, defer);
        $('.message_table tr').fadeIn(100);
    }
    else if (hm_list_path == 'flagged') {
        $('.menu_flagged').addClass('selected_menu');
    }
    else if (hm_list_path.substring(0, 4) == 'imap') {
        $('a:eq(0)', $('.'+clean_selector(hm_list_path))).addClass('selected_menu');
        $('a:eq(1)', $('.'+clean_selector(hm_list_path))).addClass('selected_menu');
        if ($('.message_table tbody tr').length == 0) {
            select_imap_folder(hm_list_path, true);
        }
        $('.message_table tr').fadeIn(100);
    }
    $(':checkbox').click(function() {
        toggle_msg_controls();
    });

}
else if (hm_page_name == 'message') {
    if (hm_list_path.substring(0, 4) == 'imap') {
        if ($('.msg_text').children().length == 0) {
            get_message_content();
        }
        else {
            document.title = 'HM3 '+$('.content_title').text();
        }
    }
}
else if (hm_page_name == 'servers') {
    $('.imap_delete').on('click', imap_delete_action);
    $('.save_imap_connection').on('click', imap_save_action);
    $('.forget_imap_connection').on('click', imap_forget_action);
    $('.test_imap_connect').on('click', imap_test_action);
}
if ($.tablesorter) {
    $.tablesorter.addParser({
        id: 'dt',
        is: function(s) { return false; },
        format: function(s) { return Date.parse(s); },
        type: 'numeric'
    });
}
<|endoftext|>


<commit_before>/**
 * Module dependencies.
 */

var config = require('lib/config');
var mongoose = require('mongoose');
var mongoUrl = config('mongoUsersUrl') || config('mongoUrl');
var conn = mongoose.createConnection(mongoUrl);
var Schema = mongoose.Schema;
var ObjectId = Schema.ObjectId;
var passportLocalMongoose = require('passport-local-mongoose');
var gravatar = require('mongoose-gravatar');
var regexps = require('lib/regexps');

/**
 * Define `User` Schema
 */

var UserSchema = new Schema({
    firstName: { type: String }
  , lastName:  { type: String }
  , username:  { type: String }
  , avatar:    { type: String }
  , email:     { type: String, lowercase: true, trim: true, match: regexps.email } // main email
  , emailValidated: { type: Boolean, default: false }
  , profiles:  {
        facebook: { type: Object }
      , twitter:  { type: Object }
    }
  , createdAt: { type: Date, default: Date.now }
  , updatedAt: { type: Date }
  , profilePictureUrl: { type: String }
  , disabledAt: { type: Date }
  , notifications: {
    replies: { type: Boolean, default: true },
    "new-topic": { type: Boolean, default: true }
  }
});

/**
 * Define Schema Indexes for MongoDB
 */

UserSchema.index({ createdAt: -1 });
UserSchema.index({ firstName: 1, lastName: 1 });
UserSchema.index({'notifications.replies': 1});
UserSchema.index({'notifications.new-topic': 1});

/**
 * Make Schema `.toObject()` and
 * `.toJSON()` parse getters for
 * proper JSON API response
 */

UserSchema.set('toObject', { getters: true });
UserSchema.set('toJSON', { getters: true });

UserSchema.options.toObject.transform =
UserSchema.options.toJSON.transform = function(doc, ret, options) {
  // remove the hasn and salt of every document before returning the result
  delete ret.hash;
  delete ret.salt;
}

/**
 * -- Model's Plugin Extensions
 */

UserSchema.plugin(gravatar, { default: 'mm' });

UserSchema.plugin(passportLocalMongoose, {
  usernameField: 'email',
  userExistsError: 'There is already a user using %s'
});

/**
 * -- Model's API Extension
 */

/**
 * Get `fullName` from `firstName` and `lastName`
 *
 * @return {String} fullName
 * @api public
 */

UserSchema.virtual('fullName').get(function() {
  return this.firstName + ' ' + this.lastName;
});

/**
 * Get `staff` check from configured staff array
 *
 * @return {Boolean} staff
 * @api public
 */

UserSchema.virtual('staff').get(function() {
  var staff = config.staff || [];
  return !!~staff.indexOf(this.email);
});

/**
 * Find `User` by its email
 *
 * @param {String} email
 * @return {Error} err
 * @return {User} user
 * @api public
 */

UserSchema.statics.findByEmail = function(email, cb) {
  return this.findOne({ email: email })
    .exec(cb);
}

/**
 * Find `User` by social provider id
 *
 * @param {String|Number} id
 * @param {String} social
 * @return {Error} err
 * @return {User} user
 * @api public
 */

UserSchema.statics.findByProvider = function(profile, cb) {
  var path = 'profiles.'.concat(profile.provider).concat('.id');
  var query = {};
  query[path] = profile.id;
  return this.findOne(query)
    .exec(cb);
}

/**
 * Expose `User` Model
 */

module.exports = conn.model('User', UserSchema);
<commit_msg>Fix usage of quotes to match coding standard<commit_after>/**
 * Module dependencies.
 */

var config = require('lib/config');
var mongoose = require('mongoose');
var mongoUrl = config('mongoUsersUrl') || config('mongoUrl');
var conn = mongoose.createConnection(mongoUrl);
var Schema = mongoose.Schema;
var ObjectId = Schema.ObjectId;
var passportLocalMongoose = require('passport-local-mongoose');
var gravatar = require('mongoose-gravatar');
var regexps = require('lib/regexps');

/**
 * Define `User` Schema
 */

var UserSchema = new Schema({
    firstName: { type: String }
  , lastName:  { type: String }
  , username:  { type: String }
  , avatar:    { type: String }
  , email:     { type: String, lowercase: true, trim: true, match: regexps.email } // main email
  , emailValidated: { type: Boolean, default: false }
  , profiles:  {
        facebook: { type: Object }
      , twitter:  { type: Object }
    }
  , createdAt: { type: Date, default: Date.now }
  , updatedAt: { type: Date }
  , profilePictureUrl: { type: String }
  , disabledAt: { type: Date }
  , notifications: {
    replies: { type: Boolean, default: true },
    'new-topic': { type: Boolean, default: true }
  }
});

/**
 * Define Schema Indexes for MongoDB
 */

UserSchema.index({ createdAt: -1 });
UserSchema.index({ firstName: 1, lastName: 1 });
UserSchema.index({'notifications.replies': 1});
UserSchema.index({'notifications.new-topic': 1});

/**
 * Make Schema `.toObject()` and
 * `.toJSON()` parse getters for
 * proper JSON API response
 */

UserSchema.set('toObject', { getters: true });
UserSchema.set('toJSON', { getters: true });

UserSchema.options.toObject.transform =
UserSchema.options.toJSON.transform = function(doc, ret, options) {
  // remove the hasn and salt of every document before returning the result
  delete ret.hash;
  delete ret.salt;
}

/**
 * -- Model's Plugin Extensions
 */

UserSchema.plugin(gravatar, { default: 'mm' });

UserSchema.plugin(passportLocalMongoose, {
  usernameField: 'email',
  userExistsError: 'There is already a user using %s'
});

/**
 * -- Model's API Extension
 */

/**
 * Get `fullName` from `firstName` and `lastName`
 *
 * @return {String} fullName
 * @api public
 */

UserSchema.virtual('fullName').get(function() {
  return this.firstName + ' ' + this.lastName;
});

/**
 * Get `staff` check from configured staff array
 *
 * @return {Boolean} staff
 * @api public
 */

UserSchema.virtual('staff').get(function() {
  var staff = config.staff || [];
  return !!~staff.indexOf(this.email);
});

/**
 * Find `User` by its email
 *
 * @param {String} email
 * @return {Error} err
 * @return {User} user
 * @api public
 */

UserSchema.statics.findByEmail = function(email, cb) {
  return this.findOne({ email: email })
    .exec(cb);
}

/**
 * Find `User` by social provider id
 *
 * @param {String|Number} id
 * @param {String} social
 * @return {Error} err
 * @return {User} user
 * @api public
 */

UserSchema.statics.findByProvider = function(profile, cb) {
  var path = 'profiles.'.concat(profile.provider).concat('.id');
  var query = {};
  query[path] = profile.id;
  return this.findOne(query)
    .exec(cb);
}

/**
 * Expose `User` Model
 */

module.exports = conn.model('User', UserSchema);
<|endoftext|>


<commit_before>lobby.app.saves = {};

/* Make an associative array of Forms' data */
$.fn.serializeHTML = function() {
    var formData = "";
    var formId = $(this).attr("id");
    this.find('[name]').each(function() {
        name = $(this).attr("name");
        if(name.substr(-2, 2) == "[]"){
          name = name.substr(0, name.length-2);
          formData+='<input name="'+ formId + "[" + name + "][]" + '" value="' + $(this).val() + '" type="text" />';
        }else{
          if($(this).is(":checked")){
            formData += '<input name="'+ formId + "[" + name + "]" + '" type="checkbox" checked="checked" />';
          }else if($(this).attr("type") != "checkbox"){
            formData += '<input name="'+ formId + "[" + name + "]" + '" value="' + $(this).val().replace(/"/g, "'") + '" type="text" />';
          }
        }
    });
    return formData;
};

/**
 * Restoring/Loading Configuration
 */
lobby.app.restoreConfig = function(configName){
 /**
  * Get the config as JSON object
  */
  clog(configName);
  $replaceData = lobby.app["saves"][configName]["replacer"];
  $mainData = lobby.app["saves"][configName]["main"];

  /* Replacer Config */
  var replaceFields={};
  $("#replaceFields div").remove();
  $.each($replaceData, function(key, val){
     $(".workspace#site-compressor .addReplaceField").click();
     $(".workspace#site-compressor #replaceFields div:last").find("[name='replaceFrom[]']").val(key);
     $(".workspace#site-compressor #replaceFields div:last").find("[name='replaceTo[]']").val(val);
  });

   /* Restore Site Details */
  $('.workspace#site-compressor .top [data-binding]').each(function(){
    // handle the set value
    // need consider the different value type for different field type
    var $this = $(this);
    var val = $mainData[$this.data('binding')];

     // for chechbox
    if($this.is('[type=checkbox]')){
      $this.prop('checked',val)
      // for others
    }else{
      $this.val(
       decodeURIComponent(
         val.replace($this.attr("name") + "=", "")
       )
      );
    }
  });
  $(".workspace#site-compressor [name='beforeCommand'], .workspace#site-compressor [name='afterCommand']").each(function(){
    $(this).val($(this).val().replace(/\+/g, " "));
  });
};

/* Save Configuration */
lobby.app.saveConfig = function(configName){
   /* Save Site Details & Compression Options */
    var generalSettings = {};
  $('.workspace#site-compressor .top [data-binding]').each(function(){
    generalSettings[$(this).data('binding')] = $(this).serialize();
  });

    /* Since Replacer may have mutiple fields according to user choice, we add each values one by one. */
    var replacerData = {};
    if($(".workspace#site-compressor #siteDetails div").length != 0){
      $(".workspace#site-compressor #siteDetails div").each(function(){
        from = $(this).find("[name='replaceFrom[]']").val();
        to = $(this).find("[name='replaceTo[]']").val();
        if(from!="" && to!=""){
          replacerData[from] = to;
        }
      });
    }
  var configData = JSON.stringify({
    "main"      : generalSettings,
    "replacer" : replacerData
  });
    lobby.app.save(configName, configData, function(data){
      if(data == "bad"){
      alert("Failed Saving Data");
    }else{
        lobby.app.displaySaves();
      }
  });
}

lobby.app.displaySaves = function(){
  lobby.app.ajax("saves.php", {}, function(data){
    var data = JSON.parse(data);
    if( data.length == 0 ){
      $(".workspace#site-compressor #configSaves").html("No Saves Found");
    }else{
      $(".workspace#site-compressor #configSaves").html(""); // Empty the saves

      $.each(data, function(key){
        $(".workspace#site-compressor #configSaves").append("
" + key + "	LoadRemove
");
      });
    }
    lobby.app.saves = data;
  });
};

lobby.load(function(){
  localStorage["lastSaveName"] = "";

  /* Add Dynamic Srollbars */
  $(".workspace#site-compressor #left, .workspace#site-compressor #right, .workspace#site-compressor .compress-status").addClass("scrollbar-inner").scrollbar();
  $(".workspace#site-compressor .table #left:first").width($(document).width() * 40/100);
  $(".workspace#site-compressor .table #right:first").width($(document).width() * 57/100);

  /* Display the saved configs */
  lobby.app.displaySaves();

  /* Load Config when requested */
  $(".workspace#site-compressor .loadConfig").live("click", function(){
    id = $(this).attr("id");
    localStorage["lastSaveName"] = id;
    lobby.app.restoreConfig(id);
  });

  /* Remove Config when requested */
  $(".workspace#site-compressor .removeConfig").live("click", function(){
    configName = $(this).attr("id");
    lobby.app.remove(configName, function(){
      /* After deletion, Display the saves that are left */
      lobby.app.displaySaves();
    });
  });

  $(".workspace#site-compressor #siteDetails").live("submit", function(e){
    e.preventDefault();
    var formURL = lobby.app.src + "/src/ajax/compress.php";

    /* Make the fake form to be inserted in iframe */
    var formHTML = $("<form>").html(
      $(".workspace#site-compressor #options").serializeHTML() + $(".workspace#site-compressor #siteDetails").serializeHTML()
    ).attr({
      "method" : "POST",
      "action" : formURL
    }).css("display", "none").wrap('
').parent().html();

    $(".workspace#site-compressor .compress-status").html("");
    $("").attr({
      "height"      : ($(document).height() - ($(".workspace#site-compressor .top").offset().top + $(".workspace#site-compressor .top").height())) - 5,
      "width"       : "100%",
      "frameborder" : 0,
    }).appendTo(".workspace#site-compressor .compress-status");
    $(".workspace#site-compressor .compress-status").find("iframe").contents().find("body").html(formHTML);
    $(".workspace#site-compressor .compress-status").find("iframe").contents().find("body").find("form").submit();
  });
  $(".workspace#site-compressor .addReplaceField").live("click", function(){
    $(this).before("
<input name='replaceFrom[]' placeholder='From'><input name='replaceTo[]' style='margin-left:5px' placeholder='To'/>
");
  });

  $(".workspace#site-compressor #saveConfig").live("click", function(){
    var saveName = prompt("Please type in the name of the configuration", localStorage["lastSaveName"]);
    if(saveName != null){ /* If user didn't clicked cancel button */
      if(saveName.match("'")){
        alert("Can't have special characters in the save name");
      }else{
        if(saveName == ""){
          saveName = "default";
        }
        localStorage["lastSaveName"] = saveName;
        lobby.app.saveConfig(saveName);
      }
    }
  });

  /**
   * Site path Picker
   */
  $(".workspace #choose_site_path").live("click", function(){
    lobby.mod.FilePicker("/", function(result){
      $(".workspace #site_location").val(result.dir);
    });
  });

  $(".workspace #choose_site_output_path").live("click", function(){
    lobby.mod.FilePicker("/", function(result){
      $(".workspace #site_output_location").val(result.dir);
    });
  });
});
<commit_msg>Know which site is active<commit_after>lobby.app.saves = {};

/* Make an associative array of Forms' data */
$.fn.serializeHTML = function() {
    var formData = "";
    var formId = $(this).attr("id");
    this.find('[name]').each(function() {
        name = $(this).attr("name");
        if(name.substr(-2, 2) == "[]"){
          name = name.substr(0, name.length-2);
          formData+='<input name="'+ formId + "[" + name + "][]" + '" value="' + $(this).val() + '" type="text" />';
        }else{
          if($(this).is(":checked")){
            formData += '<input name="'+ formId + "[" + name + "]" + '" type="checkbox" checked="checked" />';
          }else if($(this).attr("type") != "checkbox"){
            formData += '<input name="'+ formId + "[" + name + "]" + '" value="' + $(this).val().replace(/"/g, "'") + '" type="text" />';
          }
        }
    });
    return formData;
};

/**
 * Restoring/Loading Configuration
 */
lobby.app.restoreConfig = function(configName){
 /**
  * Get the config as JSON object
  */
  $replaceData = lobby.app["saves"][configName]["replacer"];
  $mainData = lobby.app["saves"][configName]["main"];

  /* Replacer Config */
  var replaceFields={};
  $("#replaceFields div").remove();
  $.each($replaceData, function(key, val){
     $(".workspace#site-compressor .addReplaceField").click();
     $(".workspace#site-compressor #replaceFields div:last").find("[name='replaceFrom[]']").val(key);
     $(".workspace#site-compressor #replaceFields div:last").find("[name='replaceTo[]']").val(val);
  });

   /* Restore Site Details */
  $('.workspace#site-compressor .top [data-binding]').each(function(){
    // handle the set value
    // need consider the different value type for different field type
    var $this = $(this);
    var val = $mainData[$this.data('binding')];

     // for chechbox
    if($this.is('[type=checkbox]')){
      $this.prop('checked',val)
      // for others
    }else{
      $this.val(
       decodeURIComponent(
         val.replace($this.attr("name") + "=", "")
       )
      );
    }
  });
  $(".workspace#site-compressor [name='beforeCommand'], .workspace#site-compressor [name='afterCommand']").each(function(){
    $(this).val($(this).val().replace(/\+/g, " "));
  });
  $('.workspace#site-compressor .top #right').scrollTop($('.workspace#site-compressor .top #right')[0].scrollHeight);
};

/* Save Configuration */
lobby.app.saveConfig = function(configName){
   /* Save Site Details & Compression Options */
    var generalSettings = {};
  $('.workspace#site-compressor .top [data-binding]').each(function(){
    generalSettings[$(this).data('binding')] = $(this).serialize();
  });

    /* Since Replacer may have mutiple fields according to user choice, we add each values one by one. */
    var replacerData = {};
    if($(".workspace#site-compressor #siteDetails div").length != 0){
      $(".workspace#site-compressor #siteDetails div").each(function(){
        from = $(this).find("[name='replaceFrom[]']").val();
        to = $(this).find("[name='replaceTo[]']").val();
        if(from!="" && to!=""){
          replacerData[from] = to;
        }
      });
    }
  var configData = JSON.stringify({
    "main"      : generalSettings,
    "replacer" : replacerData
  });
    lobby.app.save(configName, configData, function(data){
      if(data == "bad"){
      alert("Failed Saving Data");
    }else{
        lobby.app.displaySaves();
      }
  });
}

lobby.app.displaySaves = function(){
  lobby.app.ajax("saves.php", {}, function(data){
    var data = JSON.parse(data);
    if( data.length == 0 ){
      $(".workspace#site-compressor #configSaves").html("No Saves Found");
    }else{
      $(".workspace#site-compressor #configSaves").html(""); // Empty the saves

      $.each(data, function(key){
        $(".workspace#site-compressor #configSaves").append("
" + key + "	LoadRemove
");
      });
    }
    lobby.app.saves = data;
  });
};

lobby.load(function(){
  localStorage["lastSaveName"] = "";

  /* Add Dynamic Srollbars */
  $(".workspace#site-compressor #left, .workspace#site-compressor #right, .workspace#site-compressor .compress-status").addClass("scrollbar-inner").scrollbar();
  $(".workspace#site-compressor .table #left:first").width($(document).width() * 40/100);
  $(".workspace#site-compressor .table #right:first").width($(document).width() * 57/100);

  /* Display the saved configs */
  lobby.app.displaySaves();

  /* Load Config when requested */
  $(".workspace#site-compressor .loadConfig").live("click", function(){
    id = $(this).attr("id");
    localStorage["lastSaveName"] = id;
    lobby.app.restoreConfig(id);
    $(".workspace .left #configSaves tr").attr("style", "");
    $(this).parents("tr").css("background-color", "#FAEBD7");
  });

  /* Remove Config when requested */
  $(".workspace#site-compressor .removeConfig").live("click", function(){
    configName = $(this).attr("id");
    lobby.app.remove(configName, function(){
      /* After deletion, Display the saves that are left */
      lobby.app.displaySaves();
    });
  });

  $(".workspace#site-compressor #siteDetails").live("submit", function(e){
    e.preventDefault();
    var formURL = lobby.app.src + "/src/ajax/compress.php";

    /* Make the fake form to be inserted in iframe */
    var formHTML = $("<form>").html(
      $(".workspace#site-compressor #options").serializeHTML() + $(".workspace#site-compressor #siteDetails").serializeHTML()
    ).attr({
      "method" : "POST",
      "action" : formURL
    }).css("display", "none").wrap('
').parent().html();

    $(".workspace#site-compressor .compress-status").html("");
    $("").attr({
      "height"      : ($(document).height() - ($(".workspace#site-compressor .top").offset().top + $(".workspace#site-compressor .top").height())) - 5,
      "width"       : "100%",
      "frameborder" : 0,
    }).appendTo(".workspace#site-compressor .compress-status");
    $(".workspace#site-compressor .compress-status").find("iframe").contents().find("body").html(formHTML);
    $(".workspace#site-compressor .compress-status").find("iframe").contents().find("body").find("form").submit();
  });
  $(".workspace#site-compressor .addReplaceField").live("click", function(){
    $(this).before("
<input name='replaceFrom[]' placeholder='From'><input name='replaceTo[]' style='margin-left:5px' placeholder='To'/>
");
  });

  $(".workspace#site-compressor #saveConfig").live("click", function(){
    var saveName = prompt("Please type in the name of the configuration", localStorage["lastSaveName"]);
    if(saveName != null){ /* If user didn't clicked cancel button */
      if(saveName.match("'")){
        alert("Can't have special characters in the save name");
      }else{
        if(saveName == ""){
          saveName = "default";
        }
        localStorage["lastSaveName"] = saveName;
        lobby.app.saveConfig(saveName);
      }
    }
  });

  /**
   * Site path Picker
   */
  $(".workspace #choose_site_path").live("click", function(){
    lobby.mod.FilePicker("/", function(result){
      $(".workspace #site_location").val(result.dir);
    });
  });

  $(".workspace #choose_site_output_path").live("click", function(){
    lobby.mod.FilePicker("/", function(result){
      $(".workspace #site_output_location").val(result.dir);
    });
  });
});
<|endoftext|>


<commit_before>require.config({
    'waitSeconds': 2,
    'baseUrl': '../../../src',
    'packages': [
        {
            'name': 'ubRiaUi',
            'location': 'src',
            'main': 'main'
        },
        {
            'name': 'esui',
            'location': '../dep/esui/3.2.0-beta.2/src',
            'main': 'main'
        },
        {
            'name': 'mini-event',
            'location': '../dep/mini-event/1.0.2/src',
            'main': 'main'
        },
        {
            'name': 'underscore',
            'location': '../dep/underscore/1.5.2/src',
            'main': 'underscore'
        },
        {
            'name': 'moment',
            'location': '../dep/moment/2.7.0/src',
            'main': 'moment'
        },
        {
            'name': 'etpl',
            'location': '../dep/etpl/3.0.1/src',
            'main': 'main'
        },
        {
            'name': 'eoo',
            'location': '../dep/eoo/0.1.4/src'
        },
        {
            'name': 'jquery',
            'location': '../dep/jquery/1.11.1/src',
            'main': 'jquery'
        },
        {
            'name': 'eicons',
            'location': '../dep/eicons/1.0.0-beta.1/src',
            'main': 'main.less'
        },
        {
            'name': 'esf',
            'location': '../dep/esf/1.0.0-rc.2/src'
        },
        {
            'name': 'est',
            'location': '../dep/est/1.3.0/src'
        },
        {
            'name': 'unit',
            'location': 'test/unit'
        }
    ],
    'paths': { 'jquery-simulate': 'test/third-party/jquery.simulate' },
    'shim': {
        'jquery-simulate': ['jquery'],
        'matchers': ['jasmine']
    }
});
<commit_msg>revert config.js<commit_after>require.config({
    'waitSeconds': 2,
    'baseUrl': '../../../src',
    'packages': [
        {
            'name': 'ubRiaUi',
            'location': 'src',
            'main': 'main'
        },
        {
            'name': 'esui',
            'location': '../dep/esui/3.2.0-beta.2/src',
            'main': 'main'
        },
        {
            'name': 'mini-event',
            'location': '../dep/mini-event/1.0.2/src',
            'main': 'main'
        },
        {
            'name': 'underscore',
            'location': '../dep/underscore/1.5.2/src',
            'main': 'underscore'
        },
        {
            'name': 'moment',
            'location': '../dep/moment/2.7.0/src',
            'main': 'moment'
        },
        {
            'name': 'etpl',
            'location': '../dep/etpl/3.0.1/src',
            'main': 'main'
        },
        {
            'name': 'eoo',
            'location': '../dep/eoo/0.1.4/src',
            'main': 'src/main'
        },
        {
            'name': 'jquery',
            'location': '../dep/jquery/1.11.1/src',
            'main': 'jquery'
        },
        {
            'name': 'eicons',
            'location': '../dep/eicons/1.0.0-beta.1/src',
            'main': 'main.less'
        },
        {
            'name': 'esf',
            'location': '../dep/esf/1.0.0-rc.2/src'
        },
        {
            'name': 'est',
            'location': '../dep/est/1.3.0/src'
        },
        {
            'name': 'unit',
            'location': 'test/unit'
        }
    ],
    'paths': { 'jquery-simulate': 'test/third-party/jquery.simulate' },
    'shim': {
        'jquery-simulate': ['jquery'],
        'matchers': ['jasmine']
    }
});
<|endoftext|>


<commit_before>'use strict';

(function() {
  angular.module('ncsaas')
    .service('baseEventListController', [
      'baseControllerListClass', 'eventsService', 'EVENTTYPE', baseEventListController]);

  function baseEventListController(baseControllerListClass, eventsService, EVENTTYPE) {
    var ControllerListClass = baseControllerListClass.extend({
      EVENTTYPE: EVENTTYPE,

      init:function() {
        this.service = eventsService;
        this.searchFieldName = 'search';
        this.searchFilters = [
          {
            name: 'event_type',
            title: 'Logged in',
            value: EVENTTYPE.auth_logged_in_with_username
          },
          {
            name: 'event_type',
            title: 'Project creation',
            value: EVENTTYPE.project_creation_succeeded
          },
          {
            name: 'event_type',
            title: 'Organization creation',
            value: EVENTTYPE.customer_creation_succeeded
          }
        ];
        this._super();
      }
    });

    return ControllerListClass;
  }

  angular.module('ncsaas')
    .controller('EventListController', [
      '$scope',
      'baseEventListController',
      'currentStateService',
      'ENV',
      EventListController]);

  function EventListController(
    $scope,
    baseEventListController,
    currentStateService,
    ENV) {
    var controllerScope = this;
    var EventController = baseEventListController.extend({
      init:function() {
        this.controllerScope = controllerScope;
        this.cacheTime = ENV.dashboardEventsCacheTime;
        this._super();

        $scope.$on('currentCustomerUpdated', this.onCustomerUpdate.bind(this));
      },

      onCustomerUpdate: function() {
        this.getList();
      },

      getList: function(filter) {
        var vm = this;
        var fn = this._super.bind(vm);
        return currentStateService.getCustomer().then(function(customer) {
          vm.service.defaultFilter.scope = customer.url;
          fn(filter);
        });
      }
    });

    controllerScope.__proto__ = new EventController();
  }

  angular.module('ncsaas')
    .controller('CustomerAlertsListController', [
      '$scope',
      'baseControllerListClass',
      'currentStateService',
      'alertsService',
      'ENTITYLISTFIELDTYPES',
      CustomerAlertsListController]);

  function CustomerAlertsListController(
    $scope,
    baseControllerListClass,
    currentStateService,
    alertsService,
    ENTITYLISTFIELDTYPES) {
    var controllerScope = this;
    var controllerClass = baseControllerListClass.extend({
      init: function() {
        this.controllerScope = controllerScope;
        this.service = alertsService;
        this._super();

        this.entityOptions = {
          entityData: {
            noDataText: 'No alerts yet'
          },
          list: [
            {
              name: 'Message',
              propertyName: 'message',
              type: ENTITYLISTFIELDTYPES.noType
            }
          ]
        };

        $scope.$on('currentCustomerUpdated', this.onCustomerUpdate.bind(this));
      },

      onCustomerUpdate: function() {
        this.getList();
      },

      getList: function(filter) {
        var vm = this;
        var fn = this._super.bind(vm);
        filter = filter || {};
        return currentStateService.getCustomer().then(function(customer) {
          vm.service.defaultFilter.aggregate = 'customer';
          vm.service.defaultFilter.uuid = customer.uuid;
          fn(filter);
        })
      }
    });

    controllerScope.__proto__ = new controllerClass();
  }

  angular.module('ncsaas')
    .controller('DashboardIndexController', [
      '$scope',
      '$stateParams',
      'baseControllerClass',
      DashboardIndexController]);

  function DashboardIndexController($scope, $stateParams, baseControllerClass) {
    var controllerScope = this;
    var EventController = baseControllerClass.extend({
      init: function() {
        $scope.activeTab = $stateParams.tab || 'activity';
      }
    });

    controllerScope.__proto__ = new EventController();
  }

  angular.module('ncsaas')
    .controller('DashboardCostController', [
      '$scope',
      'baseControllerClass',
      'priceEstimationService',
      'blockUI',
      DashboardCostController]);

  function DashboardCostController(
    $scope,
    baseControllerClass,
    priceEstimationService,
    blockUI) {
    var controllerScope = this;
    var EventController = baseControllerClass.extend({
      init: function() {
        this.controllerScope = controllerScope;

        $scope.$on('currentCustomerUpdated', this.onCustomerUpdate.bind(this));
        this.onCustomerUpdate();
        blockUI.start();
      },

      onCustomerUpdate: function() {
        var vm = this;
        priceEstimationService.pageSize = 1000;
        priceEstimationService.getList().then(function(rows) {
          vm.processChartData(rows);
          vm.processTableData(rows);
        });
      },

      processChartData: function(rows) {
        var labels = [];
        var totals = [];
        rows.forEach(function(row) {
          if (row.scope_type == 'customer') {
            labels.unshift(moment(row.month, 'MM').format('MMMM'));
            totals.unshift(row.total);
          }
        });
        blockUI.stop();

        this.chartOptions = {
          bezierCurve: false,
          responsive: true,
          animationEasing: "linear"
        };

        this.costData = {
          labels: labels,
          datasets: [
            {
              fillColor: "rgba(123, 166, 196,0.5)",
              strokeColor: "rgba(123, 166, 196,1)",
              pointColor: "rgba(123, 166, 196,1)",
              pointStrokeColor: "#fff",
              pointHighlightFill: "#fff",
              pointHighlightStroke: "rgba(123, 166, 196,1)",
              data: totals
            }
          ]
        };
      },

      processTableData: function(rows) {
        var results = {};
        for (var i = 0; i < rows.length; i++) {
          var row = rows[i];
          var date = moment(row.month, 'MM').format('MMMM') + ' ' + row.year;
          if (!results.hasOwnProperty(date)) {
            results[date] = {
              total: 0,
              projects: [],
              services: [],
              resources: []
            }
          }
          if (row.scope_type == 'customer') {
            results[date].total = row.total;
          }
          if (row.scope_type == 'project') {
            results[date].projects.push(row);
          }
          if (row.scope_type == 'resource') {
            results[date].resources.push(row);
          }
          if (row.scope_type == 'service') {
            results[date].services.push(row);
          }
          if (row.scope_type == 'serviceprojectlink') {
            results[date].services.push(row);
          }
        }
        var table = [];
        for (var date in results) {
          var row = results[date];
          table.push({
            date: date,
            total: row.total,
            projects: row.projects,
            services: row.services,
            resources: row.resources
          });
        }
        if (table.length > 0) {
          table[0].selected = true;
          table[0].activeTab = 'services';
        }
        this.table = table;
      }
    });

    controllerScope.__proto__ = new EventController();
  }

  angular.module('ncsaas')
    .controller('DashboardActivityController', [
      'baseControllerClass',
      '$scope',
      '$rootScope',
      '$state',
      'projectsService',
      'alertsService',
      'eventsService',
      'eventStatisticsService',
      'resourcesCountService',
      'currentStateService',
      'ENV',
      '$window',
      DashboardActivityController]);

  function DashboardActivityController(
    baseControllerClass,
    $scope,
    $rootScope,
    $state,
    projectsService,
    alertsService,
    eventsService,
    eventStatisticsService,
    resourcesCountService,
    currentStateService,
    ENV,
    $window) {
    var controllerScope = this;
    var EventController = baseControllerClass.extend({
      showGraph: true,
      init:function() {
        this.controllerScope = controllerScope;
        this.cacheTime = ENV.dashboardEventsCacheTime;
        this._super();
        this.activeTab = 'activity';
        this.chartOptions = {
          responsive: true,
          scaleShowVerticalLines: false,
          scaleShowGridLines: false,
          bezierCurve: false
        };

        $scope.$on('currentCustomerUpdated', this.onCustomerUpdate.bind(this));
        this.onCustomerUpdate();
        this.resizeControl();
      },
      resizeControl: function() {
        var vm = this;

        var window = angular.element($window);
        window.bind('resize', function () {
          vm.showGraph = false;
          setTimeout(function() {
            vm.showGraph = true;
            $scope.$apply();
          }, 0);
          $scope.$apply();
        });
      },
      selectProject: function (project) {
        if (project) {
          project.selected =! project.selected;
          this.getProjectResources(project);
          this.getProjectEvents(project);
        }
      },
      onCustomerUpdate: function() {
        this.getCustomerProjects();
        this.getCustomerEvents();
        this.getCustomerAlerts();
      },
      getCustomerAlerts: function () {
        var vm = this;
        currentStateService.getCustomer().then(function(customer) {
          alertsService.getList({'aggregate': 'customer', 'uuid': customer.uuid}).then(function(response) {
            vm.alerts = response;
          })
        })
      },
      getCustomerEvents: function () {
        var vm = this;
        currentStateService.getCustomer().then(function(customer) {
          eventsService.getList({'scope': customer.url}).then(function(response) {
            vm.events = response;
          })
        })
      },
      getCustomerProjects: function() {
        var vm = this;
        projectsService.getList().then(function(response) {
          vm.projects = response;
          for (var i = 0; i < vm.projects.length; i++) {
            vm.projects[i].selected = false;
          }
          vm.selectProject(vm.projects[0]);
        });
      },
      getProjectResources: function (project) {
        if (project.count) {
          return;
        }
        project.count = {};
        project.count.services = project.services.length;
        resourcesCountService.users({'project': project.uuid}).then(function(count) {
          project.count.users = count;
        });
        resourcesCountService.resources({
          'project_uuid': project.uuid,
          'resource_type': ENV.resourceFilters.VMs
        }).then(function(count) {
          project.count.resources = count;
        });
        resourcesCountService.alerts({'scope': project.url}).then(function(count) {
          project.count.alerts = count;
        });
      },
      getProjectEvents: function (project) {
        if (project.chartData) {
          return;
        }
        var end = moment.utc().unix();
        var count = 7;
        var start = moment.utc().subtract(count + 1, 'days').unix();
        eventStatisticsService.getList({
          'scope': project.url,
          'start': start,
          'end': end,
          'points_count': count + 1
        }).then(function(response) {
          var labels = [];
          var total = [];
          for (var i = 0; i < response.length; i++) {
            var date = moment.unix(response[i].point);
            var day = date.format('dddd');
            var value = response[i].object.count;
            labels.push(day);
            total.push(value);
          }

          var points = [];
          for (var i = 1; i < total.length; i++) {
            points[i] = total[i] - total[i-1];
          }
          labels.shift();
          points.shift();

          project.chartData = {
            labels: labels,
            datasets: [
              {
                label: "Events",
                fillColor: "rgba(220,220,220,0.2)",
                strokeColor: "rgba(220,220,220,1)",
                pointColor: "rgba(220,220,220,1)",
                pointStrokeColor: "#fff",
                pointHighlightFill: "#fff",
                pointHighlightStroke: "rgba(220,220,220,1)",
                data: points
              }
            ]
          };
        })
      },
      addSupportContract: function(project) {
        $rootScope.$broadcast('adjustCurrentProject', project);
        $state.go('appstore.store', {category: 'support'});
      }
    });

    controllerScope.__proto__ = new EventController();
  }
})();
<commit_msg>Remove SPL from cost collector (SAAS-703)<commit_after>'use strict';

(function() {
  angular.module('ncsaas')
    .service('baseEventListController', [
      'baseControllerListClass', 'eventsService', 'EVENTTYPE', baseEventListController]);

  function baseEventListController(baseControllerListClass, eventsService, EVENTTYPE) {
    var ControllerListClass = baseControllerListClass.extend({
      EVENTTYPE: EVENTTYPE,

      init:function() {
        this.service = eventsService;
        this.searchFieldName = 'search';
        this.searchFilters = [
          {
            name: 'event_type',
            title: 'Logged in',
            value: EVENTTYPE.auth_logged_in_with_username
          },
          {
            name: 'event_type',
            title: 'Project creation',
            value: EVENTTYPE.project_creation_succeeded
          },
          {
            name: 'event_type',
            title: 'Organization creation',
            value: EVENTTYPE.customer_creation_succeeded
          }
        ];
        this._super();
      }
    });

    return ControllerListClass;
  }

  angular.module('ncsaas')
    .controller('EventListController', [
      '$scope',
      'baseEventListController',
      'currentStateService',
      'ENV',
      EventListController]);

  function EventListController(
    $scope,
    baseEventListController,
    currentStateService,
    ENV) {
    var controllerScope = this;
    var EventController = baseEventListController.extend({
      init:function() {
        this.controllerScope = controllerScope;
        this.cacheTime = ENV.dashboardEventsCacheTime;
        this._super();

        $scope.$on('currentCustomerUpdated', this.onCustomerUpdate.bind(this));
      },

      onCustomerUpdate: function() {
        this.getList();
      },

      getList: function(filter) {
        var vm = this;
        var fn = this._super.bind(vm);
        return currentStateService.getCustomer().then(function(customer) {
          vm.service.defaultFilter.scope = customer.url;
          fn(filter);
        });
      }
    });

    controllerScope.__proto__ = new EventController();
  }

  angular.module('ncsaas')
    .controller('CustomerAlertsListController', [
      '$scope',
      'baseControllerListClass',
      'currentStateService',
      'alertsService',
      'ENTITYLISTFIELDTYPES',
      CustomerAlertsListController]);

  function CustomerAlertsListController(
    $scope,
    baseControllerListClass,
    currentStateService,
    alertsService,
    ENTITYLISTFIELDTYPES) {
    var controllerScope = this;
    var controllerClass = baseControllerListClass.extend({
      init: function() {
        this.controllerScope = controllerScope;
        this.service = alertsService;
        this._super();

        this.entityOptions = {
          entityData: {
            noDataText: 'No alerts yet'
          },
          list: [
            {
              name: 'Message',
              propertyName: 'message',
              type: ENTITYLISTFIELDTYPES.noType
            }
          ]
        };

        $scope.$on('currentCustomerUpdated', this.onCustomerUpdate.bind(this));
      },

      onCustomerUpdate: function() {
        this.getList();
      },

      getList: function(filter) {
        var vm = this;
        var fn = this._super.bind(vm);
        filter = filter || {};
        return currentStateService.getCustomer().then(function(customer) {
          vm.service.defaultFilter.aggregate = 'customer';
          vm.service.defaultFilter.uuid = customer.uuid;
          fn(filter);
        })
      }
    });

    controllerScope.__proto__ = new controllerClass();
  }

  angular.module('ncsaas')
    .controller('DashboardIndexController', [
      '$scope',
      '$stateParams',
      'baseControllerClass',
      DashboardIndexController]);

  function DashboardIndexController($scope, $stateParams, baseControllerClass) {
    var controllerScope = this;
    var EventController = baseControllerClass.extend({
      init: function() {
        $scope.activeTab = $stateParams.tab || 'activity';
      }
    });

    controllerScope.__proto__ = new EventController();
  }

  angular.module('ncsaas')
    .controller('DashboardCostController', [
      '$scope',
      'baseControllerClass',
      'priceEstimationService',
      'blockUI',
      DashboardCostController]);

  function DashboardCostController(
    $scope,
    baseControllerClass,
    priceEstimationService,
    blockUI) {
    var controllerScope = this;
    var EventController = baseControllerClass.extend({
      init: function() {
        this.controllerScope = controllerScope;

        $scope.$on('currentCustomerUpdated', this.onCustomerUpdate.bind(this));
        this.onCustomerUpdate();
        blockUI.start();
      },

      onCustomerUpdate: function() {
        var vm = this;
        priceEstimationService.pageSize = 1000;
        priceEstimationService.getList().then(function(rows) {
          vm.processChartData(rows);
          vm.processTableData(rows);
        });
      },

      processChartData: function(rows) {
        var labels = [];
        var totals = [];
        rows.forEach(function(row) {
          if (row.scope_type == 'customer') {
            labels.unshift(moment(row.month, 'MM').format('MMMM'));
            totals.unshift(row.total);
          }
        });
        blockUI.stop();

        this.chartOptions = {
          bezierCurve: false,
          responsive: true,
          animationEasing: "linear"
        };

        this.costData = {
          labels: labels,
          datasets: [
            {
              fillColor: "rgba(123, 166, 196,0.5)",
              strokeColor: "rgba(123, 166, 196,1)",
              pointColor: "rgba(123, 166, 196,1)",
              pointStrokeColor: "#fff",
              pointHighlightFill: "#fff",
              pointHighlightStroke: "rgba(123, 166, 196,1)",
              data: totals
            }
          ]
        };
      },

      processTableData: function(rows) {
        var results = {};
        for (var i = 0; i < rows.length; i++) {
          var row = rows[i];
          var date = moment(row.month, 'MM').format('MMMM') + ' ' + row.year;
          if (!results.hasOwnProperty(date)) {
            results[date] = {
              total: 0,
              projects: [],
              services: [],
              resources: []
            }
          }
          if (row.scope_type == 'customer') {
            results[date].total = row.total;
          }
          if (row.scope_type == 'project') {
            results[date].projects.push(row);
          }
          if (row.scope_type == 'resource') {
            results[date].resources.push(row);
          }
          if (row.scope_type == 'service') {
            results[date].services.push(row);
          }
        }
        var table = [];
        for (var date in results) {
          var row = results[date];
          table.push({
            date: date,
            total: row.total,
            projects: row.projects,
            services: row.services,
            resources: row.resources
          });
        }
        if (table.length > 0) {
          table[0].selected = true;
          table[0].activeTab = 'services';
        }
        this.table = table;
      }
    });

    controllerScope.__proto__ = new EventController();
  }

  angular.module('ncsaas')
    .controller('DashboardActivityController', [
      'baseControllerClass',
      '$scope',
      '$rootScope',
      '$state',
      'projectsService',
      'alertsService',
      'eventsService',
      'eventStatisticsService',
      'resourcesCountService',
      'currentStateService',
      'ENV',
      '$window',
      DashboardActivityController]);

  function DashboardActivityController(
    baseControllerClass,
    $scope,
    $rootScope,
    $state,
    projectsService,
    alertsService,
    eventsService,
    eventStatisticsService,
    resourcesCountService,
    currentStateService,
    ENV,
    $window) {
    var controllerScope = this;
    var EventController = baseControllerClass.extend({
      showGraph: true,
      init:function() {
        this.controllerScope = controllerScope;
        this.cacheTime = ENV.dashboardEventsCacheTime;
        this._super();
        this.activeTab = 'activity';
        this.chartOptions = {
          responsive: true,
          scaleShowVerticalLines: false,
          scaleShowGridLines: false,
          bezierCurve: false
        };

        $scope.$on('currentCustomerUpdated', this.onCustomerUpdate.bind(this));
        this.onCustomerUpdate();
        this.resizeControl();
      },
      resizeControl: function() {
        var vm = this;

        var window = angular.element($window);
        window.bind('resize', function () {
          vm.showGraph = false;
          setTimeout(function() {
            vm.showGraph = true;
            $scope.$apply();
          }, 0);
          $scope.$apply();
        });
      },
      selectProject: function (project) {
        if (project) {
          project.selected =! project.selected;
          this.getProjectResources(project);
          this.getProjectEvents(project);
        }
      },
      onCustomerUpdate: function() {
        this.getCustomerProjects();
        this.getCustomerEvents();
        this.getCustomerAlerts();
      },
      getCustomerAlerts: function () {
        var vm = this;
        currentStateService.getCustomer().then(function(customer) {
          alertsService.getList({'aggregate': 'customer', 'uuid': customer.uuid}).then(function(response) {
            vm.alerts = response;
          })
        })
      },
      getCustomerEvents: function () {
        var vm = this;
        currentStateService.getCustomer().then(function(customer) {
          eventsService.getList({'scope': customer.url}).then(function(response) {
            vm.events = response;
          })
        })
      },
      getCustomerProjects: function() {
        var vm = this;
        projectsService.getList().then(function(response) {
          vm.projects = response;
          for (var i = 0; i < vm.projects.length; i++) {
            vm.projects[i].selected = false;
          }
          vm.selectProject(vm.projects[0]);
        });
      },
      getProjectResources: function (project) {
        if (project.count) {
          return;
        }
        project.count = {};
        project.count.services = project.services.length;
        resourcesCountService.users({'project': project.uuid}).then(function(count) {
          project.count.users = count;
        });
        resourcesCountService.resources({
          'project_uuid': project.uuid,
          'resource_type': ENV.resourceFilters.VMs
        }).then(function(count) {
          project.count.resources = count;
        });
        resourcesCountService.alerts({'scope': project.url}).then(function(count) {
          project.count.alerts = count;
        });
      },
      getProjectEvents: function (project) {
        if (project.chartData) {
          return;
        }
        var end = moment.utc().unix();
        var count = 7;
        var start = moment.utc().subtract(count + 1, 'days').unix();
        eventStatisticsService.getList({
          'scope': project.url,
          'start': start,
          'end': end,
          'points_count': count + 1
        }).then(function(response) {
          var labels = [];
          var total = [];
          for (var i = 0; i < response.length; i++) {
            var date = moment.unix(response[i].point);
            var day = date.format('dddd');
            var value = response[i].object.count;
            labels.push(day);
            total.push(value);
          }

          var points = [];
          for (var i = 1; i < total.length; i++) {
            points[i] = total[i] - total[i-1];
          }
          labels.shift();
          points.shift();

          project.chartData = {
            labels: labels,
            datasets: [
              {
                label: "Events",
                fillColor: "rgba(220,220,220,0.2)",
                strokeColor: "rgba(220,220,220,1)",
                pointColor: "rgba(220,220,220,1)",
                pointStrokeColor: "#fff",
                pointHighlightFill: "#fff",
                pointHighlightStroke: "rgba(220,220,220,1)",
                data: points
              }
            ]
          };
        })
      },
      addSupportContract: function(project) {
        $rootScope.$broadcast('adjustCurrentProject', project);
        $state.go('appstore.store', {category: 'support'});
      }
    });

    controllerScope.__proto__ = new EventController();
  }
})();
<|endoftext|>


<commit_before>/**
 * The MIT License (MIT)
 * Copyright (c) 2016 Krypto Fin ry and the FIMK Developers
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of
 * this software and associated documentation files (the "Software"), to deal in
 * the Software without restriction, including without limitation the rights to
 * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
 * the Software, and to permit persons to whom the Software is furnished to do so,
 * subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 * */
(function () {
'use strict';
var module = angular.module('fim.base');

module.config(function($routeProvider) {
  $routeProvider.when('/merchant/:recipient?/:amountNQT?/:deadline?/:description?/:message?/:assetId?/', {
    templateUrl: 'partials/merchant-terminal.html',
    controller: 'MerchantTerminalController'
  });
});

module.controller('MerchantTerminalController', function ($scope, $rootScope, nxt, $routeParams, plugins,$q) {

  $scope.paramRecipient     = $routeParams.recipient;
  $scope.paramAmountNQT     = $routeParams.amountNQT;
  $scope.paramDeadline      = $routeParams.deadline;
  $scope.paramDescription   = $routeParams.description;
  $scope.paramMessage       = $routeParams.message;
  $scope.assetId            = $routeParams.assetId;

  $scope.amountNXT          = nxt.util.convertToNXT($scope.paramAmountNQT);
  $scope.recipientName      = '';
  $scope.success            = false;

  var api                   = nxt.get($scope.paramRecipient);
  $scope.symbol             = api.engine.symbol;

  $scope.loading = true;

  var promises = [
    api.engine.socket().getAccount({account: $scope.paramRecipient}).then(function (data) {
      $scope.$evalAsync(function () {
        $scope.recipientName = data.accountName||data.accountEmail;
        if ($scope.recipientName == $scope.paramRecipient) {
          $scope.recipientName = '';
        }
      });
    })
  ];
  if ($scope.assetId) {
    promises.push(
      api.engine.socket().callAPIFunction({requestType:'getAsset', asset: $scope.assetId}).then(function (data) {
        $scope.$evalAsync(function () {
          $scope.asset = data;
          console.log(data)
        });
      })
    );
  }
  $q.all(promises).then(function () {
    $scope.$evalAsync(function () {
      $scope.loading = false;
    });
  });

  $scope.payNow = function () {
    var args = {};
    if ($scope.asset){
      args = {
        asset: $scope.asset.asset,
        recipient: $scope.paramRecipient,
        quantity:nxt.util.convertNQT($scope.paramAmountNQT, 8)
      };
      if ($scope.paramMessage) {
        args.txnMessage = $scope.paramMessage;
        args.txnMessageType = 'to_recipient';
      }

      $rootScope.executeTransaction('transferAsset', args).then(
        function (items) {
          console.log(items)
          if (items) {
            $scope.$evalAsync(function () {
              $scope.success = true;
            });
          }
        }
      );
    }else{
      args = {
        recipient: $scope.paramRecipient,
        amountNXT: nxt.util.convertNQT($scope.paramAmountNQT, 8),
        deadline: $scope.paramDeadline
      };
      if ($scope.paramMessage) {
        args.txnMessage = $scope.paramMessage;
        args.txnMessageType = 'to_recipient';
      }

      $rootScope.executeTransaction('sendMoney', args).then(
        function (items) {
          if (items) {
            $scope.$evalAsync(function () {
              $scope.success = true;
            });
          }
        }
      );
    }
  }

  $scope.signin = function () {
    $rootScope.loginWizard('signin', {}, false /* stay on same url */);
  }

});
})();
<commit_msg>Add redirect and status url support for merchant terminal<commit_after>/**
 * The MIT License (MIT)
 * Copyright (c) 2016 Krypto Fin ry and the FIMK Developers
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of
 * this software and associated documentation files (the "Software"), to deal in
 * the Software without restriction, including without limitation the rights to
 * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
 * the Software, and to permit persons to whom the Software is furnished to do so,
 * subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 * */
(function () {
'use strict';
var module = angular.module('fim.base');

module.config(function($routeProvider) {
  $routeProvider.when('/merchant/:recipient?/:amountNQT?/:deadline?/:description?/:message?/:assetId?/:urls*', {
    templateUrl: 'partials/merchant-terminal.html',
    controller: 'MerchantTerminalController'
  });
});

/**
 * The final urls parameter consists of a redirect url and status url delimitted by a |
 *
 * Included urls must be escaped with encodeURIComponent, this can be done from the browser
 * address bar. Enter javascript:encodeURIComponent("http://google.com/search?q=redirect")
 * in the address bar and hit enter.
 *
 * Example: urls with redirect and status.
 *
 * http%3A%2F%2Fgoogle.com%2Fsearch%3Fq%3Dredirect|http%3A%2F%2Fgoogle.com%2Fsearch%3Fq%3Dstatus
 *
 * Example: urls with only a status
 *
 * |http%3A%2F%2Fgoogle.com%2Fsearch%3Fq%3Dstatus
 *
 * Example: redirect and status
 * http://localhost:9001/#/merchant/FIM-BA8U-LVXC-WBFT-49C4S/100000000/1440/Send%20money/Message%20text/15249019093105168329/http%3A%2F%2Fgoogle.com%2Fsearch%3Fq%3Dredirect|http%3A%2F%2Fgoogle.com%2Fsearch%3Fq%3Dstatus
 *
 * Example: status only
 * http://localhost:9001/#/merchant/FIM-BA8U-LVXC-WBFT-49C4S/100000000/1440/Send%20money/Message%20text/15249019093105168329/|http%3A%2F%2Fgoogle.com%2Fsearch%3Fq%3Dstatus
 **/

module.controller('MerchantTerminalController', function ($scope, $rootScope, nxt, $routeParams, plugins, $q, $http) {

  $scope.paramRecipient     = $routeParams.recipient;
  $scope.paramAmountNQT     = $routeParams.amountNQT;
  $scope.paramDeadline      = $routeParams.deadline;
  $scope.paramDescription   = $routeParams.description;
  $scope.paramMessage       = $routeParams.message;
  $scope.assetId            = $routeParams.assetId;

  $scope.amountNXT          = nxt.util.convertToNXT($scope.paramAmountNQT);
  $scope.recipientName      = '';
  $scope.success            = false;

  var api                   = nxt.get($scope.paramRecipient);
  $scope.symbol             = api.engine.symbol;

  $scope.loading = true;

  var promises = [
    api.engine.socket().getAccount({account: $scope.paramRecipient}).then(function (data) {
      $scope.$evalAsync(function () {
        $scope.recipientName = data.accountName||data.accountEmail;
        if ($scope.recipientName == $scope.paramRecipient) {
          $scope.recipientName = '';
        }
      });
    })
  ];
  if ($scope.assetId) {
    promises.push(
      api.engine.socket().callAPIFunction({requestType:'getAsset', asset: $scope.assetId}).then(function (data) {
        $scope.$evalAsync(function () {
          $scope.asset = data;
        });
      })
    );
  }
  $q.all(promises).then(function () {
    $scope.$evalAsync(function () {
      $scope.loading = false;
    });
  });

  $scope.payNow = function () {
    var args = {};
    if ($scope.asset){
      args = {
        asset: $scope.asset.asset,
        recipient: $scope.paramRecipient,
        quantity:nxt.util.convertNQT($scope.paramAmountNQT, 8)
      };
      if ($scope.paramMessage) {
        args.txnMessage = $scope.paramMessage;
        args.txnMessageType = 'to_recipient';
      }

      $rootScope.executeTransaction('transferAsset', args).then(
        function (items) {
          if (items) {
            $scope.$evalAsync(function () {
              $scope.success = true;
              sendTransactionStatus();
            });
          }
        }
      );
    }else{
      args = {
        recipient: $scope.paramRecipient,
        amountNXT: nxt.util.convertNQT($scope.paramAmountNQT, 8),
        deadline: $scope.paramDeadline
      };
      if ($scope.paramMessage) {
        args.txnMessage = $scope.paramMessage;
        args.txnMessageType = 'to_recipient';
      }

      $rootScope.executeTransaction('sendMoney', args).then(
        function (items) {
          if (items) {
            $scope.$evalAsync(function () {
              $scope.success = true;
              sendTransactionStatus();
            });
          }
        }
      );
    }
  }

  $scope.signin = function () {
    $rootScope.loginWizard('signin', {}, false /* stay on same url */);
  }

  function sendTransactionStatus() {
    var url = ($routeParams.urls||"").split('|')[1];
    if (url) {
      $http({method:'GET',url:url}).finally(function () {
        maybeRedirect();
      })
    }
    else {
      maybeRedirect();
    }
  }

  function maybeRedirect() {
    var url = ($routeParams.urls||"").split('|')[0];
    if (url) {
      window.location = url;
    }
  }

});
})();
<|endoftext|>