<%@ page import="ro.emid.callcenter.CallcenterSessionUtils" %>
<%@ page import="ro.emid.common.constants.AppConstants" %>
<%@ page import="ro.emid.common.constants.DeranjamentConstants" %>
<%@ page import="ro.emid.common.constants.ReclamatieConstants" %>
<%@ page import="ro.emid.common.constants.RoleConstants" %>
<%@ page import="ro.emid.common.db.CategoryAccessDB" %>
<%@ page import="ro.emid.common.db.DeranjamentAccessDB" %>
<%@ page import="ro.emid.common.db.framework.Filter" %>
<%@ page import="ro.emid.common.db.framework.IFilter" %>
<%@ page import="ro.emid.common.types.Category" %>
<%@ page import="ro.emid.common.types.Deranjament" %>
<%@ page import="ro.emid.common.types.Reclamatie" %>
<%@ page import="ro.emid.common.types.User" %>
<%@ page import="ro.emid.common.utils.ObjectUtils" %>
<%@ page import="ro.emid.common.utils.SessionUtils" %>
<%@ page import="ro.emid.common.utils.StringUtils" %>
<%@ page import="java.sql.Date" %>
<%@ page import="java.sql.Timestamp" %>
<%@ page import="java.util.Calendar" %>

<%@ taglib prefix="emid" tagdir="/WEB-INF/tags" %>

<%
    final User user = SessionUtils.getUserLogat(session);
    final boolean printVersion = request.getParameter("printVersion") != null && "true".equals( request.getParameter("printVersion")) || request.getAttribute("printVersion") != null && "true".equals( request.getAttribute("printVersion")) ;

    long filialaId = CallcenterSessionUtils.getFilialaId(session);
    long sucursalaId = CallcenterSessionUtils.getSucursalaId(session);
    long centruId = CallcenterSessionUtils.getCentruId(session);

    if (0 < ObjectUtils.getLongValue(request.getParameter("filiala"), -2)) {
        filialaId = ObjectUtils.getLongValue(request.getParameter("filiala"));
    }

    if (0 < ObjectUtils.getLongValue(request.getParameter("sucursala"), -2)) {
        sucursalaId = ObjectUtils.getLongValue(request.getParameter("sucursala"));
    }

    if (0 < ObjectUtils.getLongValue(request.getParameter("centruId"), -2)) {
        centruId = ObjectUtils.getLongValue(request.getParameter("centruId"));
    }

    Category filialaRaport = CategoryAccessDB.getById(filialaId);
    if (filialaRaport == null) filialaRaport = new Category();

    Category sucursalaRaport = CategoryAccessDB.getById(sucursalaId);
    if (sucursalaRaport == null) sucursalaRaport = new Category();

    Category centruRaport = CategoryAccessDB.getById(centruId);
    if (centruRaport == null) centruRaport = new Category();

    Date dataStart = ObjectUtils.getDateValue(request.getParameter("data_start"), AppConstants.FORMAT_DATA_TIME);
    Date dataStop = ObjectUtils.getDateValue(request.getParameter("data_stop"), AppConstants.FORMAT_DATA_TIME);

    final Calendar c = Calendar.getInstance();
    c.set(c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DATE), 7, 0, 0);
    if (dataStart == null) dataStart = new Date(c.getTime().getTime());

    if (dataStop == null) {
        c.add(Calendar.DATE, 1);
        dataStop = new Date(c.getTime().getTime());
    }

    final String value_data_start = AppConstants.formatx(dataStart);
    final String value_data_stop = AppConstants.formatx(dataStop);

    final IFilter filter = new Filter();

    if (centruRaport.getId() > 0) {
        filter.addOrSetCriteria("AND", "SECTIE_ID", "=", new Long(centruRaport.getId()));
    } else if (sucursalaRaport.getId() > 0) {
        filter.addOrSetCriteria("AND", "SUCURSALA_ID", "=", new Long(sucursalaRaport.getId()));
    } else if (filialaRaport.getId() > 0) {
        filter.addOrSetCriteria("AND", "FILIALA_ID", "=", new Long(filialaRaport.getId()));
    }

    final Timestamp dataStartx = new Timestamp(dataStart.getTime());
    final Timestamp dataStopx = new Timestamp(dataStop.getTime());

    final int extendedFilters = ObjectUtils.getIntValue(request.getParameter("extendedFilters"), 0);
    final int fortaMajora = ObjectUtils.getIntValue(request.getParameter("fortaMajora"), -1);

    final String localitate = ObjectUtils.getStringValue(request.getParameter("LocalitateTxt"));
    final String strada = ObjectUtils.getStringValue(request.getParameter("StradaTxt"));
    final long codLocalitate = ObjectUtils.getLongValue(request.getParameter("CodLocalitate"), -1);
    final long codMunicipiu = ObjectUtils.getLongValue(request.getParameter("CodMunicipiu"), -1);
    final String municipiu = ObjectUtils.getStringValue(request.getParameter("Municipiu"));
    final long codStrada = ObjectUtils.getLongValue(request.getParameter("CodStrada"), -1);
    final int nrStrada = ObjectUtils.getIntValue(request.getParameter("NrStradaTxt"), -1);
    final int durataIntrerupH1 = ObjectUtils.getIntValue(request.getParameter("DurataIntreruph1"), -1);
    final int durataIntrerupM1 = ObjectUtils.getIntValue(request.getParameter("DurataIntrerupm1"), -1);
    final int durataIntrerupH2 = ObjectUtils.getIntValue(request.getParameter("DurataIntreruph2"), -1);
    final int durataIntrerupM2 = ObjectUtils.getIntValue(request.getParameter("DurataIntrerupm2"), -1);
    final String cond1 = ObjectUtils.getStringValue(request.getParameter("DI1"));
    final String cond2 = ObjectUtils.getStringValue(request.getParameter("DI2"));
    long durataIntrerup1 = 0;
    long durataIntrerup2 = 0;
    final int mediu = ObjectUtils.getIntValue(request.getParameter("Mediu"), -1);
    final String tipArtera = ObjectUtils.getStringValue(request.getParameter("TipArtera"));
    final int durataRemediere = ObjectUtils.getIntValue(request.getParameter("Remediere"), -1);

    durataIntrerup1 = (durataIntrerupH1 > 0 ? durataIntrerupH1 * 60 : 0 ) + (durataIntrerupM1 > 0 ? durataIntrerupM1 : 0);
    durataIntrerup2 = (durataIntrerupH2 > 0 ? durataIntrerupH2 * 60 : 0 ) + (durataIntrerupM2 > 0 ? durataIntrerupM2 : 0);

    filter.addOrSetCriteria("AND", "DATA_ANUNTARE", ">=", dataStartx);
    filter.addOrSetCriteria("AND", "DATA_ANUNTARE", "<=", dataStopx);

    if (extendedFilters == 1) {
        if (fortaMajora == 1 || fortaMajora == 0) {
            filter.addOrSetCriteria("AND", "FORTA_MAJORA", "=", new Integer(fortaMajora));
        }

        if (durataIntrerup1 > 0 && !StringUtils.isZeroLength(cond1)) {
                filter.addOrSetStringCriteria("AND", durataIntrerup1 + cond1, "(d.data_rezolvare-d.data_anuntare)*24*60 ");
        }

        if (durataIntrerup2 > 0 && !StringUtils.isZeroLength(cond2)){
                filter.addOrSetStringCriteria("AND", "(d.data_rezolvare-d.data_anuntare)*24*60", cond2 +  durataIntrerup2);
        }

        if (nrStrada >= 0) {
            filter.addOrSetCriteria("AND", "NR", "=", Integer.toString(nrStrada));
        }

        if (!StringUtils.isZeroLength(strada)) {
            filter.addOrSetCriteria("AND", "UPPER(STRADA)", "=", strada.toUpperCase());
        }

        if (!StringUtils.isZeroLength(localitate)) {
            filter.addOrSetCriteria("AND", "UPPER(LOCALITATE)", "=", localitate.toUpperCase());
        }

        if (mediu == 1 || mediu == 2) {
            filter.addOrSetCriteria("AND", "MEDIUL", "=", Integer.toString(mediu));
        }

        if (durataRemediere == 12 || durataRemediere == 24 || durataRemediere == 72) {
            filter.addOrSetCriteria("AND", "(d.data_rezolvare-d.DATA_SOSIRE_ECHIPA)*24*60", ">", Integer.toString(durataRemediere * 60));
        }
    }

    long nrLines = ObjectUtils.getLongValue(request.getParameter("nrLines"), -1);
    if (nrLines == -1) nrLines = CallcenterSessionUtils.getNrLines(session);

    long currentBeginIndex = ObjectUtils.getLongValue(request.getParameter("currentBeginIndex"), -1);
    if (currentBeginIndex == -1) currentBeginIndex = CallcenterSessionUtils.getBeginIndex(session);

    String sortColumn = ObjectUtils.getStringValue(request.getParameter("sortColumn"));
    if( sortColumn == null || sortColumn.length() == 0) sortColumn = "NUMAR";
    String sortType   = ObjectUtils.getStringValue(request.getParameter("sortType"));
    if( sortType == null || sortType.length() == 0) sortType = "DESC";

    Deranjament[] deranjamente = DeranjamentAccessDB.getAllDeranjamente2(filter, filter, sortColumn, sortType, currentBeginIndex, currentBeginIndex + nrLines - 1 );

    final long nrLinesTotal = DeranjamentAccessDB.getDeranjamenteCount(filter, filter);
    final String direction = ObjectUtils.getStringValue(request.getParameter("direction"));
    if ("backward".equals(direction)) {
        currentBeginIndex -= nrLines;
    } else if ("forward".equals(direction)) {
        currentBeginIndex += nrLines;
    } else if( "first".equals( direction)){
        currentBeginIndex = 1;
    } else if( "last".equals( direction)){
        currentBeginIndex =  nrLines * nrLinesTotal/nrLines + 1;
    }

    if (currentBeginIndex > nrLinesTotal && nrLinesTotal > 1)
        currentBeginIndex -= nrLines; //cazul cind se sterge ultimul element de pe ultima pagina si este singurul pe pagina
    if (currentBeginIndex < 1) currentBeginIndex = 1;

    final int nrLinesSelected = deranjamente.length;
%>

<%!
    private static final java.text.SimpleDateFormat _df = new java.text.SimpleDateFormat("yyyyMMdd");
%>

<table>
<tr>
<td>
<span style="font-size: 16px; font-weight:bold;">Registrul de deranjamente</span>
<%if (!printVersion) {%>
<div class="spacer"></div>
<form id="zaforma" name="zaforma" action="<%=AppConstants.APP_NAME%>?action=raport-registrul-deranjamente" method="post">
<table class="gsaptd" width="100%">
    <tr>
        <td>
                <input type="hidden" name="printVersion" value="nope">
                Filiala:
                <SELECT name="filiala" onchange="fill_sucursala_select(); "
                        class="gSAPSelect" <%=user.getIeLevel() == RoleConstants.NIVEL_FULL ? "" : "disabled"%> >
                    <OPTION value="-1">ELECTRICA SA:</OPTION>
                    <% final Category[] filiale = CategoryAccessDB.getAllCategoriesByParentId(-1);
                        if (filiale != null) for (int i = 0; i < filiale.length; i++) {%>
                    <OPTION <%=(filiale[i].getId() == filialaRaport.getId()) ? "selected=\"true\" " : ""%>value="<%=filiale[i].getId()%>"><%=filiale[i].getName()%>
                    </OPTION>
                    <%} %>
                </SELECT>&nbsp;&nbsp;

                Sucursala:
                <span id="sucursalaDiv">
                <SELECT name="sucursala" class="gSAPSelect" onchange="fill_centru_select()">
                    <option value="-1">Selectati:</option>
                </SELECT></span>&nbsp;&nbsp;

                C.E.:
                <span id="centruDiv">
                    <SELECT name="centruId" class="gSAPSelect">
                        <OPTION value="-1">Selectati:</OPTION>
                    </SELECT>
                </span>&nbsp;&nbsp;

                <input type="text" id="data_start" name="data_start"
                       size="14" value="<%=value_data_start%>"/> <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> -
                <input type="text" id="data_stop" name="data_stop"
                       size="14" value="<%=value_data_stop%>"/> <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>

                &nbsp;
                <span id="extendedFiltersPlus"><nobr><b>mai mult</b>&nbsp;</nobr></span>
                <input type="hidden" id="extendedFilters" name="extendedFilters" value="<%=extendedFilters%>">

                <input type="button" value="Aplică"
                       onclick="this.form.target='_self'; this.form.submit()"/>
                <input type="hidden" name="toExport" value="0">
                <input type="button" id="btn-export-excel" value="Export Excel"
                       <%--onclick="document.zaforma.toExport.value = '1'; document.zaforma.submit();"--%>
                       />
        </td>
    </tr>


    <tr>
        <td>
            <!-- Adaugare elemente in plus filtru!!! -->
            <span id="extendedFiltersSpan">

        Forta majora:
        <select name="fortaMajora" class="gSAPSelect">
            <option value="-1"></option>
            <option value="1" <%=fortaMajora == 1 ? "selected" : ""%>>Da</option>
            <option value="0" <%=fortaMajora == 0 ? "selected" : ""%>>Nu</option>
        </select>&nbsp;&nbsp;
            
        Mediu:
        <select name="Mediu" class="gSAPSelect">
            <option value="-1"></option>
            <option value="1" <%=mediu == 1 ? "selected" : ""%>>Urban</option>
            <option value="2" <%=mediu == 2 ? "selected" : ""%>>Rural</option>
        </select>
        Localitate:
    <input type="hidden" id="CodLocalitateId" name="CodLocalitate" value="<%=codLocalitate%>">
    <input type="hidden" id="CodMunicipiuId" name="CodMunicipiu" value="<%=codMunicipiu%>">
    <input type="hidden" id="MunicipiuId" name="Municipiu" value="<%=municipiu%>">
    <input class="gsapinputtext" style="width: 160px" type=text id="LocalitateId" name="LocalitateTxt"
           value="<%=localitate%>"
           sugestWidth="250">

        Strada:
    <input type="hidden" name="CodStrada" id="CodStradaId" value="-1">
    <input class="gsapinputtext" style="width: 240px;" name="StradaTxt" id="StradaId" value="<%=strada%>">&nbsp;
        Tip Artera:
         <input class="gsapinputtext" style="width: 70px" type=text name="TipArtera"
                id="TipArteraId" onchange="onChangeTipArtera()" value="<%=tipArtera%>">&nbsp;
         Nr. strada:
                <input onfocus="validateForNumar()" class="gsapinputtext" type="text"
                       value="<%=nrStrada == -1 ? "" : Integer.toString(nrStrada)%>" size="10" name="NrStradaTxt"
                       id="NrStradaId">&nbsp;</br>

                <!--<span id="extendedFiltersSpan2">-->
                <input type="text" size="2" maxlength="2" align="right" name="DurataIntreruph1"
                       value="<%=durataIntrerupH1 == -1 ? "" : Integer.toString(durataIntrerupH1)%>"> h
                <input type="text" size="2" maxlength="2" align="right" name="DurataIntrerupm1"
                       value="<%=durataIntrerupM1 == -1 ? "" : Integer.toString(durataIntrerupM1)%>"> m
                <select name="DI1" class="gSAPSelect">
                    <option value=""></option>
                    <option value="=" <%=cond1.equals("=") ? "selected" : ""%>>=</option>
                    <option value="<" <%=cond1.equals("<") ? "selected" : ""%>><</option>
                    <option value="<=" <%=cond1.equals("<=") ? "selected" : ""%>><=</option>
                    <option value=">" <%=cond1.equals(">") ? "selected" : ""%>>></option>
                    <option value=">=" <%=cond1.equals(">=") ? "selected" : ""%>>>=</option>
                </select>
                <span title="Durata intreruperii" >D.I.</span>
                <select name="DI2" class="gSAPSelect">
                    <option value=""></option>
                    <option value="=" <%=cond2.equals("=") ? "selected" : ""%>>=</option>
                    <option value="<" <%=cond2.equals("<") ? "selected" : ""%>><</option>
                    <option value="<=" <%=cond2.equals("<=") ? "selected" : ""%>><=</option>
                    <option value=">" <%=cond2.equals(">") ? "selected" : ""%>>></option>
                    <option value=">=" <%=cond2.equals(">=") ? "selected" : ""%>>>=</option>
                </select>
                <input type="text" size="2" maxlength="2" align="right" name="DurataIntreruph2"
                       value="<%=durataIntrerupH2 == -1 ? "" : Integer.toString(durataIntrerupH2)%>"> h
                <input type="text" size="2" maxlength="2" align="right" name="DurataIntrerupm2"
                       value="<%=durataIntrerupM2 == -1 ? "" : Integer.toString(durataIntrerupM2)%>"> m
                &nbsp;

                Remediere mai mare de:
                <select name="Remediere" class="gSAPSelect">
                    <option value="-1"></option>
                    <option value="12" <%=durataRemediere == 12 ? "selected" : ""%>>12</option>
                    <option value="24" <%=durataRemediere == 24 ? "selected" : ""%>>24</option>
                    <option value="72" <%=durataRemediere == 72 ? "selected" : ""%>>72</option>
                </select>h

            </span>

            <script type="text/javascript">
                var plusu2 = new Plus("extendedFiltersPlus", "extendedFiltersSpan", function() {
                    $("extendedFilters").value = ( plusu2.getStatus() == PlusConstants.STATUS_MINUS ? "1" : "0");
                });

                <% if( extendedFilters == 1){ %>
                plusu2.setMinus();
                <% } %>

            </script>


        </td>
    </tr>


</table>

<div class="spacer">&nbsp;</div>
<%} else {%>
<br>
<%=filialaRaport.getId() > 0 ? filialaRaport.getName() : "Electrica SA"%>
<%=sucursalaRaport.getId() > 0 ? " - " + sucursalaRaport.getName() : ""%>
<%=centruRaport.getId() > 0 ? " - " + centruRaport.getName() : ""%>

&nbsp;&nbsp;&nbsp;<b><%=value_data_start%> - <%=value_data_stop%>
</b>
<%}%>


<TABLE border=1 cellPadding=2 cellSpacing=1 width="100%" class="table" style="BACKGROUND-COLOR: white">
<thead>
<tr>
    <th class="gsapthead" rowspan="3" width="10">Nr. crt.</th>
    <th class="gsapthead" rowspan="3" width="10">ID</th>
    <th class="gsapthead" rowspan="3" width="10">SDEE</th>
    <th class="gsapthead" rowspan="3" width="10">C.E.</th>
    <th class="gsapthead" rowspan="3">Numele si denumirea persoanei care a anuntat deranjamentul</th>
    <th class="gsapthead" rowspan="3">Municipiu/<br/>Comuna</th>
    <th class="gsapthead" rowspan="3">Localitate/<br/>Sat</th>
    <th class="gsapthead" rowspan="3">Strada</th>
    <th class="gsapthead" rowspan="3">Nr.</th>
    <th class="gsapthead" rowspan="3">Bl.</th>
    <th class="gsapthead" rowspan="3">Sc.</th>
    <th class="gsapthead" rowspan="3">Ap.</th>
    <th class="gsapthead" rowspan="3">Nr. Telefon</th>
    <th class="gsapthead" rowspan="3">Continutul Sesizarii</th>
    <%--<th class="gsapthead" rowspan="3" nowrap style="writing-mode: tb-rl;">Data si ora anuntarii<br> deranjamentului</th>--%>
    <th class="gsapthead" rowspan="3" nowrap style="font-size:10px">Data si<br>ora<br>anuntarii<br>deranja-<br>mentului
    </th>
    <%--<th class="gsapthead" rowspan="3" nowrap style="writing-mode: tb-rl;">Data si ora sosirii echipei la fata locului</th>--%>
    <th class="gsapthead" rowspan="3" nowrap style="font-size:10px">Data si<br/> ora<br>sosirii<br>echipei<br/>
        la fata<br/>locului
    </th>
    <%--<th class="gsapthead" rowspan="3" style="writing-mode: tb-rl; ">Intervalul de timp de la anuntare pina la sosirea echipei</th>--%>
    <th class="gsapthead" rowspan="3" style="">Intervalul de timp<br> de la anuntare<br>pina la sosirea<br>
        echipei
    </th>
    <%--<th class="gsapthead" rowspan="3" style="writing-mode: tb-rl;  ">Data si ora realimetarii consumatorilor</th>--%>
    <th class="gsapthead" rowspan="3" style="font-size:10px">Data si<br/>ora <br/>realimetarii<br/>consumatorilor
    </th>
    <th class="gsapthead" rowspan="3">Durata Intreruperii</th>
    <%--<th class="gsapthead" rowspan="2" colspan="2" style="writing-mode: tb-rl;  ">Mediul in care sint amplasati consumatorii intrerupti</th>--%>
    <th class="gsapthead" rowspan="2" colspan="2" style="font-size:10px">Mediul in care <br>sint amplasati <br>consumatorii
        intrerupti
    </th>
    <th class="gsapthead" rowspan="2" colspan="4">Categoria consumatorilor intrerupti</th>
    <%--<th class="gsapthead" rowspan="2" colspan="3" style="writing-mode: tb-rl;  ">Energia electrica nelivrata consumatorilor intrerupti (KW/h)</th>--%>
    <th class="gsapthead" rowspan="2" colspan="3" style="font-size:10px">Energia electrica <br>nelivrata
        consumatorilor <br>intrerupti (KW/h)
    </th>
    <th class="gsapthead" colspan="8">Constatari ale echipei care a rezolvat deranjamentul</th>
    <th class="gsapthead" rowspan="3">Modul de rezolvare</th>
    <th class="gsapthead" colspan="3">Alte activitati</th>
    <th class="gsapthead" rowspan="3">Echipa care a anuntat deranjamentul [Numele si Prenumele sefului]</th>
    <th class="gsapthead" rowspan="3">Masurile luate</th>
    <th class="gsapthead" rowspan="3">Efectul asupra consumatorului</th>
    <th class="gsapthead" rowspan="3">Provizorat</th>
    <th class="gsapthead" rowspan="3">Autor</th>
</tr>
<tr>
    <%--<th class="gsapthead" rowspan="2" style="writing-mode: tb-rl;  ">Descrierea deranjamentului</th>--%>
    <th class="gsapthead" rowspan="2" style="font-size: 10px">Descrierea<br/>deranjamentului</th>
    <%--<th class="gsapthead" rowspan="2" style="writing-mode: tb-rl;  ">Localizarea defectului. Categoria de instalatii (initial)</th>--%>
    <th class="gsapthead" rowspan="2" style="font-size: 10px">Localizarea defectului. <br>Categoria de
        instalatii<br> (initial)
    </th>
    <th class="gsapthead" rowspan="2">Elementul defect</th>
    <th class="gsapthead" rowspan="2">Componenta defecta</th>
    <th class="gsapthead" rowspan="2">Cauza deranjamentului</th>
    <th class="gsapthead" rowspan="2">Factori favorizanti</th>
    <th class="gsapthead" colspan="2">Apartenenta instalatiilor in care a fost localizata cauza
        deranjamentului
    </th>

    <th class="gsapthead" rowspan="2" >Data si ora inceperii</th>
    <th class="gsapthead" rowspan="2"  >Data si ora terminarii</th>
    <th class="gsapthead" rowspan="2"  >Continutul activitatii</th>
</tr>
<tr>
    <%--<th class="gsapthead"  >Urban</th>--%>
    <th class="gsapthead" style="font-size: 10px">Urban</th>
    <%--<th class="gsapthead"  >Rural</th>--%>
    <th class="gsapthead" style="font-size: 10px">Rural</th>

    <th class="gsapthead"  >Nr case</th>
    <th class="gsapthead" nowrap  >Nr. apartamente</th>
    <th class="gsapthead"  >Nr. mici consumatori</th>
    <th class="gsapthead"  >Nr. mari consumatori</th>
    <th class="gsapthead"  >Casnici</th>
    <th class="gsapthead"  >Mici consumatori</th>
    <th class="gsapthead"  >Mari consumatori</th>


    <th class="gsapthead">"Electrica ..."</th>
    <th class="gsapthead">Consumator</th>
</tr>
<tr>
    <% for (int i = 1; i <= 45; i++) {%>
    <th class="gsapthead" width=""><%=i%></th>
    <% }%>
</tr>
</thead>
<tbody>

    <% if( deranjamente.length == 0){%>
    <tr>
        <td class="no-data" colspan="45">Nu exista date ...</td>
    </tr>
    <% }else for (int i = 0; i < deranjamente.length; i++) {
    final Deranjament deranjament = deranjamente[i];
    Reclamatie reclamatie = deranjament.getPrimaReclamatie();
    if (reclamatie == null) reclamatie = new Reclamatie();

   final Category sdee =  CategoryAccessDB.getById(deranjament.getSucursalaId());
    String sdeeName = "-";
    if (sdee != null){
        sdeeName = sdee.getName();
    }
   final Category centru = CategoryAccessDB.getById(deranjament.getCentruId());
    String centruName = "-";
    if(centru != null){
        centruName = centru.getName();
    }
%>
<tr>
    <td align="center"><%=(i + currentBeginIndex )%>
    </td>
    <td align="center"><%=deranjament.getNumar()%>
    </td>
    <td align="center"><%=sdeeName%>
    </td>
    <td align="center"><%=centruName%>
    </td>
    <td nowrap><%=AppConstants.format(reclamatie.getNumeClient())%>&nbsp;</td>
    <td><%=AppConstants.format(reclamatie.getLocalitate())%>&nbsp;</td>
    <td><%=AppConstants.format(reclamatie.getLocalitate2())%>&nbsp;</td>
    <td><%=AppConstants.format(reclamatie.getStrada())%>&nbsp;</td>
    <td align="right"><%=AppConstants.format(reclamatie.getNr())%>&nbsp;</td>
    <td align="right"><%=AppConstants.format(reclamatie.getBloc())%>&nbsp;</td>
    <td align="right"><%=AppConstants.format(reclamatie.getScara())%>&nbsp;</td>
    <td align="right"><%=AppConstants.format(reclamatie.getAp())%>&nbsp;</td>
    <td align="center"><%=AppConstants.format(reclamatie.getMobil())%>&nbsp;</td>
    <td><%=ReclamatieConstants.getContinutSesizare(reclamatie, " ")%> &nbsp;</td>
    <td align="center"><%=AppConstants.format(deranjament.getDataAnuntareReclamatie())%>&nbsp;</td>
    <td align="center"><%=AppConstants.format(deranjament.getDataSosireEchipa())%>&nbsp;</td>
    <%
        final long durataSosireEchipa = deranjament.getDurataSosireEchipa();
    %>
    <td align="center"><%=durataSosireEchipa != 0 ? durataSosireEchipa / 60 + "h " + durataSosireEchipa % 60 + '\'' : "-"%>
        &nbsp;</td>
    <td align="center"><%=AppConstants.format(deranjament.getDataRezolvare())%>&nbsp;</td>
    <!-- Data si ora realimetarii consumatorilor-->
    <%
        long durataIntrerupere = 0; // in minute
        if (deranjament.getDataRezolvare() != null && deranjament.getDataAnuntareReclamatie() != null) {
            durataIntrerupere = (deranjament.getDataRezolvare().getTime() - deranjament.getDataAnuntareReclamatie().getTime()) / 60000;
        }
    %>
    <td align="center"><%=durataIntrerupere != 0 ? (durataIntrerupere / 60) + "h " + (durataIntrerupere % 60) + '\'' : "-"%>
    </td>
    <!-- Durata intreruperii -->
    <td align="center"><%=deranjament.getMediul() == Deranjament.MEDIU_URBAN ? "X" : ""%>&nbsp;</td>
    <td align="center"><%=deranjament.getMediul() == Deranjament.MEDIU_RURAL ? "X" : ""%>&nbsp;</td>

    <td align="right"><%=AppConstants.format(deranjament.getNrCase())%>&nbsp;</td>
    <td align="right"><%=AppConstants.format(deranjament.getNrAp())%>&nbsp;</td>
    <td align="right"><%=AppConstants.format(deranjament.getNrMici())%>&nbsp;</td>
    <td align="right"><%=AppConstants.format(deranjament.getNrMari())%>&nbsp;</td>
    <td align="right"><%=AppConstants.format2(deranjament.getEncCasnici())%>
    </td>
    <td align="right"><%=AppConstants.format2(deranjament.getEncMici())%>
    </td>
    <td align="right"><%=AppConstants.format2(deranjament.getEncMari())%>
    </td>
    <td><%=AppConstants.format(deranjament.getDescriere())%>&nbsp;</td>
    <td>
        <% if( deranjament.getApartenentaInstalatie() == Deranjament.APARTINE_ELECTRICA){%>
            <%=AppConstants.format(DeranjamentConstants.getTextInstalatie((int) deranjament.getInstalatia()))%>
        <% }else if( deranjament.getApartenentaInstalatie() == Deranjament.APARTINE_CONSUMATOR){%>
            instalatie abonat
        <% }else{%>
            <span title="Apartenenta instalatiei necunoscuta : <%=deranjament.getApartenentaInstalatie()%>">N/A</span>
        <% }%>
        &nbsp;</td>
    <td id="td_elemetul_<%=i%>"> <!-- Elementul defect -->
        <% if (deranjament.getCatInstalatii() > 0 &&
                deranjament.getElementulDefect() > 0 &&
                deranjament.getCatInstalatii() < DeranjamentConstants.ARR_ELEMENTE_DEFECTE.length &&
                deranjament.getElementulDefect() < DeranjamentConstants.ARR_ELEMENTE_DEFECTE[(int) deranjament.getCatInstalatii()].length
                ) { %>
        <script type="text/javascript">
            try {
                var el = "<%=ro.emid.common.utils.Util.escapeToJs( DeranjamentConstants.ARR_ELEMENTE_DEFECTE[ (int)deranjament.getCatInstalatii()][ (int)deranjament.getElementulDefect()])%>";
                $('td_elemetul_<%=i%>').innerHTML = el;
            } catch(ex) {
                alert(ex.message);
            }
        </script>
        <%}%>
        &nbsp;
    </td>
    <td id="td_componenta_<%=i%>"> <!-- Componenta defecta -->
        <script type="text/javascript">
            if ( <%=deranjament.getCatInstalatii()%>     > 0 &&
                 <%=deranjament.getElementulDefect()%>   > 0 &&
                 <%=deranjament.getComponentaDefecta()%> > 0
            )
            {
                try {
                    var c = componente[ <%=deranjament.getCatInstalatii()%> - 1][<%=deranjament.getElementulDefect()%> - 1];
                    $('td_componenta_<%=i%>').innerHTML = c[<%=deranjament.getComponentaDefecta()%>][0];
                } catch(ex) {
                    alert(ex.message);
                }
            }
        </script>
        &nbsp;
    </td>
    <td><%=AppConstants.format(DeranjamentConstants.getTextCauze((int) deranjament.getCauza()))%>&nbsp;</td>
    <!-- Cauza deranjamentului -->
    <td><%=AppConstants.format(DeranjamentConstants.getTextFactorFavorizat((int) deranjament.getFactoriiFavozizati()))%>
        &nbsp;</td>
    <!-- Factori favorizanti -->
    <td align="center"><%=AppConstants.format(deranjament.getApartenentaInstalatie() == Deranjament.APARTINE_ELECTRICA ? "Da" : "Nu")%>
        &nbsp;</td>
    <td align="center"><%=AppConstants.format(deranjament.getApartenentaInstalatie() == Deranjament.APARTINE_CONSUMATOR ? "Da" : "Nu")%>
        &nbsp;</td>
    <td><%=AppConstants.format(deranjament.getModRezolvare())%>&nbsp;</td>
    <td>-</td>
    <!-- Data si ora inceperii  -->
    <td>-</td>
    <!-- Data si ora terminarii -->
    <td>-</td>
    <!-- Continutul activitatii -->
    <td><%=AppConstants.format(deranjament.getEchipa())%> &nbsp;</td>
    <td><%=AppConstants.format(DeranjamentConstants.getTextMasuriLuate((int) deranjament.getMasuriLuate()))%>
        &nbsp;</td>
    <!-- Masurile luate -->
    <td align="center"><%=deranjament.getEfectulAsupraConsumatorilor() > 0 ? "Da" : "Nu"%> &nbsp;</td>
    <td align="center"><%=AppConstants.format(deranjament.getProvizorat() > 0 ? "X" : "")%>&nbsp;</td>
    <td align="center"><%=deranjament.getUserUpdate() == null ? deranjament.getUserInsert() : deranjament.getUserUpdate()%></td>
</tr>
<%}%>
</tbody>
<tfoot>
<tr>
    <td colspan="45" >
        <input type="hidden" name="currentBeginIndex" value="<%=currentBeginIndex%>">
        <input type="hidden" name="direction" value="">
        <input type="hidden" name="sortColumn" value="<%=sortColumn%>">
        <input type="hidden" name="sortType" value="<%=sortType%>">
        Nr. linii:
        <select name="nrLines" onchange="this.form.submit()" style="font-size: 10px">
            <option value="10"  <%=nrLines == 10 ? "selected" : ""%> >10</option>
            <option value="15"  <%=nrLines == 15 ? "selected" : ""%> >15</option>
            <option value="20"  <%=nrLines == 20 ? "selected" : ""%> >20</option>
            <option value="30"  <%=nrLines == 30 ? "selected" : ""%> >30</option>
            <option value="40"  <%=nrLines == 40 ? "selected" : ""%> >40</option>
            <option value="50"  <%=nrLines == 50 ? "selected" : ""%> >50</option>
        </select>&nbsp;&nbsp;
        <%=currentBeginIndex%> - <%=currentBeginIndex + nrLinesSelected - 1%> din <%=nrLinesTotal%>&nbsp;&nbsp;&nbsp;
        <input <%=currentBeginIndex == 1 ? "disabled" : ""%>  title="Primele <%=nrLines%> linii" type="button" onclick="this.form.direction.value='first'; this.form.submit()" style="font-size: 8px; cursor: pointer" value="&lt&lt" />
        <input <%=currentBeginIndex == 1 ? "disabled" : ""%>  title="Precedentele <%=nrLines%> linii" type="button" onclick="this.form.direction.value='backward'; this.form.submit()" style="font-size: 8px; cursor: pointer" value="&lt" />
        <input <%=currentBeginIndex + nrLinesSelected - 1 >= nrLinesTotal ? "disabled" : ""%> title="Urmatoarele <%=nrLines%> linii" type="button" onclick="this.form.direction.value='forward'; this.form.submit()" style="font-size: 8px; cursor: pointer" value="&gt" />
        <input <%=currentBeginIndex + nrLinesSelected - 1 >= nrLinesTotal ? "disabled" : ""%> title="Ultimele <%=nrLines%> linii" type="button" onclick="this.form.direction.value='last'; this.form.submit()" style="font-size: 8px; cursor: pointer" value="&gt&gt" />
    </td>
</tr>
</tfoot>
</TABLE>

</form>

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

<script type="text/javascript">

    function fill_sucursala_select(selectedValue, disabled, firstShow) {
        resetComboLeaveFirstOption(document.zaforma.sucursala);
        resetComboLeaveFirstOption(document.zaforma.centruId);

        var filialaId = document.zaforma.filiala[ document.zaforma.filiala.selectedIndex].value;
        if (filialaId > -1) {
            var params = "parentId=" + filialaId + "&selectName=sucursala&disabled=" + disabled + (selectedValue ? "&selectedValue=" + selectedValue : "");
            //alert( params);

            getCategoriesFromServer(params, function(originalRequest) {
                //alert( getResponseMesg (originalRequest.responseText));
                $('sucursalaDiv').innerHTML = getResponseMesg(originalRequest.responseText);

                document.zaforma.sucursala.onchange = function() {
                    fill_centru_select();
                };

                if (firstShow) {
                    fill_centru_select(<%=centruRaport.getId()%>, <%=user.getIeLevel() == RoleConstants.NIVEL_CENTRU || user.getIeLevel() == RoleConstants.NIVEL_FORMATIE%>);
                }
            });
        }
    }

    function fill_centru_select(selectedValue, disabled) {
        resetComboLeaveFirstOption(document.zaforma.centruId);

        var sucursalaId = document.zaforma.sucursala[ document.zaforma.sucursala.selectedIndex].value;
        if (sucursalaId > -1) {
            var params = "parentId=" + sucursalaId + "&selectName=centruId&disabled=" + disabled + (selectedValue ? "&selectedValue=" + selectedValue : "");
            //alert( params);

            getCategoriesFromServer(params, function(originalRequest) {
                //alert( getResponseMesg (originalRequest.responseText));
                $('centruDiv').innerHTML = getResponseMesg(originalRequest.responseText);
            });
        }
    }


    fill_sucursala_select(<%=sucursalaRaport.getId()%>, <%=user.getIeLevel() == RoleConstants.NIVEL_SUCURSALA || user.getIeLevel() == RoleConstants.NIVEL_CENTRU || user.getIeLevel() == RoleConstants.NIVEL_FORMATIE%>, true);

    Calendar.setup(
            {
                inputField  : "data_start",         // ID of the input field
                ifFormat    : "%d.%m.%Y %H:%M",    // 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 %H:%M",    // the date format
                button      : "trigger_data_stop"       // ID of the button
            }
    );


    function setUpSuggesters(){

        /*
         //tip artera sugest
         var tipArteraAjaxDataProvider = new AjaxDataProvider(function() {
         return "<%=AppConstants.APP_NAME%>?action=callcenter_cautTipArtera2&q=";
         });

         var tipArteraAjaxSugest = new InputSugest($("<%=ReclamatieConstants.TIP_ARTERA%>"), null, tipArteraAjaxDataProvider, {
         onSelect : function(item) {
         //item.key;
         //item.value;
         $('<%=ReclamatieConstants.STRADA%>').value = '';
         $('<%=ReclamatieConstants.STRADA%>').focus();
         }
         });
         */

        //localitate sugest
        var localitate2AjaxDataProvider = new AjaxDataProvider(function() {
            return "<%=AppConstants.APP_NAME%>?action=callcenter_cautLocalitate22" + "&q=";
        });

        new InputSugest($("LocalitateTxt"), $("CodLocalitate"), localitate2AjaxDataProvider, {
            onSelect : function(item) {
                $('LocalitateTxt').value = item.denLocalitate;
                $('CodLocalitate').value = item.key;
                $('CodMunicipiu').value = item.codMunicipiu;
                $('Municipiu').value = item.denMunicipiu;
                $('StradaTxt').value = '';
                $('StradaTxt').focus();
            }
        });

        //strada sugest
        var stradaAjaxDataProvider = new AjaxDataProvider(function() {

            var loc = $('LocalitateTxt').value;
            var codloc = $('CodLocalitate').value;
            var mun = $('Municipiu').value;
            //var loc = $('LocalitateTxt');
            if (loc != null && loc.trim().length > 0)
                return "<%=AppConstants.APP_NAME%>?action=callcenter_cautStrada2" + "&loc=" + loc + "&codloc=" + codloc +
                        "&mun=" + mun + "&tipArtera=" + "&q=";
            //"&mun=" + mun + "&loc=" + loc + "&tipArtera=" + tipArtera + "&q=";
            else return null;
        });

        new InputSugest($("StradaTxt"), $("CodStrada"), stradaAjaxDataProvider, {
            onSelect : function(item) {
                setStradaData(item.cod, item.denumire, item.tipArtera);//, item.tipArtera, item.denumire);
                $('NrStradaTxt').value = '';
                $('NrStradaTxt').focus();
            }
        });
    }

    function setUpExportButton(){
        new JobButton({
            jobId: "callcenter-rd",
            jobStartAction: "<%=AppConstants.APP_NAME%>?action=job-start-reg-deranjamente",
            jobStatusAction: "<%=AppConstants.APP_NAME%>?action=job-status",
            downloadFileFromRepo: "<%=AppConstants.APP_NAME%>?action=download-file-from-repo",
            jobData: {
                form: $('zaforma')
            }
        }, "btn-export-excel");
    }

    function validateForNumar() {
        if (document.zaforma.LocalitateTxt.value.length == 0) {
            alert('Selectati o localitate !');
            document.zaforma.LocalitateTxt.focus();
            return false;
        }

        if (document.zaforma.StradaTxt.value.length == 0) {
            alert('Selectati o strada !');
            document.zaforma.StradaTxt.focus();
            return false;
        }
        return true;
    }

    function setStradaData(codStrada, denumire, tipArtera) {//, tipArtera, denumire){
        $('CodStrada').value = codStrada;
        $('StradaTxt').value = denumire;
        $('TipArtera').value = tipArtera;
    }

    function onChangeTipArtera() {
        document.zaforma.CodStrada.value = '-1';
        document.zaforma.StradaTxt.value = '';
    }


    setUpExportButton();
    setTimeout(function(){
        setUpSuggesters();
    }, 200);
</script>
