<%!
import splunk
import logging
import hashlib
import os.path
import splunk.appserver.mrsparkle.lib.i18n as i18n
import splunk.appserver.mrsparkle.lib.filechain as filechain
import cherrypy
from mako.exceptions import RichTraceback
from splunk.appserver.mrsparkle.lib import util
from splunk.appserver.mrsparkle.lib.eai import cpQuoteEntity
logger = logging.getLogger('splunk.appserver.templates.lib')
import splunk.appserver.mrsparkle.lib.module as module

modules = module.moduleMapper.getInstalledModules()
isLite = util.isLite()
%>

<%namespace name="helpers" file="//view/_helpers.html" import="*"/>


<%def name="add_script_block()">
    <%
    if attributes.get('script_blocks', None) is None:
        attributes['script_blocks'] = []
    attributes['script_blocks'].append(capture(caller.body))
    %>
</%def>

<%def name="fillform(form_defaults, form_errors)">
    <%
    from formencode import htmlfill
    context.write(htmlfill.render(capture(caller.body), form_defaults, form_errors, auto_insert_errors=False))
    %>
</%def>

<%def name="get_script_blocks()">
    % if attributes.get('script_blocks'):
    <script type="text/javascript">
    % for script_block in attributes.get('script_blocks', []):
    //<![CDATA[
        ${script_block} \
    //]]>
    % endfor
    </script>
    % endif
</%def>

## DO NOT USE compile flag - here only to maintain compatibility with customer templates
<%def name="script_tags(files, compile=False)">
    <% seen = attributes.setdefault('script_tags_seen', set()) %>
	<%
        disable_messenger = cherrypy.session.get('sessionKey', None) is None
        minify_js = splunk.util.normalizeBoolean(cherrypy.config.get('minify_js'))
	%>
    % for file in files:
        % if minify_js and not file.startswith('/static/app/') and not file.startswith('/config?') and not file.endswith('init.js') and not file.endswith('highcharts.js'): 
            % if 'common.min.js' not in seen:
                % if disable_messenger:
                    <script type="text/javascript">
                        var DISABLE_MESSENGER = true;
                    </script>
                % endif
                <script type="text/javascript" src="${make_url('/static/js/common.min.js')}"></script> \
                <% seen.add('common.min.js') %>
            % endif
            % if '/modules/' in file:
                <%
                    basename = 'modules-' + filechain.generate_file_list_hash(files) + '.min.js'
                %>
                % if basename not in seen:
                     <% filechain.chain_modules_js(files) %>
                    <script type="text/javascript" src="${make_url(['modules', basename])}"></script> \
                    <% seen.add(basename) %>
                % endif
            % endif
        % elif file not in seen:
            <script type="text/javascript" src="${make_url(file)}"></script> \
            <% seen.add(file) %>
        % endif
    % endfor
</%def>

## DO NOT USE compile flag - here only to maintain compatibility with customer templates
<%def name="stylesheet_tags(files, compile=False, media=None)">
    <%
        seen = attributes.setdefault('stylesheet_tags_seen', set())
        minify_css = splunk.util.normalizeBoolean(cherrypy.config.get('minify_css'))
    %>
    % for file in files:
        % if minify_css and '/modules/' in file:
            <%
                basename = 'modules-' + filechain.generate_file_list_hash(files) + '.min.css'
            %>
            % if basename not in seen:
                 <% filechain.chain_modules_css(files) %>
                <link rel="stylesheet" href="${make_url(['modules', basename])}" ${'' if media is None else 'media="%s" ' % media}/> \
                <% seen.add(basename) %>
            % endif
        % elif file not in seen:
            <link rel="stylesheet" href="${make_url(file)}" ${'' if media is None else 'media="%s" ' % media}/> \
            <% seen.add(file) %>
        % endif
     % endfor
</%def>

<%def name="traceback(header=None, parent_element_class_name='traceback', row_highlight_class_name='active', max_lines=5)">
    <%
    tback = RichTraceback()
    line = tback.lineno
    if tback.source:
        lines = tback.source.split('\n')
    else:
        lines = None
    %>
    <div class="${parent_element_class_name}">
        <h2>${header if header else "Error!"}</h2>
        <h3>${str(tback.error.__class__.__name__)|h}: ${str(tback.error)|h}</h3>
        % if lines:
            <table cellpadding="0" cellspacing="0">
                % for index in range(max(0, line-(max_lines-1)), min(len(lines), line+max_lines)):
                    <tr ${'class="'+row_highlight_class_name+'"' if index + 1 == line else ''}>
                        <td>${index + 1}</td>
                        <td><pre>${lines[index] | h}</pre></td>
                    </tr>
                % endfor
            </table>
        % endif
        <dl>
            % for (filename, lineno, function, line) in tback.reverse_traceback:
                <dt>${filename}, line ${lineno}:</dt>
                <dd>${line | h}</dd>
            % endfor
        </dl>
    </div>
</%def>

<%def name="generate_select_options(optionArray, selectedValue=None)">
    % for pair in optionArray:
        <% sel = ' selected="1"' if selectedValue != None and unicode(pair[0], 'utf-8') == unicode(selectedValue, 'utf-8') else '' %> \
<option value="${pair[0]|h}"${sel}>${pair[1] | h}</option> \
    % endfor
</%def>

<%def name="generate_radio_options(optionArray, formName, disabled=None, selectedValue=None)">
    % for pair in optionArray:
        <% sel = ' checked ' if selectedValue != None and pair[0] == selectedValue else '' %> \
        <input type="radio" name="${formName}" value="${pair[0]|h}" ${sel} ${' disabled="true" ' if disabled != None and disabled == 'true' else ''}/> ${pair[1] | h} <br/>
    % endfor
</%def>

<%def name="getSavedSearch(module, savedSearchName, useHistory=False, namespace=None, owner=None, nativeObjectMode=None)">
<%
    jsonSearch = None
    jobNotFoundMessage = 'Module %(module)s: Could not find a previously run search for saved search "%(savedSearchName)s".'
    savedSearchNotFoundMessage = 'Module %(module)s: Could not find a saved search named "%(savedSearchName)s".'
    quoteExceededMessage = 'Module %(module)s: There are too many searches running; unable to dispatch "%(savedSearchName)s".'

    try : 
        savedSearchObject = splunk.search.getSavedSearch(
            label = savedSearchName,
            namespace = namespace,
            owner = owner
        )
        # if decomp isn't supported, return decomp fail
	if not splunk.util.normalizeBoolean(cherrypy.config.get('support_decomposition')):
           q = util.layPiping(savedSearchObject["qualifiedSearch"])
           jsonSearch = {
                "fullSearch" : q,
                "baseSearch" : q,
                "intentions": [],
                "decompositionFailed": True,
                "s": savedSearchObject.getLink('alternate'),
                "name": savedSearchObject.name,
                "earliest": savedSearchObject.get('dispatch.earliest_time'),
                "latest": savedSearchObject.get('dispatch.latest_time')
            }
        else:
           jsonSearch = splunk.appserver.mrsparkle.util.resurrectFromSavedSearch(
               savedSearchObject = savedSearchObject,
               hostPath = splunk.mergeHostPath(),
               namespace = namespace,
               owner = owner
           )

        useHistory = unicode(useHistory).capitalize()
        if (useHistory in ["Auto", "None", "True"]) :
            if useHistory == "None":
                logger.warn("useHistory == None is being depreciated, please use Auto instead.")
         
            historySearch = 'name=scheduler* OR name=rt_scheduler*'

            # for real-time, not scheduled searches try to use an already running instance of the search
            if not splunk.util.normalizeBoolean(savedSearchObject.get('is_scheduled')) and \
               savedSearchObject.get('dispatch.earliest_time')                         and \
               savedSearchObject.get('dispatch.earliest_time').startswith('rt') :
                historySearch = 'isDone=0 AND isRealTimeSearch=1 AND isZombie=0 AND isFinalized=0'


            try:
                # Note that we never submit anything other than useHistory="true". 
                # this is because its problematic to let the python dispatch the search for us.
                # instead if there's no job run by the scheduler, we return the other context data and let the 
                # client dispatch the search itself.
                job = splunk.search.getJobForSavedSearch(
                    savedSearchName,
                    useHistory="True", 
                    namespace=namespace,
                    owner=owner,
                    search=historySearch,
                    historyURI= savedSearchObject.getLink("history")
                )
                if (job) :
                    jsonSearch["job"] = job.toJsonable(timeFormat='unix')
                    
                elif useHistory == "True":
                    helpers.message('error', jobNotFoundMessage % {'savedSearchName': savedSearchName, 'module': module['id']})

            except splunk.RESTException, e:
            
                # Payment Required!
                # Get a job by using useHistory = True
                if e.statusCode == 402:
                    logger.warn("Could not retrieve the job history for the saved search '%s' because the current license does not allow it." % savedSearchName)
                    helpers.message("info", _("This view references scheduled searches that do not run automatically in Free Splunk. Please wait while they run now."))
                else:
                    raise e


            except splunk.BadRequest, e:
                logger.exception(e)
                if len(e.extendedMessages) > 0:
                    for msg in e.extendedMessages:
                        logger.error(msg['text'])
                        helpers.message(msg['type'].lower(), msg['text'])
                else:
                    helpers.message('error', jobNotFoundMessage % {'savedSearchName': savedSearchName, 'module': module['id']})
            
    except splunk.ResourceNotFound, e:
        logger.exception(e)
        if nativeObjectMode!='SimpleDashboard': 
            helpers.message('error', savedSearchNotFoundMessage % {'savedSearchName': savedSearchName, 'module': module['id']})
        
    except splunk.QuotaExceededException, e:
        logger.warn(str(e))
        helpers.message('warn', quoteExceededMessage % {'searchName': savedSearchName, 'module': module['id']})
%>
<%call expr="add_script_block()">
    % if jsonSearch:
        Splunk.Module.loadParams.${module['id']}.jsonSearch = ${json_decode(jsonSearch)};
    % else:
        Splunk.Module.loadParams.${module['id']}.jsonSearch = null;
    % endif
</%call>
</%def>

<%def name="csrf_hidden_input()">
<input type="hidden" name="splunk_form_key" value="${util.getFormKey()|h}" />
</%def>


<%def name="render_exception(e)">
    <span class="exception_name">${e.msg if hasattr(e, 'msg') else e | h}</span>
        % if hasattr(e, 'extendedMessages') and e.extendedMessages:
            &#8212;
            % for item in e.extendedMessages:
            <span class="exception_message">${item['text'] | h}</span>
            % endfor
        % endif
</%def>



<%def name="manager_save_search_link(namespace, id, name, label=None)">
    <a href="${make_url(['manager', namespace, 'saved', 'searches', cpQuoteEntity(name, urlquote=False)], _qs=dict(app=namespace, search=name, uri=id, action='edit')) | h}" target="_blank" class="spl-icon-external-link-xsm">${label or name | h}</a>.
</%def>

<%def name="wizard_errors(header, errors)">
    % if len(errors)>0:
        <h2 class="error">${header|h}</h2>
        <ul class="errors">
        % for error in errors:
            <li>${error|h}</li>
        % endfor
        </ul>
    % endif
</%def>

<%def name="wizard_save_search_form(app, saved_search, display_share=True, display_acceleration=False)">
    <%self:wizard_errors header="${_('Your search could not be saved.')}" errors='${saved_search.errors}'/>
    <%self:csrf_hidden_input/>
    % if saved_search.id:
        <input type="hidden" name="id" value="${saved_search.id | h}"/>
    % endif
    <input type="hidden" name="ui.vsid" value="${saved_search.ui.vsid or '' |h}" />
    <input type="hidden" name="ui.dispatch_view" value="${saved_search.ui.dispatch_view or '' |h}" />
    <input type="hidden" name="ui.display_view" value="${saved_search.ui.display_view or '' |h}" />
    <input type="hidden" name="search" value="${saved_search.search or '' |h}" />
    <input type="hidden" name="dispatch.earliest_time" value="${saved_search.dispatch.earliest_time or '' |h}" /> 
    <input type="hidden"  name="dispatch.latest_time" value="${saved_search.dispatch.latest_time or '' |h}" />
    <table class="saveSearchForm">
        <tbody>
            <tr>
                <td class="col1"><label for="name"><span class="required">*</span> ${_('Name')}</label></td>
                <td class="col2"><input type="text" name="name" maxlength="100" value="${saved_search.name or '' |h}" id="name" ${'disabled="disabled"' if saved_search.id else ''}/></td>
            </tr>
            % if display_share:
                
                <tr>
                    <td class="col1 share"><span class="orphanLabel">${_('Share')}</span></td>
                    <td class="col2">
                    	<fieldset><legend class="hiddenLabel">${_('Share')}</legend>
                        <ul>
                            <li>
                                <input type="radio" name="sharing" value="user" id="private" class="sharing typeRadio" ${'checked="checked"' if saved_search.metadata.sharing=='user' or saved_search.id is None else ''}/>
                                <label for="private">${_('Keep search private')}</label>
                            </li>
                            <li>
                                <input type="radio" name="sharing" value="app" id="share" class="sharing typeRadio" ${'checked="checked"' if saved_search.metadata.sharing=='app' else ''}/>
                                <label for="share">${_('Share as read-only to all users of current app')}</label>
                            </li>
                            <li class="note">
                                ${_('<em>Additional permission settings available in </em><br/><strong>Settings &raquo; Searches, reports, and alerts</strong>')}
                            </li>
                        </ul>
                        </fieldset>
                    </td>
                
                </tr>
            % endif
  
            % if display_acceleration and saved_search.auto_summarize.enabled is not None and saved_search.auto_summarize.can_summarize: 
              <tr>
                    <td class="col1 share"><span class="orphanLabel">${_('Acceleration')}</span></td>
                    <td class="col2">
                        <%self:acceleration_options/>
                    </td>
             </tr>
           % endif
        </tbody>
    </table>
    <%self:add_script_block>
    $(document).ready(function(){
        var searchName = $('#name')[0];
        if(searchName.disabled==false){
            searchName.focus();
        }else{
            $('#search').focus();
        }
    });

    </%self:add_script_block>
</%def>

<%def name="acceleration_options()">
	<fieldset>
		<div>
		<legend class="hiddenLabel">${_('Acceleration')}</legend>
		<input type="checkbox" class="checkbox" name="auto_summarize.enabled" id="auto_summarize" value="True" ${'checked="checked"' if saved_search.auto_summarize.enabled else ''}/> 
		<label for="auto_summarize">${_('Accelerate this search')}</label>
		    <p class="note">
			${_('<em>May increase storage and processing costs</em>')}
                        <a href="${generateSelfHelpLink('learnmore.search.acceleration')}" class="spl-icon-external-link-xsm" target="_blank">${_('Learn more.')}</a>
		    </p> 
		</div>
	    <div id="auto_summarize_options">
                <%
                    timespan_options = [{'value':'1m', 'label':'1 min'}, {'value':'1h', 'label':'1 hour'}, {'value':'1d', 'label':'1 day'}, {'value':'7d', 'label':'1 week'}]
                    earliest_time_options = [{'value':'-1d@h', 'label':'1 Day'}, {'value':'-7d@d', 'label':'7 Days'}, {'value':'-1mon@d', 'label':'1 Month'}, {'value':'-3mon@d', 'label':'3 Months'}, {'value':'-1y@d', 'label':'1 Year'}, {'value':'0', 'label':'All Time'}]
                %>
		<div style="display:none; float:left; width:100px; border-left-style:solid; border-left-width:5px; border-left-color:999; padding-left:5px; margin-top:3px; margin-left:10px;">
		    <label> ${_('Granularity')}</label> <br/>
		    <select  name="auto_summarize.timespan" >
                    % for option in timespan_options:
		        <option value="${option.get('value')}" ${'selected="1"' if (option.get('value') == saved_search.auto_summarize.timespan) else ''}>${option.get('label')}</option>
	            % endfor
		    </select>
		</div>
		<div style="float:left; width:100px; border-left-style:solid; border-left-width:5px; border-left-color:999; padding-left:5px; margin-top:3px; margin-left:10px;">
		    <label> ${_('Summary Range')}</label> <br/>
		    <select  name="auto_summarize.earliest_time" >
                    % for option in earliest_time_options:
		        <option value="${option.get('value')}" ${'selected="1"' if (option.get('value') == saved_search.auto_summarize.earliest_time) else ''}>${option.get('label')}</option>
	            % endfor
		    </select>
		</div>
		<div style="clear:both"/>
                % if not saved_search.auto_summarize.is_good_summarization_candidate:
                <div style="color:#FF0000; font-weight:bold;">Warning: Splunkd has determined that turning on acceleration will likely not benefit this search.</div>
                % endif
	    </div>
	</fieldset>
    <%self:add_script_block>
    $(document).ready(function(){
        $('#auto_summarize').click(toggle_autosummarize); 
        toggle_autosummarize();  
        
    });

    function toggle_autosummarize(){
        if ($('#auto_summarize').attr('checked')) { 
             $('#auto_summarize_options').show(); 
        } else {
             $('#auto_summarize_options').hide(); 
        }
            
    }
    </%self:add_script_block>
</%def>


<%def name="get_summarization_status(tsum)">
    <% 
     from splunk.appserver.mrsparkle.lib import util 

     complete = int(float(tsum.complete)*100)
     completeString = _('%s%% Complete') % complete
     mod_time    = util.timeToAgoStr(int(tsum.mod_time))
     mod_time_string = " <span class='access_time'>" + _('Updated: ') + mod_time + "</span>" if mod_time else ''
     mod_time_seconds =util.timeToAgoSeconds(int(tsum.mod_time)) 
     isUpdatedALongTimeAgo = util.timeToAgoSeconds(int(tsum.mod_time)) > 600
     

     if tsum.is_inprogress:
         completeString = "<div class='running'>" + _('Building summary - ') + str(complete) + "%</div>"   
     else: 
         isNotStarted = len(tsum.run_stats) == 0 and not tsum.is_inprogress 
         isNotEnoughData = int(tsum.size) == 0 and len(tsum.run_stats) > 0 and len(tsum.last_error) == 0
         if isNotStarted:
             completeString = _('Summarization not started')
         elif isNotEnoughData: 
             completeString = '<span class="icon_small yellow_warning_small">&nbsp;</span>' + _("Not enough data to summarize.")
         elif tsum.is_suspended: 
             completeString = '<span class="icon_small yellow_warning_small">&nbsp;</span>' + _("Suspended.") 
         elif isUpdatedALongTimeAgo: 
             completeString = _('Pending (Built summary - ') + str(complete) + "%)"
         elif complete == 100:
             completeString = _('Complete')

     completeString += mod_time_string 
     return completeString
    %>
</%def>


<%def name="wizard_steps(items, active)">
    <ul class="steps splClearfix">
        % for idx, item in enumerate(items):
            <% idx = idx + 1 %>
            <li${' class="active"'if active==idx else ''}>
                <em>${idx}</em>
                <h2>${item | h}</h2>
            </li>
        % endfor
    </ul>
    <div class="splClearFix"></div>
</%def>

<%def name="wizard_cancel_delete(action, id, dashboard_id=None)">
    <form method="post" action="${action | h}" class="cancel">
        ${csrf_hidden_input()}
        <input type="hidden" name="id" value="${id | h}"/>
        % if dashboard_id:
        	<input type="hidden" name="dashboard_id" value="${dashboard_id | h}"/>
        % endif
        <button class="splButton-secondary" type="submit">${_('Cancel')}</button>
    </form>
</%def>

<%def name="wizard_schedules()">
    <%
    return [
        ('* * * * *', _('minute')),
        ('*/5 * * * *', _('5 minutes')),
        ('*/15 * * * *', _('15 minutes')),
        ('*/30 * * * *', _('30 minutes')),
        ('0 * * * *', _('hour')),
        ('0 */4 * * *', _('4 hours')),
        ('0 */12 * * *', _('12 hours')),
        ('0 0 * * *', _('day at midnight')),
        ('0 18 * * *', _('day at 6pm')),
        ('0 0 * * 6', _('Saturday at midnight'))
    ]
    %>
</%def>

<%def name="wizard_ok()">
    <ul class="buttons splClearfix">
        <li class="right">
            <a class="splButton-primary cancel" href="#">
                <span>${_('OK')}</span>
            </a>
        </li>
        <script type="text/javascript">
           $(document).ready(function(){
             $(".splButton-primary").focus();
            });
        </script>
    </ul> 
</%def>

<%def name="summarization_verification_form(verifyLink, estimated_verify_time_fast, estimated_verify_time_thorough, selectedValue='', error=None)">
    <div class="verificationWizard">
        <div style="margin-bottom: 10px;" class="note">
            ${_('Verification tests a percentage of the summary to ensure the data is valid. ')}
            <a href="${generateSelfHelpLink('learnmore.search.acceleration')}" class="spl-icon-external-link-xsm" target="_blank">${_('Learn more.')}</a></label>
        </div>
        <hr>
        <%self:csrf_hidden_input/>
        <%self:wizard_errors header="${_('Your verification could not be started.')}" errors='${error if error else []}'/>
               <input type="hidden" name="verifyLink" value="${verifyLink | h}"/> 
                        <fieldset>
                        <ul>
                            <li>
                                <% sel = ' checked ' if selectedValue=='fast' or selectedValue==''  else '' %> 
                                <input type="radio" name="mode" value="fast" ${sel} $id="fast" class="typeRadio"/> 
                                <label for="fast">${_('Fast verification')}</label>
                                <div class="checkboxNote note">${_('Quickly verify the data at the cost of thoroughness.')}</div>
                                <div class="checkboxNote note">${_('Estimated time to verify: ')}${secondsToFormattedTime(estimated_verify_time_fast)} </div>
                            </li>
                            <br/>
                            <li>
                                <% sel = ' checked ' if selectedValue=='thorough'  else '' %> \
                                <input type="radio" name="mode" value="thorough" ${sel} id="thorough" class="typeRadio"/> 
                                <label for="thorough">${_('Thorough verification')}</label>
                                <div class="checkboxNote note">${_('Thoroughly verify the data at the cost of speed. ')}</div>
                                <div class="checkboxNote note">${_('Estimated time to verify: ')}${secondsToFormattedTime(estimated_verify_time_thorough)} </div>
                            </li>
                        </ul>
                        </fieldset>
     <br/>
     <br/>
     <br/>
     </div>
</%def>
 

<%def name="prettyInt(num)">
    <%
    s = '%d' % num
    groups = []
    while s and s[-1].isdigit():
        groups.append(s[-3:])
        s = s[:-3]
    return s + ','.join(reversed(groups))
    %>
</%def>

<%def name="timeToDateStr(num)">
    <%
   import time
 
   if not num: 
       return ''

   num = int(num)
   dateStr = time.ctime(num) if num > 0 else 'N/A' 
   return dateStr
    %>
</%def>



<%def name="secondsToFormattedTime(t)">
    <%
    result = 'Never'
    if t > 0:
        result = ''
        if t > 60: 
            if t/86400 >= 1:
                days = int(t/86400)
                result = "%dd " % (days)
                t =  t % 86400
               
            hours = int(t/3600)
            mins  = int( (t%3600)/60)
               
            if len(result) > 0 or hours > 0:
                result +=  ("%dh " % (hours))
                  
            result +=  ("%dm " % (mins))
        else:
            result = "< 1 min"
           
    return result
    %>
</%def>



<%def name="summarization_verification_form_step2(verifyLink, max_buckets, max_time, max_ratio, auto_delete, total_buckets,  error)">
    <div class="verificationWizard">
        <%self:csrf_hidden_input/>
        <%self:wizard_errors header="${_('Your verification could not be started.')}" errors='${error if error else []}'/>
        <div style="margin-bottom: 10px;">
            This summary spans ${total_buckets} buckets. 
        </div>
        <hr>
        <input type="hidden" name="verifyLink" value="${verifyLink | h}"/> 
                        <fieldset>
                        <ul>
                            <li>
                                <label for="max_buckets">${_('Maximum buckets to verify without fail before quitting')}
                                <a href="${generateSelfHelpLink('learnmore.search.acceleration')}" class="spl-icon-external-link-xsm" target="_blank">${_('Learn more.')}</a></label>
                                <input type="text" value="${max_buckets | h}"  name="max_buckets"/> 
                            </li>
                            <li>
                                <label for="max_time">${_('Maximum time to spend verifying each bucket')}</label>
                                <input type="text"  value="${max_time | h}" name="max_time"/> 
                                <div class="note"> ${_('Enter # of seconds. 0 means no time limit.')} </div>
                            </li>
                            <li>
                                <label for="max_ratio">${_('Max ratio of data in each bucket to verify')}</label>
                                <input type="text"  value="${max_ratio | h}" name="max_ratio"/> 
                                <div class="note">${_('Enter a decimal between 0 and 1. Larger numbers take longer to verify.')} </div>
                            </li>
                            <li>
                                <div> If verification fails </div>
                                <div style="margin-left:5px; margin-top:5px;">
                                    <% sel = '' if auto_delete and auto_delete == 'off' else ' checked ' %>
                                    <input type="checkbox" ${sel} name="auto_delete"/>
                                    <label for="auto_delete">${_('Delete the related summaries.')}</label>
                                    <div class="checkboxNote note"> On a per-bucket basis </div>
                                </div>
                            </li>
                        </ul>
                        </fieldset>
        <br/>
        <br/>
    </div>
</%def>

<%def name="sort_link(label, url, params, sort_by)">
    <%
        css_class = 'splSortNone'
        qs = {}
        qs.update(params)
        if qs.get('sort_by') == sort_by:
            if qs.get('sort_dir') is None or qs.get('sort_dir') == 'desc':
                qs['sort_dir'] = 'asc'
                css_class = 'splSortAsc'
            else:
                qs['sort_dir'] = 'desc'
                css_class = 'splSortDesc'
        else:
            qs['sort_by'] = sort_by
            qs['sort_dir'] = 'desc'
    %>
    <a href="${make_url(url, _qs=qs)}" class="sortable"><span>${label|h}</span><span class="${css_class|h}"></span></a>
</%def>

<%def name="get_application_css(app)">
    <%
    from lib.apps import local_apps
    css = None
    local_app = local_apps.apps.get(app, None)
    if local_app:
        local_app.setdefault('static', {}).setdefault('css', [])
        if local_app['static']['css'].count('application.css')>0:
            css = '/static/app/%s/application.css' % app
    %>
    % if css:
        <link rel="stylesheet" href="${make_url(css)}" />
    % endif
    <% appPatches = local_apps[app]['patch'].get('css', []) %>
    % for patch in appPatches:
         <link rel="stylesheet" href="${make_url(patch)}" />
    % endfor
</%def>

<%def name="pretty_bucket_search_state(searchState)">
    % if searchState == "Searchable":
        ${_("Raw data and Index files")}
    % else:
        ${_("Raw data only")}
    % endif
</%def>

<%def name="generate_slave_pagination(countPerPage, offset, numItems, search, ns, pwnr)">
     
        ## EAI pagination
        <%
        import copy
        import splunk.appserver.mrsparkle.lib.paginator as paginator

        try:
            count = int(countPerPage)
        except Exception, e:
            count = 25
        try:
            offset = int(offset)
        except Exception, e:
            offset = 0
        try:
            totalResults = int(numItems)
        except Exception, e:
            totalResults = 0
        newOffset = count + offset
        prevOffset = 0 if ( (offset - count) < 0 ) else (offset - count) 
        spanStart = 1 if offset == 0 else (offset + 1)
        spanEnd = ( offset + count )
        sel = ""
        resPerPage = [10, 25, 50, 100]
        if (spanEnd > totalResults):
            lastPage = True
            spanEnd = totalResults
            
        max_pages = 10    
        pager = paginator.Google(totalResults, count, max_pages=max_pages, item_offset=offset)
        page_range = []
        for page in pager.page_range:
            page_range.append(
                {
                    'number':page,
                    'offset':pager.page_item_offset(page),
                    'active':pager.is_active_page(page)
                }
            )
    
        %>
 
    <div style="background-color: #FFFFFF; padding-top: 10px; border-color: #FFFFFF;" class="eaiResultsPageControls splClearfix">
            % if totalResults > 0:

			<p class="eaiResultsCount eaiResultsPageControl">${ungettext('Showing <span>%(first)s-%(last)s</span> of %(total)s item', 'Showing <span>%(first)s-%(last)s</span> of %(total)s items', totalResults) % dict(first=spanStart, last=spanEnd, total=totalResults)}</p>
            % endif

	        <div class="Paginator eaiResultsPageControl">
               <% page_opts = {'search':search, 'count':countPerPage, 'offset':offset, 'ns':ns, 'pwnr':pwnr}%>
                <div class="ResultsContainer">
                    <ul>
                        <li class="previous">
                            % if ( (spanStart > count) or (spanStart > 1) ):
                                <% page_opts['offset'] = prevOffset %>
                                <a href="${make_url('', _qs=page_opts, translate=False)}"> <%doc>TRANS: Previous page</%doc>&laquo; ${_('prev')} </a>
                            % endif
                        </li>
                        % for page in page_range:
                            % if page['active']:
                        <li class="page active">
                            % else:
                        <li class="page">
                            % endif
                            <% page_opts['offset'] = page['offset'] %>
                            <a href="${make_url('', _qs=page_opts, translate=False)}">${page['number']}</a>
                        </li>
                        % endfor
                        <li class="next">
                            % if spanEnd < totalResults:
                                <% page_opts['offset'] = newOffset %>
                                <a href="${make_url('', _qs=page_opts, translate=False)}"> <%doc>TRANS:Next page</%doc>${_('next')} &raquo; </a>
                            % endif
                        </li>
                    </ul>
                </div>
            </div>
	</div> <!-- eaiResultsPageControls -->

</%def>


<%def name="generate_master_pagination(countPerPage, offset, numItems, search, ns, pwnr)">
      
        <form name="pagingControl" method="get">
          <input type="hidden" name="search" value="${search}"/>
          <input type="hidden" name="offset" value="${offset}"/>
          <input type="hidden" name="ns" value="${ns}"/>
          <input type="hidden" name="pwnr" value="${pwnr}"/>

     
        ## EAI pagination
        <%
        import copy
        import splunk.appserver.mrsparkle.lib.paginator as paginator

        try:
            count = int(countPerPage)
        except Exception, e:
            count = 25
        try:
            offset = int(offset)
        except Exception, e:
            offset = 0
        try:
            totalResults = int(numItems)
        except Exception, e:
            totalResults = 0
        newOffset = count + offset
        prevOffset = 0 if ( (offset - count) < 0 ) else (offset - count) 
        spanStart = 1 if offset == 0 else (offset + 1)
        spanEnd = ( offset + count )
        sel = ""
        resPerPage = [10, 25, 50, 100]
        if (spanEnd > totalResults):
            lastPage = True
            spanEnd = totalResults
            
        max_pages = 10    
        pager = paginator.Google(totalResults, count, max_pages=max_pages, item_offset=offset)
        page_range = []
        for page in pager.page_range:
            page_range.append(
                {
                    'number':page,
                    'offset':pager.page_item_offset(page),
                    'active':pager.is_active_page(page)
                }
            )
    
        %>
 
    <div style="background-color: #FFFFFF; padding-top: 10px; border-color: #FFFFFF;" class="eaiResultsPageControls splClearfix">
            % if totalResults > 0:
			<div class="eaiResultsPerPage eaiResultsPageControl">
                <label for="resultsPerPageSelect">${_('Results per page')}</label>
                <select name="count" class="short" onchange="document.pagingControl.submit()" id="resultsPerPageSelect">
                    % for i in resPerPage:
                        <%
                        if i == count:
                            sel = "selected='selected'"
                        else:
                            sel = ""
                        endif
                        %>
                        <option ${sel}>${i}</option>
                    % endfor
                    % if count not in resPerPage and count != 0:
                        <option disabled="disabled">---</option>
                        <option selected='selected'>${count | h}</option>
                    % endif
                </select>
            </div>

			<p class="eaiResultsCount eaiResultsPageControl">${ungettext('Showing <span>%(first)s-%(last)s</span> of %(total)s item', 'Showing <span>%(first)s-%(last)s</span> of %(total)s items', totalResults) % dict(first=spanStart, last=spanEnd, total=totalResults)}</p>
            % endif

	        <div class="Paginator eaiResultsPageControl">
               <% page_opts = {'search':search, 'count':countPerPage, 'offset':offset, 'ns':ns, 'pwnr':pwnr}%>
                <div class="ResultsContainer">
                    <ul>
                        <li class="previous">
                            % if ( (spanStart > count) or (spanStart > 1) ):
                                <% page_opts['offset'] = prevOffset %>
                                <a href="${make_url('', _qs=page_opts, translate=False)}"> <%doc>TRANS: Previous page</%doc>&laquo; ${_('prev')} </a>
                            % endif
                        </li>
                        % for page in page_range:
                            % if page['active']:
                        <li class="page active">
                            % else:
                        <li class="page">
                            % endif
                            <% page_opts['offset'] = page['offset'] %>
                            <a href="${make_url('', _qs=page_opts, translate=False)}">${page['number']}</a>
                        </li>
                        % endfor
                        <li class="next">
                            % if spanEnd < totalResults:
                                <% page_opts['offset'] = newOffset %>
                                <a href="${make_url('', _qs=page_opts, translate=False)}"> <%doc>TRANS:Next page</%doc>${_('next')} &raquo; </a>
                            % endif
                        </li>
                    </ul>
                </div>
            </div>
	</div> <!-- eaiResultsPageControls -->
    </form> 

</%def>

<%def name="generate_searchbar(search, ns, countPerPage, appOptionList, pwnrOptionList, pwnr)">

    <div class="adminContentList">
    <%
    nss = appOptionList
    pwnrs = pwnrOptionList
    %>

    <form name="searchControl" method="get">
        <input type="hidden" name="count" value="${countPerPage | h}"/>
        <div class="eaiFilterControls splClearfix">
            <div class="eaiFilterControl">
			% if nss is not None  and len(nss) > 0:
				<label for="appContextSelect">${_('App context')}</label>
				<select name="ns" onchange="document.searchControl.submit()" id="appContextSelect">
				  <option value="-">${_('All')}</option>
				  % for option in nss:
				  <option value="${option.get('value', '') | h}" ${'selected="selected"' if (option.get('value') == ns) else ''}>${option.get("label") | h}</option>
				  % endfor
				</select>
			% endif
              </div>
			% if pwnrs is not None and len(pwnrs) > 0:
			<div class="eaiFilterControl">
				<label for="ownerSelect">${_('Owner')}</label>
				<select name="pwnr" onchange="document.searchControl.submit()" id="ownerSelect">
					<option value="-" ${'selected="selected"'}>${_('Any')}</option>
					% for option in pwnrs:
					<option value="${option.get('value', '') | h}" ${'selected="selected"' if (option.get('value') == pwnr) else ''}>${option.get("label") | h}</option>
					% endfor
				</select>
			</div>
			% endif
			
	    	<div class="eaiFilterControl eaiSearchControl">
	            <input name="search" type="text" value='${search | h}' class="eaiFilter" id="searchInput"> <!-- js needs to go somewhere else-->
	            <input class="searchButton" value="" type="submit">
	        </div>
        </div>
 
     </div>
    </form>
</%def>
<%def name="generate_splunk_header()">
    <script type="text/javascript">
    $(function(){
        // this must not be in admin_lite.js because that is loaded by
        // the main manager page

        require([
            'views/shared/splunkbar/Master',
            'views/shared/litebar/Master',
            'views/shared/footer/Master',
            'models/shared/Application',
            'models/config',
            'models/services/server/ServerInfo',
            'models/shared/User',
            'collections/services/data/ui/Tours',
            'util/splunkd_utils'
        ], function(
            GlobalNav,
            LiteBar,
            FooterNav,
            ApplicationModel,
            configModel,
            ServerInfoModel,
            UserModel,
            ToursCollection,
            splunkd_utils
        ){
            var rootPath = $C.MRSPARKLE_ROOT_PATH;
            //root path cannot have leading slash
            rootPath = rootPath[0] === '/' ? rootPath.substring(1) : rootPath;

            var app = Splunk.util.getCurrentApp() == "UNKNOWN_APP" ? 'search' : Splunk.util.getCurrentApp(),
                owner = $C.USERNAME,
                ServerInfo = new ServerInfoModel(),
                ServerInfoDfd = ServerInfo.fetch(),
                UserModel = new UserModel({}, {serverInfoModel: ServerInfo}),
                UserModelDfd = UserModel.fetch({
                    data: {
                        app: app,
                        owner: owner
                    },
                    url: splunkd_utils.fullpath(UserModel.url + "/" + $C.USERNAME)
                }),
                tours = new ToursCollection(),
                toursDfd = tours.fetch({
                    data: {
                        app: app,
                        owner: owner,
                        count: -1
                    }
                });

            var applicationModel = new ApplicationModel({
                locale: $C.LOCALE,
                app: app,
                owner: $C.USERNAME,
                root: rootPath,
                page: '_admin'
            });

            var footer = FooterNav.create({
                model: {
                    application: applicationModel
                }
            }).render();

            var $container = $('.SplunkModule.AccountBar');
            $container.addClass('splunk-components');

            $container.removeClass('SplunkModule AccountBar');
            
            $.when(ServerInfoDfd, UserModelDfd, toursDfd).then(function(){
                % if isLite:
                    var header = LiteBar.create({
                        model: {
                            application: applicationModel,
                            config: configModel,
                            serverInfo: ServerInfo,
                            user: UserModel
                        },
                        collection: {
                            tours: tours
                        },
                        autoRender: true
                    });
                % else:
                    var header = GlobalNav.create({
                        model: {
                            application: applicationModel,
                            config: configModel,
                            serverInfo: ServerInfo
                        }
                    }).render();
                % endif
                $container.html(header.$el);
            });

            var $footerContainer = $('<div class="splunk-components" />');
            $footerContainer.append(footer.$el);
            $('body').append($footerContainer);
        });
    });
    </script>
</%def>
