<%@ page import="ro.emid.common.types.Nomenclator" %>
<%@ page import="ro.emid.common.db.NomAccessDB" %>
<%@ page import="ro.emid.common.types.Reclamatie" %>
<%@ page import="ro.emid.common.constants.*" %>
<%@ page import="ro.emid.common.db.CategoryAccessDB" %>
<%@ page import="org.apache.log4j.Logger" %>
<%@ page import="ro.emid.common.utils.*" %>

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

<%

    int trimiteLa = -1;
    final Object o = session.getAttribute(ro.emid.common.constants.SessionConstants.TRIMITE_LA_TIP);
    if (o != null) trimiteLa = ((Integer) o).intValue();

    if (trimiteLa == -1) {
        trimiteLa = Reclamatie.LEGAT_LA_INCIDENT;
    }
%>

<style type="text/css">
    #reclamatiiTableContainer{
        width: 100%;
        height: 470px;
    }

    #destinationObjectTableContainer{
        height: 470px;
        width: 100%;
    }

    fieldset{
        margin: 2px;
    }


    .bb{
        border-bottom:#cccccc 1px solid;
    }

    .left-side{
        float: left;
        width: 60%;
    }

    .right-side{
        float: right;
        width: 39.5%;
    }

    .top-side{

    }
</style>

<form id="zaforma" name="zaforma" action="<%=AppConstants.APP_NAME%>" method="post" style="margin-top: 0px">
<table width="100%" border="0">
    <INPUT TYPE="hidden" NAME="action" VALUE="save-atasare-reclamatii" />
    <tr valign="top">
        <td colspan="2">
            <div class="left-side">
                <div class="top-side">
                    &nbsp;Lista Reclamatii:&nbsp;

                    <% Long []ids = UserUtils.getIdLocatiiFull(user); %>
                    <% if( ids != null && ids.length > 0){ %>
                    &nbsp;&nbsp;
                    <select id="zonaSelectata" name="zonaSelectata" onchange="loadReclamatii();" class="gSAPSelect">
                        <% if( ids.length > 1){ %>
                        <option value="-1">Toate locatiile:</option>
                        <% } %>
                        <% for (int i = 0; i < ids.length; i++) {

                            long idLocatie = ids[i].longValue();

                            Category c = CategoryAccessDB.getById(idLocatie);

                            if(c != null){%>
                        <option value="<%=c.getId()%>"><%=c.getName()%></option>
                        <%}%>
                        <%}%>
                    </select>
                    <% }%>

                    <%
                        final int tipCount = ro.emid.common.utils.ObjectUtils.getIntValue(session.getAttribute("tipCountReclamatii"), 1);
                    %>
                    <input type="radio" name="tipCount" value="1" id="100" <%=tipCount==1?"checked":""%> onclick="loadReclamatii(null, 1)"><label for="100">Ultimele 100</label>&nbsp;
                    <input type="radio" name="tipCount" value="2" id="all" <%=tipCount==2?"checked":""%> onclick="loadReclamatii(null, 2)"><label for="all">Toate</label>&nbsp;
                </div>
                <div id="reclamatiiTableContainer" class="tableContainer">
                    <!-- se incarca la apelul metodei loadReclamatii(); -->
                </div>
            </div>
            <div class="right-side" style="display: inline">
                <div class="top-side">
                    Lista &nbsp;&nbsp;
                    <select name="trimiteLa" onchange="loadDestinationObjectList(); $('configurareFiltru').focus();" class="gSAPSelect">
                        <option value="<%=Reclamatie.LEGAT_LA_INCIDENT%>" <%=trimiteLa == Reclamatie.LEGAT_LA_INCIDENT ? "selected=\"selected\"" : ""%> >Incidente</option>
                        <option value="<%=Reclamatie.LEGAT_LA_DERANJAMENT%>" <%=trimiteLa == Reclamatie.LEGAT_LA_DERANJAMENT ? "selected=\"selected\"" : ""%> >Deranjamente</option>

                        <% if(AppConstants.MODUL_LP1_ENABLED ){ %>
                            <option value="<%=Reclamatie.LEGAT_LA_LUCRARE%>" <%=trimiteLa == Reclamatie.LEGAT_LA_LUCRARE ? "selected=\"selected\"" : ""%> >LP</option>
                            <option value="<%=Reclamatie.LEGAT_LA_LUCRARE2%>" <%=trimiteLa == Reclamatie.LEGAT_LA_LUCRARE2 ? "selected=\"selected\"" : ""%> >LP2</option>
                        <% }else{ %>
                            <option value="<%=Reclamatie.LEGAT_LA_LUCRARE2%>" <%=trimiteLa == Reclamatie.LEGAT_LA_LUCRARE2 ? "selected=\"selected\"" : ""%> >LP</option>
                        <% } %>
                    </select>
                    &nbsp; <input type="button" id="configurareFiltru" title="Click pentru a specifica criterii de filtrare" onclick="showFiltru()" value="Configurare filtru"/>&nbsp;
                </div>
                <div id="destinationObjectTableContainer" class="tableContainer">
                    <!-- se incarca la apelul metodei loadDestinationObjectList(); -->
                </div>
            </div>
        </td>
    </tr>

    <tr>
        <td align="left">
            <%if(GlobalAppConstants.CIR_ACTIV){%>
                <% final Nomenclator[] ciruri = NomAccessDB.getAllNom(NomConstants.NOM_CIR); %>
                Retransmite catre:&nbsp;
                <select name="<%=ReclamatieConstants.COD_CIR%>" class="gSAPSelect" onchange=" enableRetransmiteButton()">
                    <option value="-1">Selectati:</option>
                    <% for (int i = 0; i < ciruri.length; i++) { %>
                        <option value="<%=ciruri[i].getCod()%>" ><%=ciruri[i].getDescriere()%></option>
                    <%} %>
                </select>&nbsp;&nbsp;
                <input type="button" name="retransmiteButton" onclick="retransmitere()" value="Retransmite" /> &nbsp;&nbsp;
            <%}%>
            <input type="button" name="arhivareButton" disabled="disabled" onclick="arhivareReclamatii()" value="Arhivare Reclamatii" />
        </td>
        <td align="right">
            <input type="button" name="save" value="Atasare Reclamatii" disabled onclick="onSalveaza()">
            <%--<input type="button" value="Inchide fereastra" onclick="window.close()">--%>
        </td>
    </tr>
</table>
</form>

<form name="refresh" action="<%=GlobalAppConstants.APP_NAME%>" method="post">
    <input type="hidden" name="action" value="callcenter_legareReclamatii">
</form>


<span id="waitPopup" style="position: absolute; left: 0; top: 0; font-size: 12px; background-color: #ff6666; color: black; display: none">
    Va rugam asteptati ...
</span>

<span id="messagePopup" style="padding:5px; font-weight:bold; z-index: 10000; position: absolute; left: 200px; top: 50px; font-size: 12px; border:1px solid red; background-color: #ffffcc; color: black; display: none">
    <span id="messageContainer">Message goes here ...</span>&nbsp; <a href="javascript: onOK();">OK</a>
</span>


<embed src="<%=AppConstants.WEB_RESOURCE_PATH%>/newItems.wav" autostart=false width=0 height=0 id="newItems" enablejavascript="true">

<%--<button onclick="simulateNewMessage()">New Message</button>--%>



<script type="text/javascript">
    function simulateNewMessage(){
        showPopupMessage("A fost inregistrata o noua reclamatie");
        playNewItems();
    }

    function playNewItems() {
        try{
            var thissound=document.getElementById("newItems");
            thissound.Play();
        }catch(e){
        }
    }

    function showPopupMessage( message){
        $("messageContainer").innerHTML = message;
        Element.show( "messagePopup");
    }
    
    function onOK(){
        $("messageContainer").innerHTML = "";
        Element.hide("messagePopup");
    }

    function arhivareReclamatii(){
        var countReclamatii = getCountReclamatiiSelected();

        if( countReclamatii > 0){
            var message = "Doriti sa ARHIVATI reclamatiile selectate ?";
            if( confirm( message)){
                document.zaforma.action.value = "callcenter_arhivareReclamatii";
                document.zaforma.submit();
            }
        }
    }

    function enableArhivare(){
        document.zaforma.arhivareButton.disabled = getCountReclamatiiSelected() == 0;
    }

    function onReclamatieChecked(oCheck, fromCheck){
        if( !fromCheck) oCheck.checked = !oCheck.checked;
        hightLightRow(oCheck, 'checked', 'normal')
        enableSave();
        enableRetransmiteCir();
        enableArhivare();

        var params = "idReclamatie="+oCheck.value + "&checked="+(oCheck.checked?1:0);
        new Ajax.Request('<%=GlobalAppConstants.APP_NAME%>?action=callcenterSetReclamatieChecked',
            {
                    method: 'post',
                    parameters: params,
                    onComplete: function ( originalRequest){
                        // nothing ...
                    }
            }
        );
    }

    var lastRadio = null;
    var trimiteLaSelected = false;
    function onObjectChecked( oRadio){
        trimiteLaSelected = true;

        if( lastRadio != null) hightLightRow(lastRadio, 'checked', 'normal')
        hightLightRow( lastRadio = oRadio, 'checked', 'normal')
        enableSave();
    }
    

    /* de pastrat in sesiune :
        - order column
        - order type la reclamatii
        - reclamatii checked
        - destionationObjectType
    */

    /**
     * Incarca Html pt tabelul cu reclamatii.
     * oAnchor este colana dupa care se vrea ordonarea
     */
    function loadReclamatii( oAnchor, tipCountReclamatii){
        var params = "";
        if( oAnchor){
            var sortColumn = oAnchor.getAttribute("sortColumn");
            var sortType   = oAnchor.getAttribute("sortType");

            params = "sortColumn="+sortColumn+"&sortType="+sortType;
        }

        if( tipCountReclamatii){
            params+="&tipCountReclamatii="+tipCountReclamatii;
        }

        var zonaSelect = $("zonaSelectata");
        if( zonaSelect ){
            params+="&zonaSelectata="+$F("zonaSelectata");
        }

        $("reclamatiiTableContainer").innerHTML = "Se incarca ...";
        new Ajax.Request('<%=AppConstants.APP_NAME%>?action=get-table-reclamatii-noi',
            {
                    method: 'post',
                    parameters: params,
                    onComplete: function (originalRequest){
                        try{
                            var response = getResponseMesg( originalRequest.responseText);
                            $("reclamatiiTableContainer").innerHTML = response;
                            startTimeoutCheckReclamatiiNoi();
                            enableSave();
                            enableArhivare();
                        }catch(e){
                            alert("Eroare la incarcare lista reclamatii\n  Error: " + e.message);
                        }
                    }
            }
        );
    }

    /**
     * Incarca Html pt tabelul cu obiecte la care se ataseaza reclamatiile (Lucrari programate/Deranjamente/Little Incidente)
     * Tipul obiectelor este stabilit de selectul "trimiteLa"
     */
    function loadDestinationObjectList( oAnchor){
        lastRadio = null;
        trimiteLaSelected = false;
        var params = "trimiteLa=" + $F(document.zaforma.trimiteLa);
        if( oAnchor){
            var sortColumn = oAnchor.getAttribute("sortColumn");
            var sortType   = oAnchor.getAttribute("sortType");

            params += "&sortColumn="+sortColumn+"&sortType="+sortType;
        }
        $("destinationObjectTableContainer").innerHTML = "Se incarca ...";
        new Ajax.Request('<%=AppConstants.APP_NAME%>?action=callcenterGetTableDestinationObject',
            {
                    method: 'post',
                    parameters: params,
                    onComplete: function (originalRequest){
                        try{
                            var response = getResponseMesg( originalRequest.responseText);
                            $("destinationObjectTableContainer").innerHTML = response;

                            ScriptsUtils.evalScripts( response, true);
                            enableSave();
                        }catch(e){
                            alert("Eroare la incarcare lista obiecte destinatie\n  Error: " + e.message);
                        }
                    }
            }
        );
    }


    var CHECK_RECLAMATII_NOI_TIMEOUT = 30*1000;
    function checkReclamatiiNoi(){
        var params = "";
        new Ajax.Request('<%=AppConstants.APP_NAME%>?action=check-reclamatii-noi',
            {
                method: 'post',
                parameters: params,
                onComplete: function ( originalRequest){
                        try{
                            var response = getResponseMesg( originalRequest.responseText);
                            if( response == null) response = "";
                            response = response.trim();
//                            alert( response);
                            var respObj = eval("(" + response + ")");

                            var diferenta = respObj.diferentaCountReclamatii;
                            if( diferenta == 0){
                                startTimeoutCheckReclamatiiNoi();
                            }else{
                                alertReclamatiiNoi( diferenta);
                                loadReclamatii();
                            }
                        }catch( e){
                            alert( "Eroare La incarcare Reclamatii:\n  Server response: " + response + "\n  Exception: " + e.message);
                        }
                    }
            });
    }

    function alertReclamatiiNoi( count){
        var message = "";
        if( count > 1){
            message = "Au fost inregistrate "+ count  + " reclamatii noi";
        }else if( count == 1){
            message = "A fost inregistrata o reclamatie noua ";
        }else if( count == -1){
            message = "A fost atasata o reclamatie";
        }else if( count < -1){
            message = "Au fost atasate "+ (-1 * count)  + " reclamatii";
        }
//        return confirm( message)
//        alert( message);
        showPopupMessage( message);
        playNewItems();
    }

    function enableSave(){
        document.zaforma.save.disabled = getCountReclamatiiSelected() == 0 || !trimiteLaSelected;
    }

    function enableRetransmiteCir(){
        try{
            document.zaforma.<%=ReclamatieConstants.COD_CIR%>.disabled = ( getCountReclamatiiSelected() == 0);

            enableRetransmiteButton();
        }catch(e){}
    }

    function enableRetransmiteButton(){
        try{
            document.zaforma.retransmiteButton.disabled = document.zaforma.<%=ReclamatieConstants.COD_CIR%>.disabled || document.zaforma.<%=ReclamatieConstants.COD_CIR%>.selectedIndex == 0;
        }catch(e){}
    }

    function getCountReclamatiiSelected(){
        var countReclamatiiSelected = 0;
        var arr = getAllCheckReclamatii();
        for( var i = 0; i < arr.length; i++ ){
            if( arr[i].checked) countReclamatiiSelected++;
        }
        return countReclamatiiSelected;
    }

    function  retransmitere(){
        var savedAction = document.zaforma.action.value;
        try{
            var countReclamatii = getCountReclamatiiSelected();
            if( countReclamatii == 0 || document.zaforma.<%=ReclamatieConstants.COD_CIR%>.selectedIndex == 0){
                return;
            }
            var selectedCir = document.zaforma.<%=ReclamatieConstants.COD_CIR%>.options[ document.zaforma.<%=ReclamatieConstants.COD_CIR%>.selectedIndex].text;
            if( confirm("Doriti sa retransmiteti "+(countReclamatii==1?" o reclamatie" :  countReclamatii + " reclamatii") + " catre " + selectedCir + " ?")){
                document.zaforma.action.value = "callcenter_retransmiteReclamatii";
                document.zaforma.submit();
            }
        }catch(e){
            document.zaforma.action.value = savedAction;
            alert( e.message);
        }
    }


    function toggleReclamatii(index){
        if( $('reclamatii' + index).style.display == 'none'){
            $('img' +index).src = '<%=AppConstants.WEB_RESOURCE_PATH + "/images/minus.bmp"%>';
            Element.show('reclamatii' + index);
        }else{
            $('img' +index).src = '<%=AppConstants.WEB_RESOURCE_PATH + "/images/plus.bmp"%>';
            Element.hide('reclamatii' + index);
        }
    }
    

    function startTimeoutCheckReclamatiiNoi(){
        setTimeout( "checkReclamatiiNoi()", CHECK_RECLAMATII_NOI_TIMEOUT);
    }

    function getAllCheckReclamatii(){
        return document.getElementsByName( 'reclamatieId');
    }

    function checkAllReclamatii( oCheck){
        var arr = getAllCheckReclamatii();
        for( var i = 0; i < arr.length; i++){
            arr[ i].checked = !oCheck.checked;
            onReclamatieChecked(arr[ i] , false);
        }
    }

    function onSalveaza(){
        var countReclamatii = getCountReclamatiiSelected();
        var trimiteLaSelected = true;
        if( countReclamatii > 0 && trimiteLaSelected){
            var catreText = lastRadio.getAttribute("catre");
            var message = "Doriti sa atasati " + (countReclamatii == 1 ? " o reclamatie" : countReclamatii + " reclamatii") + " catre " + catreText + " ?";
            if( confirm( message)){
                document.zaforma.submit();
            }
        }
    }

    function reloadDeranjamente(){
        loadDestinationObjectList();
    }

    function showFiltru(){
        var trimiteLa = $F(document.zaforma.trimiteLa);

        if( trimiteLa == <%=Reclamatie.LEGAT_LA_INCIDENT%>){
            showFiltruLittleIncidente();
        }else if( trimiteLa == <%=Reclamatie.LEGAT_LA_DERANJAMENT%>){
            showFiltruDeranjamente();
        }else if( trimiteLa == <%=Reclamatie.LEGAT_LA_LUCRARE%> || trimiteLa == <%=Reclamatie.LEGAT_LA_LUCRARE2%>){
            showFiltruLucrariProgramate();
        }else{
            alert( "ERROR: Tip Obiect destinatie necunoscut !!!");
        }
    }

    var filtruLittleIncidenteWindow = null;
    function showFiltruLittleIncidente(){
        if( filtruLittleIncidenteWindow != null) filtruLittleIncidenteWindow.close();
        filtruLittleIncidenteWindow = window.open('<%=GlobalAppConstants.APP_NAME%>?action=filtru-incidente','filtruLittleIncidente', 'top=100,left=100,width=750, height=500, status=yes,resizable=yes,dependent=yes,alwaysRaised=yes');
    }


    var filtruLucrariWindow = null;
    function showFiltruLucrariProgramate(){
        if( filtruLucrariWindow != null) filtruLucrariWindow.close();
        filtruLucrariWindow = window.open('<%=GlobalAppConstants.APP_NAME%>?action=showFiltruLucrari','filtruLucrari', 'top=100,left=100,width=750, height=500, status=yes,resizable=yes,dependent=yes,alwaysRaised=yes');
    }
  
    function reloadListaLittleIncidente(){
//        alert( "reloadListaLittleIncidente:  Not implemented");
        loadDestinationObjectList();
    }

    function reloadListaLucrariProgramate(){
//        alert( "reloadListaLucrariProgramate:  Not implemented");
        loadDestinationObjectList();
    }

    function scoateReclamatieCuAjax(idReclamatie){
        if( confirm('Confirmati actiunea.'))
            new Ajax.Request('<%=AppConstants.APP_NAME%>?action=scoate-reclamatia2&id=' + idReclamatie,
            {
                method: 'post',
                onComplete: function( originalRequest){
                    window.location = '<%=AppConstants.APP_NAME%>?action=callcenter_legareReclamatii';
                }
            });
    }

    enableRetransmiteCir();
    enableRetransmiteButton();

    loadReclamatii();
    loadDestinationObjectList();
</script>
