<%@ page import="java.sql.Date" %>
<%@ page import="java.util.Calendar" %>
<%@ page import="ro.emid.callcenter.obj.FiltruDeranjamente" %>
<%@ page import="java.sql.Timestamp" %>
<%@ page import="ro.emid.common.types.Nomenclator" %>
<%@ page import="ro.emid.common.db.NomAccessDB" %>
<%@ page import="ro.emid.common.db.CategoryAccessDB" %>
<%@ page import="ro.emid.common.constants.*" %>

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

<% if (request.getAttribute("act") !=null) { %>
    <script type="text/javascript">
        try{
            opener.reloadDeranjamente();
        }catch( e){
        }
        window.close();
    </script>
<% return;} %>

<%
    final FiltruDeranjamente filtru = CallcenterSessionUtils.getFiltruDeranjamente(session);

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

    if (filtru.getFiliala() != null && filtru.getFiliala().getId() > 0) filialaId = filtru.getFiliala().getId();
    if (filtru.getSucursala() != null && filtru.getSucursala().getId() > 0) sucursalaId = filtru.getSucursala().getId();
    if (filtru.getCentru() != null && filtru.getCentru().getId() > 0) centruId = filtru.getCentru().getId();


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

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

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

    final int fortaMajora = filtru.getFortaMajora();
    final int catInstalatii = filtru.getCatInstalatii();
    final int masuriLuate = filtru.getMasuriLuate();

    final long f_idReclamatie = filtru.getIdReclamatie();
    final boolean showRezolvate = filtru.showRezolvate();
    final boolean showNeRezolvate = filtru.showNeRezolvate();

    final Timestamp dataStart = filtru.getDataStart();
    final Timestamp dataStop = filtru.getDataStop();

    final boolean perioadaChecked = filtru.isPerioadaChecked();

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

    final String localitate = filtru.getLocalitate();
    final String tipArtera = filtru.getTipArtera();
    final String strada = filtru.getStrada();
    final String nr = filtru.getNr();
    final String bloc = filtru.getBl();
    final String scara = filtru.getSc();
    final String ap = filtru.getAp();
    final String numeClient = filtru.getNumePrenumeClient();
%>

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

<TABLE align=center border=0 cellPadding=10 cellSpacing=0 width="100%">
<TBODY>
<TR>
<TD>
<table align=center border=0 cellPadding=1 cellSpacing=0 width="100%" class="gsaptd">
<form id="submitForm" name="zaforma" action="<%=AppConstants.APP_NAME%>?action=apply-filtru-deranjamente" method="post" style="margin: 0">
<INPUT TYPE="hidden" NAME="action" VALUE="adaugaFiltruDeranjamente" />
<TBODY>
<TR>
    <TD colspan="2">
        <CENTER><span style="font-weight: bold; font-size: 15px">Configurare FILTRU Deranjamente</span></CENTER>
    </TD>
</TR>
<tr>
    <td>
        <table width="100%" border="0">
            <tr>
                <td width="50%">
                    <fieldset>
                        <legend><input VALUE="1" type="checkbox" name="perioada_checked" id="perioada_checked" onclick="enableDateInputs( this)" <%=perioadaChecked ? "checked" : ""%> > <label for="perioada_checked">Perioada</label></legend>
                        &nbsp;&nbsp;<input type="text" id="data_start" name="fd_data_start" size="16" value="<%=value_data_start%>" <%=perioadaChecked ? "" : "disabled"%>  /> <a href="#" id="trigger_data_start" ><img src="<%=AppConstants.WEB_RESOURCE_PATH%>/images/cal.gif" width="16" height="16" border="0" alt="Click pt. a selecta data."></a> -
                        <input type="text" id="data_stop" name="fd_data_stop" size="16" value="<%=value_data_stop%>" <%=perioadaChecked ? "" : "disabled"%> /> <a href="#"  id="trigger_data_stop" ><img src="<%=AppConstants.WEB_RESOURCE_PATH%>/images/cal.gif" width="16" height="16" border="0" alt="Click pt. a selecta data."></a>
                    </fieldset>
                </td>
                <td>
                    <fieldset>
                        <legend>Starea deranjamentelor ce vor fi afisate</legend>
                        <input type="checkbox" name="fd_status_ne_rezolvate" id="nerezolvare" <%=showNeRezolvate ? "checked" : "" %>  value="1"> <label for="nerezolvare">Nerezolvate</label>&nbsp;&nbsp;
                        <input type="checkbox" name="fd_status_rezolvate" id="rezolvare" <%=showRezolvate ? "checked" : "" %>  value="1"> <label for="rezolvare">Rezolvate</label>
                    </fieldset>
                </td>
            </tr>
        </table>

        <script type="text/javascript">
            function enableDateInputs( check){
                $("data_start").disabled = !check.checked;
                $("data_stop").disabled = !check.checked;

                if( check.checked){
                    $("trigger_data_start").style.visibility = '';
                    $("trigger_data_stop").style.visibility = '';
                }else{
                    $("trigger_data_start").style.visibility = 'hidden';
                    $("trigger_data_stop").style.visibility = 'hidden';
                }
            }
        </script>
    </td>
</tr>
<tr>
    <td>
        <fieldset>
            <legend>Locatia: </legend>
            <table width="100%">
                <tr>
                    <td>
                        Filiala:
                        <SELECT name="<%=DeranjamentConstants.FILIALA_ID%>" onchange="fill_sucursala_select()" class="gSAPSelect">
                            <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() == filialaFiltru.getId()) ? "selected=\"true\" " : ""%>value="<%=filiale[i].getId()%>"><%=filiale[i].getName()%></OPTION>
                            <%} %>
                        </SELECT>&nbsp;&nbsp;

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

                        C.E.:
                                             <span id="centruDiv">
                                                 <SELECT id="<%=DeranjamentConstants.SECTIE_ID%>" name="<%=DeranjamentConstants.SECTIE_ID%>" class="gSAPSelect">
                                                     <option value="-1">Selectati:</option>
                                                 </SELECT>
                                             </span>&nbsp;&nbsp;


                        <%if(GlobalAppConstants.CIR_ACTIV){%>
                        <br>
                        CIR:
                        <select name="codCIR" class="gSAPSelect" style="margin-top: 5px;">
                            <option value="-1">Selectati:</option>
                            <% final Nomenclator[] cirs = NomAccessDB.getAllNom( NomConstants.NOM_CIR);%>
                            <% for (int i = 0; i < cirs.length; i++) {
                                final Nomenclator cir = cirs[i]; %>
                            <option value="<%=cir.getCod()%>" <%=filtru.getCir() != null && filtru.getCir().getCod() == cir.getCod()? "selected" : ""%> ><%=cir.getDescriere()%></option>
                            <%}%>
                        </select>
                        <div id="xx">Text is here</div>
                        <%}%>

                        <script type="text/javascript">

                            function fill_sucursala_select(selectedValue, disabled, firstShow){

                                resetComboLeaveFirstOption( $('<%=DeranjamentConstants.SUCURSALA_ID%>'));
                                resetComboLeaveFirstOption( $('<%=DeranjamentConstants.SECTIE_ID%>'));

                                var filialaId = document.zaforma.<%=DeranjamentConstants.FILIALA_ID%>[ document.zaforma.<%=DeranjamentConstants.FILIALA_ID%>.selectedIndex].value;

                                if( filialaId > -1){

                                    var params = "parentId="+filialaId + "&selectName=<%=DeranjamentConstants.SUCURSALA_ID%>"+"&selectedValue=" + selectedValue;

                                    getCategoriesFromServer(params, function( originalRequest){

                                        // Problem with DOM, solved getting element by id and not within the form, also used html from jquery and not javascript innerHTML

                                        $('sucursalaDiv').innerHTML = getResponseMesg (originalRequest.responseText);

                                        $('<%=DeranjamentConstants.SUCURSALA_ID%>').onchange=fill_centru_select;

                                        if( disabled){
                                            removeOptionsLeaveThisOne($('<%=DeranjamentConstants.SUCURSALA_ID%>') , selectedValue);
                                        }

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

                            function fill_centru_select(selectedValue, disabled){

                                resetComboLeaveFirstOption( $('<%=DeranjamentConstants.SECTIE_ID%>'));

                                var sucursalaId = $('<%=DeranjamentConstants.SUCURSALA_ID%>').options[ $('<%=DeranjamentConstants.SUCURSALA_ID%>').selectedIndex].value;

                                if( sucursalaId > -1){
                                    var params = "parentId="+sucursalaId + "&selectName=<%=DeranjamentConstants.SECTIE_ID%>" + "&selectedValue=" + selectedValue;

                                    getCategoriesFromServer(params,function(originalRequest){

                                        $('centruDiv').innerHTML = getResponseMesg (originalRequest.responseText);

                                        if( disabled){
                                            removeOptionsLeaveThisOne($('<%=DeranjamentConstants.SECTIE_ID%>'), selectedValue);
                                        }
                                    });
                                }
                            }


                            function removeOptionsLeaveThisOne(oCombo, valueToLeave){

                                for (var i = 0; i < oCombo.options.length;) {

                                    if( oCombo.options[i].value == valueToLeave){ i++;
                                    }else{
                                        oCombo.remove(i);
                                    }
                                }
                            }

                            <%if( user.getCcLevel() != RoleConstants.NIVEL_FULL){%>
                                removeOptionsLeaveThisOne( document.zaforma.<%=DeranjamentConstants.FILIALA_ID%>, <%=filialaFiltru.getId()%>);
                            <%}%>


                            fill_sucursala_select(<%=sucursalaFiltru.getId()%>, <%=user.getCcLevel() == RoleConstants.NIVEL_SUCURSALA || user.getCcLevel() == RoleConstants.NIVEL_CENTRU || user.getIeLevel() == RoleConstants.NIVEL_FORMATIE%>, true);
                        </script>
                    </td>
                </tr>
            </table>
        </fieldset>
    </td>
</tr>
<tr>
    <td>
        <fieldset>
            <legend>&nbsp;Date reclamatie:</legend>
            <table width="100%" border="0">
                <tr>
                    <td colspan="3">Nume Prenume Client</td>
                    <td>ID reclamatie</td>
                </tr>
                <tr>
                    <td colspan="3"><input class="gsapinputtext" type="text" size="50" name="<%=ReclamatieConstants.NUME_CLIENT%>" value="<%=AppConstants.format( numeClient)%>"></td>
                    <td><input type="text" class="gsapinputtext" name="idReclamatie" value="<%=f_idReclamatie != -1 ? String.valueOf(f_idReclamatie) : ""%>"></td>
                </tr>
                <tr>
                    <td colspan="2">Localitate</td>
                    <td>TipArtera</td>
                    <td>Denumire</td>
                    <td>Nr</td>
                    <td>
                        <!--NLC-->
                    </td>
                </tr>
                <tr>
                    <td colspan="2">
                        <input class="gsapinputtext" style="width: 160px" id="<%=ReclamatieConstants.MUNICIPIU%>" name="<%=ReclamatieConstants.MUNICIPIU%>" value="<%=AppConstants.format( localitate)%>">
                    </td>
                    <td>
                        <input class="gsapinputtext" style="width: 100px" type=text name="<%=ReclamatieConstants.TIP_ARTERA%>" onchange="onChangeTipArtera()" value="<%=AppConstants.format( tipArtera)%>">
                    </td>
                    <td>
                        <input type="hidden" name="<%=ReclamatieConstants.COD_STRADA%>" id="<%=ReclamatieConstants.COD_STRADA%>"  value="-1">
                        <input class="gsapinputtext" style="width: 240px" name="<%=ReclamatieConstants.STRADA%>" id="<%=ReclamatieConstants.STRADA%>" value="<%=AppConstants.format( strada)%>">
                    </td>
                    <td>
                        <input onfocus="validateForNumar()"  class="gsapinputtext" style="width: 60px" type="text" value="<%=AppConstants.format( nr)%>" name="<%=ReclamatieConstants.NR%>" id="<%=ReclamatieConstants.NR%>">
                    </td>
                    <td>
                        <%--<input class="gsapinputtext" style="width: 100px" id="NLC" value="">--%>
                    </td>
                </tr>
                <tr>
                    <td>Bloc</td>
                    <td>Scara</td>
                    <td>Ap.</td>

                </tr>
                <tr>
                    <td><input onfocus="validateForBloc()" class="gsapinputtext" type="text" size="5" value="<%=AppConstants.format( bloc)%>" name="<%=ReclamatieConstants.BLOC%>" id="<%=ReclamatieConstants.BLOC%>" ></td>
                    <td><input class="gsapinputtext" type="text" size="5" value="<%=AppConstants.format( scara)%>" name="<%=ReclamatieConstants.SCARA%>" id="<%=ReclamatieConstants.SCARA%>" ></td>
                    <td><input class="gsapinputtext" type="text" size="5" value="<%=AppConstants.format( ap)%>" name="<%=ReclamatieConstants.AP%>"    id="<%=ReclamatieConstants.AP%>"    ></td>
                </tr>
            </table>
        </fieldset>
    </td>
</tr>
<tr>
    <td>
        <fieldset>
            <legend>&nbsp;Date deranjament:</legend>
            <table border="0" width="100%">
                <tr>
                    <td width="100"> <label for="numarDer">Numar:</label></td>
                    <td> <input id="numarDer" class="gsapinputtext" type="text" size="8" value="<%=filtru.getNrDeranjament()>0? String.valueOf(filtru.getNrDeranjament()):""%>" name="<%=DeranjamentConstants.ID%>" > </td>

                    <td width="150"> <label for="catInst">Categoria de instalatii:</label> </td>
                    <td>
                        <select id="catInst" class="gSAPSelect" name="<%=DeranjamentConstants.CAT_INSTALATII%>">
                            <OPTION VALUE="-1">Selectati:</OPTION>
                            <% for (int i = 1; i < DeranjamentConstants.ARR_CAT_INSTALATII.length; i++) {
                                final String ci = DeranjamentConstants.ARR_CAT_INSTALATII[i];%>
                            <option value="<%=i%>" <%=catInstalatii == i ? "selected" : ""%> ><%=ci%></option>
                            <% }%>
                        </select>
                    </td>
                </tr>
                <tr>
                    <td><label for="fortaMajora">Forta majora:</label></td>
                    <td>
                        <select id="fortaMajora" 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>
                    </td>

                    <td> <label for="masuriLuate">Masuri luate:</label></td>
                    <td>
                        <select id="masuriLuate" class="gSAPSelect" name="<%=DeranjamentConstants.MASURI_LUATE%>" style="height:20px">
                            <option value="-1">Selectati:</option>
                            <% for (int i = 1; i < DeranjamentConstants.MASURI_LUATE_ARR.length; i++) {
                                final String s = DeranjamentConstants.MASURI_LUATE_ARR[i]; %>
                            <option value="<%=i%>" <%=masuriLuate == i ? "selected" : ""%> ><%=s%></option>
                            <%} %>
                        </select>
                    </td>
                </tr>
            </table>
        </fieldset>
    </td>
</tr>
<tr>
    <td></td>
</tr>
<tr>
    <td colspan="2" align="center">
        <input id="aplica_button" type="button" value="Aplică filtru" onclick="checkSelects()">&nbsp;&nbsp;
        <%--<input type="button" onClick="resetFiltru()" value="Reset">&nbsp;&nbsp;--%>
        <input type="button" value="Inchide" onclick="window.close()">
    </td>
</tr>
</TBODY>
<input type="hidden" name="SUCURSALA_ID2"/>
<input type="hidden" name="SECTIE_ID2"/>

</FORM>
</TABLE>
</TD>
</TR>
</TBODY>
</TABLE>


<script type="text/javascript">

    function checkSelects(){

        // we get the values from the html document and not the form

        var sucursalaId = jQuery('#<%=DeranjamentConstants.SUCURSALA_ID%>').val();
        var sectieId = jQuery('#<%=DeranjamentConstants.SECTIE_ID%>').val();

        // hack to fill hiddens before submit

        jQuery('[name="SUCURSALA_ID2"]').val(sucursalaId);
        jQuery('[name="SECTIE_ID2"]').val(sectieId);
        jQuery("#submitForm").submit();
    }

    function resetFiltru(){
        var elements = Form.getElements(document.zaforma);
        for( var i = 0; i < elements.length; i++){
            var el = elements[i];
            if( el.type == "checkbox") el.checked =  false;
            else if( el.type == "text") el.value = "";
            else if( el.type == "radio") el.checked = false;
        }

        var selects = document.zaforma.getElementsByTagName("select");
        for( var i = 0; i < selects.length; i++){
            var selectu = selects[i];
            selectu.selectedIndex = 0;
        }
    }

    function checkLocalitateData(){
        if( document.zaforma.<%=ReclamatieConstants.MUNICIPIU%>.value.trim().length == 0){
            alert( 'Selectati localitatea');
            document.zaforma.<%=ReclamatieConstants.MUNICIPIU%>.focus();
            return false;
        }

        if( document.zaforma.<%=ReclamatieConstants.TIP_ARTERA%>.value.trim().lentgh == 0){
            alert( 'Selectati tip artera !');
            document.zaforma.<%=ReclamatieConstants.TIP_ARTERA%>.focus();
            return false;
        }

        if( document.zaforma.<%=ReclamatieConstants.STRADA%>.value.trim().length == 0){
            alert( 'Selectati strada !');
            document.zaforma.<%=ReclamatieConstants.STRADA%>.focus();
            return false;
        }

        return true;
    }

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

        if( document.zaforma.<%=ReclamatieConstants.STRADA%>.value.length == 0){
            alert( 'Selectati o strada !');
            document.zaforma.<%=ReclamatieConstants.STRADA%>.focus();
            return false;
        }
        return true;
    }

    function validateForBloc(){
        if( validateForNumar()){
            <%--if( document.zaforma.<%=ReclamatieConstants.NR%>.value.length == 0){--%>
            <%--alert( 'Introduceti un numar !');--%>
            <%--document.zaforma.<%=ReclamatieConstants.NR%>.focus();--%>
            <%--return false;--%>
            <%--}--%>
        }
        return true;
    }

    function onChangeTipArtera(){
        document.zaforma.<%=ReclamatieConstants.COD_STRADA%>.value = '-1';
        document.zaforma.<%=ReclamatieConstants.STRADA%>.value = '';
    }

    var ac_localitate = new AutoAssist("<%=ReclamatieConstants.MUNICIPIU%>", function() {
        return "<%=GlobalAppConstants.APP_NAME%>?action=callcenter_cautLocalitate&q=" + this.txtBox.value;
    });

    var ac_tipArtera = new AutoAssist("<%=ReclamatieConstants.TIP_ARTERA%>", function() {
        return "<%=GlobalAppConstants.APP_NAME%>?action=callcenter_cautTipArtera&q=" + this.txtBox.value;
    });

    var ac_strada = new AutoAssist("<%=ReclamatieConstants.STRADA%>", function() {
        return "<%=GlobalAppConstants.APP_NAME%>?action=callcenter_cautStrada&q=" + this.txtBox.value +
                "&loc="+document.zaforma.<%=ReclamatieConstants.MUNICIPIU%>.value +
                "&tipArtera=" + document.zaforma.<%=ReclamatieConstants.TIP_ARTERA%>.value;
    });

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

    enableDateInputs($("perioada_checked"));
</script>
