<%@ page import="java.util.Date" %>
<%@ page import="ro.emid.common.utils.ObjectUtils" %>
<%@ page import="ro.emid.common.db.framework.ReportStatement" %>
<%@ page import="java.util.List" %>
<%@ page import="ro.emid.common.utils.pagination.PaginationController" %>
<%@ page import="ro.emid.common.db.AccessDB" %>
<%@ page import="ro.emid.common.utils.pagination.PaginationConstants" %>
<%@ page import="ro.emid.common.utils.sort.SortController" %>
<%@ page import="ro.emid.common.utils.sort.SortData" %>
<%@ page import="ro.emid.common.db.NomAccessDB" %>
<%@ page import="ro.emid.common.utils.StringUtils" %>
<%@ page import="java.io.File" %>
<%@ page import="java.util.Set" %>
<%@ page import="java.util.HashSet" %>
<%@ page import="ro.emid.common.db.CategoryAccessDB" %>
<%@ page import="ro.emid.incidente.IncidenteSessionUtils" %>
<%@ page import="ro.emid.common.types.*" %>
<%@ page import="ro.emid.incidente.util.RaportTop10InstalatiiExcelExporter" %>
<%@ page import="ro.emid.common.constants.*" %>
<%@ page import="ro.emid.common.utils.pagination.PaginationData" %>

<%@ include file="../incidente/declaratii.jsp"%>

<%!
    private static final org.apache.log4j.Logger LOG = org.apache.log4j.Logger.getLogger("raportTop10Instalatii_jsp");
    private static final java.text.SimpleDateFormat _df = new java.text.SimpleDateFormat("yyyyMMdd");
%>

<%!
    public static final int COD_ANS_LEA = 50;
    public static final int COD_ANS_LES = 51;

    private boolean exists(final String []arr, final String value){
        if( arr == null) return false;

        for (int i = 0; i < arr.length; i++) {
            if( arr[i] == null && value == null) return true;
            if( arr[i] != null && value != null && arr[i].equals( value)) return true;
        }
        return false;
    }
%>


<TABLE border=0 cellPading=0 cellSpacing=0 width="100%">
    <TR>
        <TD>
            <%@ include file="../header-localizare.jsp"%>
            <span class="slash">/</span> <A class="link" href="<%=AppConstants.APP_NAME%>?action=rapoarte">Rapoarte</A>
            <span class="slash">/</span> Raport top 10 instalatii (FI)
        </TD>
    </TR>
</TABLE>


<%
    final boolean toate = true;
//    boolean toate = ObjectUtils.getIntValue( request.getParameter("toate"), -1) == 1;
    final boolean statii = ObjectUtils.getIntValue( request.getParameter("statii"), -1) == 1;
    final boolean linii = ObjectUtils.getIntValue( request.getParameter("linii"), -1) == 1;
    final boolean posturi = ObjectUtils.getIntValue( request.getParameter("posturi"), -1) == 1;
    final boolean derivatii = ObjectUtils.getIntValue( request.getParameter("derivatii"), -1) == 1;
    final boolean bobine = ObjectUtils.getIntValue( request.getParameter("bobine"), -1) == 1;
    final boolean celule = ObjectUtils.getIntValue( request.getParameter("celule"), -1) == 1;
    final boolean bare = ObjectUtils.getIntValue( request.getParameter("bare"), -1) == 1;
    final boolean trafo = ObjectUtils.getIntValue( request.getParameter("trafo"), -1) == 1;

    final String lea = ObjectUtils.getStringValue( request.getParameter("lea"));
    final String les = ObjectUtils.getStringValue( request.getParameter("les"));

    final String[] ansambluri = request.getParameterValues("ansamblu");

    final Date dataStart = ObjectUtils.getDateValue( request.getParameter("data_start"), AppConstants.FORMAT_DATA);
    Date dataStop  = ObjectUtils.getDateValue( request.getParameter("data_stop"), AppConstants.FORMAT_DATA);
    if( dataStop == null) dataStop = new Date();

    if( dataStart != null) session.setAttribute( "raportTop10.dataStart", dataStart); else session.removeAttribute( "raportTop10.dataStart");
    if( dataStop  != null) session.setAttribute( "raportTop10.dataStop", dataStop); else session.removeAttribute("raportTop10.dataStop");

    final int advancedFilters = ObjectUtils.getIntValue(request.getParameter("advancedFilters"), 0);

    final int tipInstalatieReq = ObjectUtils.getIntValue( request.getParameter("tipInstalatie"), -1);
    final long idInstalatieReq = ObjectUtils.getLongValue(request.getParameter("idInstalatie"), -1);
    final String denInstalatieReq = StringUtils.getNullSafe( request.getParameter("denInstalatie"), "");

    int nivelTensiune = -1;
    if ( advancedFilters == 1 ){
        nivelTensiune = ObjectUtils.getIntValue( request.getParameter( "nivelTensiune"), -1);
    }

    List result = null;
    class Totaluri{
        long countIncidente;
        long durataIncidente;
        double energieNelivrata;
        double costMent;
        double costDaune;
        double costExpl;
        double costTotal;
    }

    Totaluri totaluri = null;

    final PaginationData pd = PaginationController.getPaginationData( request, 20);

    final SortData sd = SortController.getSortData( request, "CNT", "DESC" );

    final ro.emid.common.types.CategoryCheckData checkData = IncidenteSessionUtils.getCategoriiSelectate(session);

    StringBuffer sql = null;
    if( toate || statii || linii || posturi || derivatii || bobine || celule || bare || trafo){

        final StringBuffer filter = new StringBuffer();
        final StringBuffer filter2 = new StringBuffer();

        final Category filialaRaport = filiala;
        final Category sucursalaRaport = sucursala;
        final Category centruRaport = centruExploatare;

        if( filialaRaport != null ) session.setAttribute( "raportTop10.filiala", filialaRaport);
        if( sucursalaRaport != null ) session.setAttribute( "raportTop10.sucursala", sucursalaRaport);
        if( centruRaport != null ) session.setAttribute( "raportTop10.centru", centruRaport);


        if( idInstalatieReq > 0){
            filter2.append(" AND inst.ID = ").append( idInstalatieReq );
        }

        if( filialaRaport != null && filialaRaport.getId() > 0){
            filter.append(" AND i.FILIALA_ID = ").append( filialaRaport.getId());
        }

        if( sucursalaRaport != null && sucursalaRaport.getId() > 0){
            filter.append(" AND i.SUCURSALA_ID = ").append( sucursalaRaport.getId());
        }

        if( centruRaport != null && centruRaport.getId() > 0){
            filter.append(" AND i.SECTIE_ID = ").append( centruRaport.getId());
        }

        if ( dataStart != null){
            filter.append( " AND i.DATA >= TO_DATE('").append( AppConstants.format(dataStart)).append("', 'DD.MM.YYYY') " );
        }

        if ( dataStop != null){
            filter.append( " AND i.DATA <= TO_DATE('").append( AppConstants.format(dataStop)).append("', 'DD.MM.YYYY') " );
        }

        final StringBuffer liniiFilter = new StringBuffer();

        if ( !StringUtils.isZeroLength( lea) && !StringUtils.isZeroLength( les) ){
            liniiFilter.append(" AND upper( remove_multiple_spaces( inst.TIP_OB)) IN ('").append(lea).append("','").append(les).append("') ");
        } else if( !StringUtils.isZeroLength( lea)) {
            liniiFilter.append(" AND upper( remove_multiple_spaces( inst.TIP_OB)) = '").append(lea).append("' ");
        } else if( !StringUtils.isZeroLength( les)){
            liniiFilter.append(" AND upper( remove_multiple_spaces( inst.TIP_OB)) = '").append(les).append("' ");
        }

        if( nivelTensiune == 1){ //IT
            filter.append(" AND i.TENSIUNE >= 110");
            session.setAttribute( "raportTop10.nivelTensiune", new Integer( 1));
        } else if( nivelTensiune == 2){ //MT
            filter.append(" AND i.TENSIUNE < 110");
            session.setAttribute( "raportTop10.nivelTensiune", new Integer( 2));
        } else {
            session.removeAttribute( "raportTop10.nivelTensiune");
        }

        if( ansambluri != null && ansambluri.length > 0 ){
            final StringBuffer inCond = new StringBuffer();
            for (int i = 0; i < ansambluri.length; i++) {
                final String idAnsamblu = ansambluri[i];

                if( inCond.length() > 0) inCond.append(',');

                inCond.append( idAnsamblu);
            }

            filter.append( " AND i.ANSAMBLU_ID IN (").append( inCond).append(") ");
        }

        //{Checked Categories
        //Filiale

        long ids[] = checkData.getIdFiliale();
        String condition = " AND (";
        if( ids.length > 0){
            filter.append( condition);
            filter.append(" FILIALA_ID IN (");
            for (int i = 0; i < ids.length; i++) {
                final long id = ids[i];
                filter.append( id).append( i < ids.length - 1 ? ", " : "") ;
            }
            filter.append(") ");

            condition = " OR ";
        }

        ids = checkData.getIdSucursale();
        if( ids.length > 0){
            filter.append( condition);
            filter.append(" SUCURSALA_ID IN (");
            for (int i = 0; i < ids.length; i++) {
                final long id = ids[i];
                filter.append( id).append( i < ids.length - 1 ? ", " : "") ;
            }
            filter.append(") ");

            condition = " OR ";
        }

        ids = checkData.getIdCentre();
        if( ids.length > 0){
            filter.append( condition);
            filter.append(" SECTIE_ID IN (");
            for (int i = 0; i < ids.length; i++) {
                final long id = ids[i];
                filter.append( id).append( i < ids.length - 1 ? ", " : "") ;
            }
            filter.append(") ");
            condition = " OR ";
        }

        if( condition.equals(" OR ")){
            filter.append(')');  //for AND ( FILIALA_ID IN(...) OR SUCURSLA_ID IN (...) OR SECTIE_ID IN (...))
        }
        //}

        boolean addUnion = false;
        sql = new StringBuffer();

        if ( toate || statii){
            sql.append(" SELECT 1 AS TIP, inst.CE, inst.COD_LF AS LF_ID, inst.DESC_LF, COUNT(*) CNT, SUM( i.DURATA_INCIDENT) DURATA_INCIDENTE, SUM( i.ENERGIE_NELIVR) EN, SUM( i.CHELT_MENT) CM, SUM( i.CHELT_DAUNE) CD, SUM( i.CHELT_EXPLOATARE) CEXP, SUM( i.CHELT_MENT + i.CHELT_DAUNE + i.CHELT_EXPLOATARE) CT " + " FROM incidente i INNER JOIN LF inst on (" + " i.STATIE_COD = inst.COD_LF " + " AND isSelected( i.LINIE_ID) = 0" + " AND isSelected( i.DERIVATIE_ID) = 0" + " AND isSelected( i.BARA_ID) = 0" + " AND isSelected( i.BOBINA_ID) = 0" + " AND isSelected( i.CELULA_ID) = 0" + " AND isSelected( i.TRAFO_ID) = 0" + " AND isSelected( i.PAPT_ID) = 0 " + " )" + "   WHERE 0=0 ").append(filter).append(filter2).append(" GROUP BY 1, inst.CE, inst.COD_LF, inst.DESC_LF ");
            addUnion = true;
        }

        if( toate || linii){
            if( addUnion) sql.append(" UNION ");
            sql.append(" SELECT 2 AS TIP, inst.CE, inst.COD_LF AS LF_ID, inst.DESC_LF,  count(*) CNT, sum( i.DURATA_INCIDENT) DURATA_INCIDENTE, SUM( i.ENERGIE_NELIVR) EN, SUM( i.CHELT_MENT) CM, SUM( i.CHELT_DAUNE) CD, SUM( i.CHELT_EXPLOATARE) CEXP, SUM( i.CHELT_MENT + i.CHELT_DAUNE + i.CHELT_EXPLOATARE) CT \n" + " FROM incidente i INNER JOIN LF  inst on ( \n" + " i.LINIE_COD = inst.COD_LF \n" + " AND isSelected( i.STATIE_ID) = 0 \n" + " AND isSelected( i.DERIVATIE_ID) = 0 \n" + " AND isSelected( i.PAPT_ID) = 0 \n" + " AND isSelected( i.TRAFO_ID) = 0 \n" + " ) \n" + "   WHERE 0=0 ").append(filter).append(filter2).append(liniiFilter).append(" \n ").append(" GROUP BY 2, inst.CE, inst.COD_LF, inst.DESC_LF \n");
            addUnion = true;
        }

        if( toate || posturi){
            if( addUnion) sql.append(" UNION ");
            sql.append(" SELECT 3 AS TIP, inst.CE, inst.COD_LF AS LF_ID, inst.DESC_LF,  count(*) CNT, sum( i.DURATA_INCIDENT) DURATA_INCIDENTE, SUM( i.ENERGIE_NELIVR) EN, SUM( i.CHELT_MENT) CM, SUM( i.CHELT_DAUNE) CD, SUM( i.CHELT_EXPLOATARE) CEXP, SUM( i.CHELT_MENT + i.CHELT_DAUNE + i.CHELT_EXPLOATARE) CT \n" + " FROM incidente i INNER JOIN LF inst on (i.PAPT_COD = inst.COD_LF) \n" + "   WHERE 0=0 ").append(filter).append(filter2).append(" \n").append(" GROUP BY 3, inst.CE, inst.COD_LF, inst.DESC_LF \n");
            addUnion = true;
        }

        if( toate || bobine){
            if( addUnion) sql.append(" UNION ");
            sql.append(" SELECT 4 AS TIP, inst.CE, inst.NR_EQ AS LF_ID, inst.DESC_EQ AS DESC_LF,  count(*) CNT, sum( i.DURATA_INCIDENT) DURATA_INCIDENTE, SUM( i.ENERGIE_NELIVR) EN, SUM( i.CHELT_MENT) CM, SUM( i.CHELT_DAUNE) CD, SUM( i.CHELT_EXPLOATARE) CEXP, SUM( i.CHELT_MENT + i.CHELT_DAUNE + i.CHELT_EXPLOATARE) CT " + " FROM incidente i INNER JOIN EQ inst on (i.BOBINA_COD = inst.NR_EQ) " + "   WHERE 0=0 ").append(filter).append(filter2).append(" GROUP BY 4, inst.CE, inst.NR_EQ, inst.DESC_EQ ");
            addUnion = true;
        }

        if( toate || celule){
            if( addUnion) sql.append(" UNION ");
            sql.append(" SELECT 5 AS TIP, inst.CE, inst.NR_EQ AS LF_ID, inst.DESC_EQ AS DESC_LF,  count(*) CNT, sum( i.DURATA_INCIDENT) DURATA_INCIDENTE, SUM( i.ENERGIE_NELIVR) EN, SUM( i.CHELT_MENT) CM, SUM( i.CHELT_DAUNE) CD, SUM( i.CHELT_EXPLOATARE) CEXP, SUM( i.CHELT_MENT + i.CHELT_DAUNE + i.CHELT_EXPLOATARE) CT " + " FROM incidente i INNER JOIN EQ inst on (i.CELULA_COD = inst.NR_EQ) " + "   WHERE 0=0 ").append(filter).append(filter2).append(" GROUP BY 5, inst.CE, inst.NR_EQ, inst.DESC_EQ ");
            addUnion = true;
        }

        if( toate || bare){
            if( addUnion) sql.append(" UNION ");
            sql.append(" SELECT 6 AS TIP, inst.CE, inst.NR_EQ AS LF_ID, inst.DESC_EQ AS DESC_LF,  count(*) CNT, sum( i.DURATA_INCIDENT) DURATA_INCIDENTE, SUM( i.ENERGIE_NELIVR) EN, SUM( i.CHELT_MENT) CM, SUM( i.CHELT_DAUNE) CD, SUM( i.CHELT_EXPLOATARE) CEXP, SUM( i.CHELT_MENT + i.CHELT_DAUNE + i.CHELT_EXPLOATARE) CT" + " FROM incidente i INNER JOIN EQ inst on (i.BARA_COD = inst.NR_EQ) " + "   WHERE 0=0 ").append(filter).append(filter2).append(" GROUP BY 6, inst.CE, inst.NR_EQ, inst.DESC_EQ ");
            addUnion = true;
        }

        if( toate || derivatii){
            if( addUnion) sql.append(" UNION ");
            sql.append(" SELECT 7 AS TIP, inst.CE, inst.NR_EQ AS LF_ID, inst.DESC_EQ AS DESC_LF,  count(*) CNT, sum( i.DURATA_INCIDENT) DURATA_INCIDENTE, SUM( i.ENERGIE_NELIVR) EN, SUM( i.CHELT_MENT) CM, SUM( i.CHELT_DAUNE) CD, SUM( i.CHELT_EXPLOATARE) CEXP, SUM( i.CHELT_MENT + i.CHELT_DAUNE + i.CHELT_EXPLOATARE) CT \n" + " FROM incidente i INNER JOIN EQ inst on (i.DERIVATIE_COD = inst.NR_EQ) \n" + "   WHERE 0=0 ").append(filter).append(filter2).append(liniiFilter).append(" \n").append(" GROUP BY 7, inst.CE, inst.NR_EQ, inst.DESC_EQ \n");
            addUnion = true;
        }

        if( toate || trafo){
            if( addUnion) sql.append(" UNION ");
            sql.append(" SELECT 8 AS TIP, inst.CE, inst.NR_EQ AS LF_ID, inst.DESC_EQ AS DESC_LF,  count(*) CNT, sum( i.DURATA_INCIDENT) DURATA_INCIDENTE, SUM( i.ENERGIE_NELIVR) EN, SUM( i.CHELT_MENT) CM, SUM( i.CHELT_DAUNE) CD, SUM( i.CHELT_EXPLOATARE) CEXP, SUM( i.CHELT_MENT + i.CHELT_DAUNE + i.CHELT_EXPLOATARE) CT " + " FROM incidente i INNER JOIN EQ inst on (i.TRAFO_COD = inst.NR_EQ) " + "   WHERE 0=0 ").append(filter).append(filter2).append(" GROUP BY 8, inst.CE, inst.NR_EQ, inst.DESC_EQ ");
            addUnion = true;
        }



        sql.append(  "   ) t ");
        sql.append(  "    INNER JOIN CATEGORIES c ON (t.CE=c.COD_SAP) ");
        sql.append(  "    INNER JOIN CATEGORIES s ON (c.ID_PARENT=s.ID) ");
        sql.append(  "    INNER JOIN CATEGORIES f ON (s.ID_PARENT=f.ID) ");

        final StringBuffer listSql = new StringBuffer()
                .append( "SELECT * FROM (SELECT a.*, ROWNUM AS rn FROM (" +
                        "SELECT f.NAME AS FILIALA, s.NAME AS SUCURSALA, c.NAME AS CENTRU, t.TIP, t.LF_ID, t.DESC_LF, t.CNT, t.DURATA_INCIDENTE, t.EN, t.CM, t.CD, t.CEXP, t.CT FROM (")
                .append( sql)
                .append( "   ORDER BY ").append(sd.getColumnName()).append(' ').append( sd.getDirection())
                .append( " )a WHERE ROWNUM <= ").append( pd.getQueryEndIndex())
                .append( ") WHERE ").append( pd.getStartIndex()).append(" <= rn ");

        final ReportStatement report = new ReportStatement( listSql.toString());

        result = report.getListOfArrays("run raport");

        final StringBuffer countSql = new StringBuffer("SELECT COUNT(*) FROM (").append( sql);

        pd.setTotalRowsCount( AccessDB.getLong( countSql.toString(), "Count Linii raport top 10 instalatii").intValue());
        pd.setResultRowCount( result != null ? result.size() : 0);


        //calculare totaluri
        final StringBuffer totalsSql = new StringBuffer("SELECT sum(t.CNT), sum( t.DURATA_INCIDENTE), sum( t.EN), sum(t.CM), sum(t.CD), sum(t.CEXP), sum(t.CT) FROM (").append( sql);

        final List totalsResult = new ReportStatement( totalsSql.toString()).getListOfArrays("get totaluri");

        if(totalsResult != null) for (int i = 0; i < totalsResult.size(); i++) {
            final Object[] objects = (Object[]) totalsResult.get(i);

            int k = 0;
            totaluri = new Totaluri();
            totaluri.countIncidente = ObjectUtils.getIntValue( objects[ k++], 0);
            totaluri.durataIncidente = ObjectUtils.getIntValue( objects[ k++], 0);
            totaluri.energieNelivrata = ObjectUtils.getDoubleValue( objects[ k++], 0);
            totaluri.costMent = ObjectUtils.getDoubleValue( objects[ k++],0);
            totaluri.costDaune = ObjectUtils.getDoubleValue( objects[ k++],0);
            totaluri.costExpl = ObjectUtils.getDoubleValue( objects[ k++],0);
            totaluri.costTotal = ObjectUtils.getDoubleValue( objects[ k++], 0);
            break;
        }

        session.setAttribute("raportTop10InstalatiiFilter", filter);
    }


    String publicPath = null;
    if( sql != null && ObjectUtils.getIntValue( request.getParameter("toExport"), 0) == 1){

        final String root = AppConstants.PUBLIC_RESOURCE_PATH + File.separator + "raport";


        final String folder = _df.format( new java.util.Date());
        //cleanup...
        final File[]folders = new File( root).listFiles();
        if( folders != null) for (int i = 0; i < folders.length; i++) {
            final File file = folders[i];
            if( !file.getName().equals( folder)){
                final File[]d=file.listFiles();
                if( d!=null) for (int j = 0; j < d.length; j++) {
                    final File file1 = d[j];
                    file1.delete();
                }
                file.delete( );  //cleanup
            }
        }

        File f = new File( root, folder);
        if( !f.exists()) f.mkdir();

        final String strDataStart = AppConstants.format(dataStart);
        final String strDataStop  = AppConstants.format(dataStop);

        final String fileName = "Raport top 10 instalatii " + strDataStart + " - " + strDataStop + '_' + System.currentTimeMillis() + ".xls";
        final String privatePath = root + File.separator + folder + File.separator + fileName;

        publicPath = AppConstants.WEB_RESOURCE_PATH + "/raport/" + folder + '/' + fileName;

        f = new File( privatePath);
        if( f.exists()){
            f.delete();
        }

        final String templatePath = GlobalAppConstants.PRIVATE_PATH + File.separator+"template"+File.separator+"Raport top 10 Instalatii.xls";

        final RaportTop10InstalatiiExcelExporter exporter = new RaportTop10InstalatiiExcelExporter();
        exporter.begin( templatePath, privatePath);

        final StringBuffer sqlExport = new StringBuffer()
                .append( " SELECT f.NAME AS FILIALA, s.NAME AS SUCURSALA, c.NAME AS CENTRU, t.TIP, t.LF_ID, t.DESC_LF, t.CNT, t.DURATA_INCIDENTE, t.EN, t.CM, t.CD, t.CEXP, t.CT FROM (")
                .append( sql)
                .append( "  ORDER BY ").append( sd.getColumnName()).append(' ').append( sd.getDirection());


        final ReportStatement report = new ReportStatement( sqlExport.toString());

        List resultExport = report.getListOfArrays("run export top 10");

        exporter.export( resultExport);

        resultExport = null;

        exporter.end();
    }

    final Nomenclator[] noms = NomAccessDB.getAllNom( NomConstants.NOM_ANSAMBLURI);

%>

<table width="100%">
<tr><td>
<form name="zaforma" action="<%=AppConstants.APP_NAME%>?action=raport-top10-fi" method="post" onsubmit="this.<%=PaginationConstants.JSP_RESET%>.value='true';">
<input type="hidden" name="toExport" value="0">
<input type="hidden" name="<%=PaginationConstants.JSP_RESET%>" value="">
<%=SortController.initSort( sd)%>
<table class="gsaptd" width="100%" id="tableCuCheckboxuri">
    <tr>
        <td align="left">
            <% final int cols = 3; %>
            <% final int n = noms.length; %>
            <table border="0" width="100%">
                <tr valign="top">
                    <td>
                            <% for ( int k = 0; k < n; k++ ) {
                                final Nomenclator nom = noms[ k]; %>
                            <% if ( k % (  n/cols) == 0 ) { %>
                    <td>
                            <% } %>

                        <nobr>
                            <% final boolean checked = exists( ansambluri, String.valueOf( nom.getId())); %>
                            <input type="checkbox" name="ansamblu" value="<%=nom.getId()%>" id="ansamblu<%=k%>" <%=(checked ? "checked" : "")%>
                                <% if( nom.getCod() == COD_ANS_LEA) { %>
                                   onclick="toggleLeaFilters( this)"
                                <% }else if( nom.getCod() == COD_ANS_LES) { %>
                                   onclick="toggleLesFilters( this)"
                                <% } %>
                                    ><label for="ansamblu<%=k%>"><nobr><%=nom.getDescriere()%></nobr></label>

                            <% if( nom.getCod() == COD_ANS_LEA) { %>

                            <select id="lea"  name="lea" style="font-size:10px; <%=!checked ? "display:none;" : ""%>">
                                <option></option>
                                <option <%="LEA 6 KV".equals(lea) ? "selected" : ""%> >LEA 6 KV</option>
                                <option <%="LEA 10 KV".equals(lea) ? "selected" : ""%> >LEA 10 KV</option>
                                <option <%="LEA 20 KV".equals(lea) ? "selected" : ""%> >LEA 20 KV</option>
                                <option <%="LEA 35 KV".equals(lea) ? "selected" : ""%> >LEA 35 KV</option>
                                <option <%="LEA 110 KV".equals(lea) ? "selected" : ""%> >LEA 110 KV</option>
                            </select>
                            <% } else if( nom.getCod() == COD_ANS_LES){ %>

                            <select id="les"  name="les" style="font-size:10px; <%=!checked ? "display:none;" : ""%>">
                                <option></option>
                                <option <%="LES 6 KV".equals(les) ? "selected" : ""%> >LES 6 KV</option>
                                <option <%="LES 10 KV".equals(les) ? "selected" : ""%> >LES 10 KV</option>
                                <option <%="LES 20 KV".equals(les) ? "selected" : ""%> >LES 20 KV</option>
                                <option <%="LES 110 KV".equals(les) ? "selected" : ""%> >LES 110 KV</option>
                            </select>
                            <% } %>
                        </nobr><br>
                            <% } %>
                </tr>
            </table>
            <hr/>

            &nbsp;&nbsp;<span style="font-weight:bold;" title="Instalatie">Instalatie:</span>
            <input type="hidden" id="idInstalatie" name="idInstalatie"  value="<%=idInstalatieReq%>" />
            <input type="hidden" id="tipInstalatie" name="tipInstalatie" value="<%=tipInstalatieReq%>" />
            <input type="hidden" id="isLF" name="isLF" value="" />
            <input type="text" id="denInstalatie" name="denInstalatie" size="50" value="<%=StringUtils.getNullSafe( denInstalatieReq)%>" />

            &nbsp;&nbsp;<span style="font-weight:bold;" title="Nivel tensiune">Nivel:</span>
            <input type="radio" name="nivelTensiune" value="1" id="ntIT" <%=nivelTensiune == 1 ? "checked" : ""%> /><label for="ntIT">IT</label>
            <input type="radio" name="nivelTensiune" value="2" id="ntMT" <%=nivelTensiune == 2 ? "checked" : ""%>/><label for="ntMT">MT</label>
            <input type="radio" name="nivelTensiune" value="3" id="ntTOATE" <%=nivelTensiune == 3 ? "checked" : ""%>/><label for="ntTOATE">Toate</label>

            &nbsp;&nbsp;
            <span title="Perioada producerii deranjamentelor" style="font-weight:bold;">Perioada:</span>
            <input type="text" id="data_start" name="data_start" size="8" value="<%=AppConstants.format( dataStart)%>" /> <a href="#" id="trigger_data_start" ><img src="<%=AppConstants.WEB_RESOURCE_PATH + "/images/cal.gif"%>" width="16" height="16" border="0" alt="Apasa pt. a selecta data."></a>&nbsp;&nbsp;-&nbsp;&nbsp;
            <input type="text" id="data_stop" name="data_stop" size="8" value="<%=AppConstants.format( dataStop)%>" /> <a href="#" id="trigger_data_stop" ><img src="<%=AppConstants.WEB_RESOURCE_PATH + "/images/cal.gif"%>" width="16" height="16" border="0" alt="Apasa pt. a selecta data."></a>

            <%if( user.getIeLevel() < ro.emid.common.constants.RoleConstants.NIVEL_CENTRU){ %>
            <A href="#" onClick="openCheckCategorii(); return false" class="link"><IMG alt="Click pentru a selecta mai multe sucursale/C.E." border=0 width=12 height=13 hspace=3 src="<%= AppConstants.WEB_RESOURCE_PATH + "/images/icon_mini_search.gif" %>"></A>
            <script type="text/javascript">
                var checkCategoriiWindow = null;
                function openCheckCategorii(){
                    if( checkCategoriiWindow) checkCategoriiWindow.close();
                    checkCategoriiWindow = window.open('<%=AppConstants.APP_NAME%>?action=checkCategorie','checkCategorie', 'width=800 height=620, scrollbars=yes,status=yes,resizable=yes,top=10,left=50,dependent=yes,alwaysRaised=yes');
                }
            </script>
            <% } %>

            &nbsp;&nbsp;<input type="submit" value="Aplica">
            &nbsp;<input type="button" value="Export" onclick="document.zaforma.toExport.value = '1'; document.zaforma.submit();" />

            <% if( checkData.someDataChecked()){

                final StringBuffer strCategorii = new StringBuffer("");
                final long[] idCentre = checkData.getIdCentre();
                final Set sucursaleSelectate = new HashSet();
                final Set filialeSelectate = new HashSet();
                for (int i = 0; i < idCentre.length; i++) {
                    final long id = idCentre[i];
                    final Category c = CategoryAccessDB.getById(id);
                    if (c != null) {
                        final Category s = CategoryAccessDB.getById(c.getId_parent());
                        if (s != null) {
                            final Category f = CategoryAccessDB.getById(s.getId_parent());
                            if (f != null) {
                                if (strCategorii.length() > 0) strCategorii.append("<br>");
                                strCategorii.append(f.getName()).append(", ").append(s.getName()).append(", ").append(c.getName());

                                sucursaleSelectate.add(new Long(s.getId()));
                                filialeSelectate.add(new Long(f.getId()));
                            }
                        }
                    }
                }

                final long[] idSucursale = checkData.getIdSucursale();
                for (int i = 0; i < idSucursale.length; i++) {
                    final long id = idSucursale[i];
                    if( !sucursaleSelectate.contains( new Long( id))){
                        final Category s = CategoryAccessDB.getById( id );
                        if( s != null){
                            final Category f = CategoryAccessDB.getById( s.getId_parent());
                            if( f != null){
                                if( strCategorii.length() > 0) strCategorii.append("<br>");
                                strCategorii.append(f.getName()).append(", ").append(s.getName());
                            }
                        }
                    }
                }

                final long[] idFiliale = checkData.getIdFiliale();
                for (int i = 0; i < idFiliale.length; i++) {
                    final long id = idFiliale[i];
                    if( !filialeSelectate.contains( new Long( id))){
                        final Category f = CategoryAccessDB.getById( id);
                        if( f != null){
                            if( strCategorii.length() > 0) strCategorii.append("<br>");
                            strCategorii.append(f.getName());
                        }
                    }
                }
            %>

            <br/>
            <%=strCategorii%>
            <% } %>
        </td>
    </tr>
    <tr id="rowAdvancedFilters" style="display:none">
        <td colspan="2">

        </td>
    </tr>
</table>

<script type="text/javascript">

    function toggleLeaFilters(oCheck){
        var selectu = $("lea");
        if( oCheck.checked){
            Element.show( selectu);
        }else{
            Element.hide( selectu);
        }
    }

    function toggleLesFilters(oCheck){
        var selectu = $("les");
        if( oCheck.checked){
            Element.show( selectu);
        }else{
            Element.hide( selectu);
        }
    }

    var plusuAdvanced = new Plus( "plusAdvancedFilters", "rowAdvancedFilters", function(){
        $("advancedFilters").value= ( plusuAdvanced.getStatus() == PlusConstants.STATUS_MINUS ? "1" : "0");
    });

    <% if( advancedFilters == 1){ %>
    plusuAdvanced.setMinus();
    <% } %>
</script>

<TABLE id="table" border=1 cellPadding=2 cellSpacing=1 width="100%" class="gSAPTHEAD" style="BACKGROUND-COLOR: white; margin-top:5px">
    <TR noSelect="true">
        <TH rowspan="2" class="gsapthead" noWrap width="10px">#</TH>
        <TH rowspan="2" class="gsapthead" noWrap >Instalatie</TH>
        <TH rowspan="2" class="gsapthead" noWrap width="1%">Sucursala</TH>
        <TH rowspan="2" class="gsapthead" noWrap width="2%">CE</TH>
        <TH rowspan="2" class="gsapthead" noWrap width="100px" style="text-decoration:underline"> <nobr> <%=SortController.printSortableColumn( "Nr. incidente", "CNT", sd)%></nobr></TH>
        <TH rowspan="2" class="gsapthead" noWrap width="100px" style="text-decoration:underline"> <nobr> <%=SortController.printSortableColumn( "Durata Incidente", "DURATA_INCIDENTE", sd)%></nobr></TH>
        <TH             class="gsapthead" noWrap style="text-decoration:underline"> <%=SortController.printSortableColumn( "Energie nelivr.", "EN", sd)%></TH>
        <TH colspan="4" class="gsapthead" noWrap >Cheltuieli (ron)</TH>
        <TH rowspan="2" class="gsapthead" noWrap width="50px"> Cauze </TH>
    </TR>
    <tr noSelect="true">
        <TH class="gsapthead" noWrap align="center">(kWh)</TH>
        <TH class="gsapthead" noWrap align="center" style="text-decoration:underline"> <%=SortController.printSortableColumn( "Ment.", "CM", sd)%></TH>
        <TH class="gsapthead" noWrap align="center" style="text-decoration:underline"> <%=SortController.printSortableColumn( "Daune", "CD", sd)%></TH>
        <TH class="gsapthead" noWrap align="center" style="text-decoration:underline"> <%=SortController.printSortableColumn( "Expl.", "CEXP", sd)%></TH>
        <TH class="gsapthead" noWrap align="center" style="text-decoration:underline"> <%=SortController.printSortableColumn( "Total.", "CT", sd)%></TH>
    </tr>
    <% if( result == null ) { %>
    <tr>
        <td colspan="15">Selectati categoria sau categoriile de instalatii</td>
    </tr>
    <% } else { %>
    <% if( result.size() == 0){ %>
    <tr>
        <td colspan="12">Nu exista fise de incident conform filtrului specificat.</td>
    </tr>
    <% }else {%>
    <% for (int i = 0; i < result.size(); i++) {
        final Object[] objects = (Object[]) result.get(i);

        final String numeFiliala   = (String) objects[ 0];
        final String numeSucursala = (String) objects[ 1];
        final String numeCentru    = (String) objects[ 2];

        final int tipInstalatie =  Integer.parseInt( objects[3].toString());

        String denTipInstalatie = "-";

        switch ( tipInstalatie){
            case 1: denTipInstalatie = "Statie"; break;
            case 2: denTipInstalatie = "Linie"; break;
            case 3: denTipInstalatie = "PA-PT"; break;
            case 4: denTipInstalatie = "Bobina"; break;
            case 5: denTipInstalatie = "Celula"; break;
            case 6: denTipInstalatie = "Bara"; break;
            case 7: denTipInstalatie = "Derivatie"; break;
            case 8: denTipInstalatie = "Trafo"; break;
            default:
                denTipInstalatie = "necunoscut";
                break;
        }

        final String idInstalatie = objects[4].toString();
        final String descInstalatie = objects[5].toString();
        final String countIncidente = objects[6].toString();

        final long durataIncidente = Integer.parseInt( objects[7].toString());

        final double energieNelivrata = Double.parseDouble( objects[8].toString());
        final double costMent = Double.parseDouble( objects[9].toString());
        final double costDaune = Double.parseDouble( objects[10].toString());
        final double costExpl = Double.parseDouble( objects[11].toString());

        final double costTotal = Double.parseDouble( objects[12].toString());
    %>

    <tr>
        <td align="center"><%=i+1%></td>
        <td>
            <label title="<%=denTipInstalatie%> - <%=descInstalatie%>"><nobr><%=descInstalatie%></nobr></label>
        </td>
        <td nowrap>
            <label title="Sucursala instalatie">
                <%=numeSucursala%>
            </label>
        </td>
        <td nowrap>
            <label title="Centru Exploatare instalatie">
                <%=numeCentru%>
            </label>
        </td>
        <td align="center">
            <a class="link" title="Click pentru vizualizare incidente" href="javascript: openIncidenteByTipInstalatie( '<%=tipInstalatie%>', '<%=idInstalatie%>')">
                <%=countIncidente%>
            </a>
        </td>
        <td align="right">
            <%=durataIncidente/60%>h <%=durataIncidente%60%>'
        </td>
        <td align="right"> <%= energieNelivrata%> </td>
        <td align="right"> <%= costMent%> </td>
        <td align="right"> <%= costDaune%> </td>
        <td align="right"> <%= costExpl%> </td>
        <td align="right"> <%= costTotal%> </td>
        <td align="center">
            <a class="link" title="Click pentru a vizualiza incidentele grupate pe cauze" href="javascript: openIncidenteGrupatePeCauzeByTipInstalatie('<%=tipInstalatie%>', '<%=idInstalatie%>')">
                vizualizare
            </a>
        </td>
    </tr>
    <% } %>

    <tr noSelect="true" class="paginationRow">
        <td colspan="4" align="left">
            <%=PaginationController.printPaginationData(pd)%>
        </td>
        <td align="center" class="totalCell"><%if( totaluri == null){%> &nbsp; <%}else{%> <%=totaluri.countIncidente%> <%}%></td>
        <td align="right" class="totalCell"><%if( totaluri == null){%> &nbsp; <%}else{%> <%=totaluri.durataIncidente/60%>h <%=totaluri.durataIncidente%60%>'<%}%></td>
        <td align="right" class="totalCell"><%if( totaluri == null){%> &nbsp; <%}else{%> <%=AppConstants.format2(totaluri.energieNelivrata)%> <%}%></td>
        <td align="right" class="totalCell"><%if( totaluri == null){%> &nbsp; <%}else{%> <%=AppConstants.format2(totaluri.costMent)%> <%}%></td>
        <td align="right" class="totalCell"><%if( totaluri == null){%> &nbsp; <%}else{%> <%=AppConstants.format2(totaluri.costDaune)%> <%}%></td>
        <td align="right" class="totalCell"><%if( totaluri == null){%> &nbsp; <%}else{%> <%=AppConstants.format2(totaluri.costExpl)%> <%}%></td>
        <td align="right" class="totalCell"><%if( totaluri == null){%> &nbsp; <%}else{%> <%=AppConstants.format02(totaluri.costTotal)%> <%}%></td>
        <td>&nbsp;</td>
    </tr>
    <% } %>
    <% } %>
</TABLE>
</form>

</td></tr></table>

<style type="text/css">
    .totalCell{
        font-weight: bold;
    }
</style>

<script type="text/javascript">
    Calendar.setup({
        inputField  : "data_start",         // ID of the input field
        ifFormat    : "%d.%m.%Y",    // the date format
        button      : "trigger_data_start"       // ID of the button
    });

    Calendar.setup({
        inputField  : "data_stop",         // ID of the input field
        ifFormat    : "%d.%m.%Y",    // the date format
        button      : "trigger_data_stop"       // ID of the button
    });

    function getCheckBoxes( element){
        var r = new Array();
        var t = element.getElementsByTagName("input");
        for( var i = 0; i < t.length; i++){
            if( t[i].type && t[i].type=="checkbox"){
                r.push( t[i]);
            }
        }

        return r;
    }

    function onToateClicked( oChecku){
        var disabled = oChecku.checked;

        var fixed = [
            $("statii"),
            $("linii"),
            $("posturi"),
            $("bobine"),
            $("derivatii"),
            $("celule"),
            $("bare"),
            $("trafo")
        ];

        //getCheckBoxes( $( "tableCuCheckboxuri"))
        doWork( fixed, function(element){
            if( element != oChecku){
                element.disabled = disabled;
                if( element.checked){
                    element.checked = false;
                }
            }
        });
    }

    function doWork( arr, f){
        for( var i = 0; i < arr.length; i++){
            f( arr[i]);
        }
    }

    var incidenteWindow = null;
    function openIncidenteByTipInstalatie( tipInstalatie, codInstalatie){
        if( incidenteWindow != null) incidenteWindow.close();
        incidenteWindow = window.open( '<%=AppConstants.APP_NAME%>?action=showIncidenteFromRaportTop10&tipInstalatie='+tipInstalatie + "&codInstalatie=" + codInstalatie,
                'incidenteRaport', 'top=50,left=50,width=850, height=550, status=yes,resizable=yes,dependent=yes,alwaysRaised=yes, scrollbars=yes');
    }

    function openIncidenteGrupatePeCauzeByTipInstalatie( tipInstalatie, codInstalatie){
        if( incidenteWindow != null) incidenteWindow.close();
        incidenteWindow = window.open( '<%=AppConstants.APP_NAME%>?action=showIncidenteFromRaportTop10PeCauze&tipInstalatie='+tipInstalatie + "&codInstalatie=" + codInstalatie,
                'incidenteRaport', 'top=50,left=50,width=1000, height=550, status=yes,resizable=yes,dependent=yes,alwaysRaised=yes, scrollbars=yes');
    }

    function initInstalatieSugest(){

        var ajaxDataProvider = new AjaxDataProvider( function(){
            var value = $('denInstalatie').value;
            return value.length >= 2 ? "<%=AppConstants.APP_NAME%>?action=instalatiiSugest&q=" : null;
        });

        new InputSugest( $("denInstalatie"), $("idInstalatie"), ajaxDataProvider, {
            beforeRequest : function(){
                $('tipInstalatie').value = '';
                $('isLF').value = '';
            },

            onSelect : function( item){
                $('tipInstalatie').value = item.tipInstalatie;
                $('isLF').value = item.isLF;
            }
        });
    }

    var table = new Table('table', "table");

    setTimeout("initInstalatieSugest()", 1000);

    function categoriesChecked(){
        document.zaforma.submit();
    }
</script>

<script type="text/javascript">
    <% if ( publicPath != null){ %>

    setTimeout(function(){
        window.location = '<%=publicPath%>';
    }, 500);

    <% } %>
</script>