<%@ page import="ro.emid.common.constants.AppConstants" %>
<%@ page import="ro.emid.common.constants.GlobalAppConstants" %>
<%@ page import="ro.emid.Application" %>
<%@ page import="ro.emid.lib.model.Maifi" %>
<%@ page import="ro.emid.common.components.sugest.base.SugestConstants" %>
<%@ page import="ro.emid.common.types.*" %>
<%@ page import="ro.emid.common.utils.StringUtils" %>
<%@ page import="ro.emid.callcenter.CallcenterSessionUtils" %>

<%
	Maifi maifi = (Maifi)request.getAttribute("maifi");
	String lfs = "";
	String[] lfsIds = maifi.getInstalatiiIds();
	
	Category centru =  CallcenterSessionUtils.getCentru(request.getSession());
	
	if(lfsIds.length > 0) {
		lfs = StringUtils.join(lfsIds, ",");
		
	}
	
%>

<form id="" name="zaforma" action="<%=AppConstants.APP_NAME%>?action=saveMaifi" method="post">
    <input type="hidden" name="id" value="<%=maifi.getId()%>">
    <input type="hidden" name="filialaId" value="<%=maifi.getFilialaId()%>">
    <input type="hidden" name="sucursalaId" value="<%=maifi.getSucursalaId()%>">
    <input type="hidden" name="centruId" value="<%=maifi.getCentruId()%>">
    <input type="hidden" name="formatiaDeLucruId" value="<%=maifi.getFormatiaDeLucruId()%>">
    <input type="hidden" id="instalatiiAfectate" name="instalatiiAfectate" value="<%=lfs%>" />
    <input type="hidden" id="instalatiiAfectate2" name="instalatiiAfectate2" value="<%=centru.getCodSap()%>" />

	<table class="gSAPTHEAD" cellspacing="1" cellpadding="2" width="100%" border="1">
		<tbody>
		<tr>
			<th class="gsapthead" nowrap="" colspan="2" height="25">&nbsp;Fisa Eveniment accidental:&nbsp; </th>
		</tr>
        <tr>
            <td width="25%"><b>1.</b> Numar curent eveniment:</td>
            <td width="100%">
                <input type="text" readonly="" name="numar" value="<%=maifi.getId() == -1 ? "" : maifi.getNumar()%>">
            </td>
        </tr>

        <tr>
            <td width="25%"><b>2.</b> Data producere:</td>
            <td width="100%">
                
				<div style="vertical-align: middle; display: inline-block">
					<input type="text" id="dataProducere" name="dataProducere" value="<%=maifi.getDataProducere()%>" onblur="updateDurataEveniment()" style="float: left;width:100px;">
					<img id="dataProducere-trigger" src="/emid-lpod/resources/images/cal.gif" border="0" alt="Calendar" style="margin-left: 3px;float: right;cursor: pointer">
				</div>

				<script type="text/javascript">
					//on page ready
					jQuery(function(){
						Calendar.setup({
							inputField  : "dataProducere",         // ID of the input field
							ifFormat    : "%d.%m.%Y %H:%M:%S",       // the date format
							button      : "dataProducere-trigger",         // ID of the button
							showsTime   : true,
							onUpdate : updateDurataEveniment
						});
					});
				</script>
				
				&nbsp;&nbsp;&nbsp;
				Data realimentare:


				<div style="vertical-align: middle; display: inline-block">
					<input type="text" id="dataRealimentare" name="dataRealimentare" value="<%=maifi.getId() == -1 ? "" : maifi.getDataRealimentare()%>" onblur="updateDurataEveniment()" style="float: left;width:100px;">
					<img id="dataRealimentare-trigger" src="/emid-lpod/resources/images/cal.gif" border="0" alt="Calendar" style="margin-left: 3px;float: right;cursor: pointer">
				</div>

				<script type="text/javascript">
					//on page ready
					jQuery(function(){
						Calendar.setup({
							inputField  : "dataRealimentare",         // ID of the input field
							ifFormat    : "%d.%m.%Y %H:%M:%S",       // the date format
							button      : "dataRealimentare-trigger",         // ID of the button
							showsTime   : true,
							onUpdate : updateDurataEveniment
						});
					});
				</script>
            </td>
        </tr>
        <tr>
            <td valign="top"><b>3.</b> Localizare Eveniment:&nbsp;</td>
			<td>
                <table class="gsapthead">
                    <tbody>
                    <tr valign="top" class="gSAPGroup">
                        <td>
                            <table style="font-size:13px">
                                <tbody><tr>
                                    <td valign="top" nowrap="">
                                        <table>
                                            <tbody><tr>
                                                <td>
                                                    <input name="tipInstalatieRadio" type="radio" <%=maifi.getTipInstalatieRadio() == 26 ? "checked" : ""%> value="26" id="radioStatie" onclick="onClickRadioTipInstalatie( this, 1);"><label for="radioStatie">Statie</label>
                                                </td>
                                                <td>
                                                    <input name="tipInstalatieRadio" type="radio" <%=maifi.getTipInstalatieRadio() == 15 ? "checked" : ""%> value="15" id="radioLinie" onclick="onClickRadioTipInstalatie( this, 1)"><label for="radioLinie">Linie</label>
                                                </td>
                                                <td>
                                                    <input name="tipInstalatieRadio" type="radio" <%=maifi.getTipInstalatieRadio() == 19 ? "checked" : ""%> value="19" id="radioPAPT" onclick="onClickRadioTipInstalatie( this, 1);"><label for="radioPAPT">PA/PT</label>
                                                </td>
                                            </tr>
                                        </tbody></table>
                                    </td>
                                </tr>
                                <tr>
                                    <td nowrap="">
                                        <input type="hidden" id="idInstalatie" name="idInstalatie" value="<%=maifi.getIdInstalatie()%>">
                                        <input id="denInstalatie" name="denInstalatie" class="gsapinputtext" size="60" maxlength="100" value="<%=maifi.getDenInstalatie()%>" autocomplete="off">

                                            
                                        <input id="tipInstalatie" type="hidden" name="tipInstalatie" class="gsapinputtext" size="10" maxlength="100" value="<%=maifi.getTipInstalatie()%>">

                                        &nbsp;&nbsp;&nbsp;
                                        U: <input id="u" name="u" class="gsapinputtext" size="7" maxlength="100" value="<%=maifi.getU()%>">
                                        [kV]
                                    </td>
                                </tr>
                                <tr id="radiosChildStatie" <%=maifi.getTipInstalatieRadio() == 26 ? "" : "style='display:none;'"%>>
                                    <td nowrap="">
                                        <br>
                                        <table>
                                            <tbody><tr>
                                                <td>
                                                    <input name="tipInstalatieRadio2" type="radio" <%=maifi.getTipInstalatieRadio2() == 5 ? "checked" : ""%> value="5" id="radioCelula" onclick="onClickRadioTipInstalatie( this, 2)"><label for="radioCelula">Celula</label>
                                                </td>
                                                <td>
                                                    <input name="tipInstalatieRadio2" type="radio" <%=maifi.getTipInstalatieRadio2() == 29 ? "checked" : ""%> value="29" id="radioTrafo" onclick="onClickRadioTipInstalatie( this, 2)"><label for="radioTrafo">Trafo</label>
                                                </td>
                                                <td>
                                                    <input name="tipInstalatieRadio2" type="radio" <%=maifi.getTipInstalatieRadio2() == 33 ? "checked" : ""%> value="33" id="radioBara" onclick="onClickRadioTipInstalatie( this, 2)"><label for="radioBara">Bara</label>
                                                </td>
                                                <td>
                                                    <input name="tipInstalatieRadio2" type="radio" <%=maifi.getTipInstalatieRadio2() == 30 ? "checked" : ""%> value="30" id="radioBobina" onclick="onClickRadioTipInstalatie( this, 2)"><label for="radioBobina">Bobina</label>
                                                </td>
                                            </tr>
                                        </tbody></table>
                                    </td>
                                </tr>
                                <tr id="instalatie2Inputs" <%=maifi.getTipInstalatieRadio() == 26 ? "" : "style='display:none;'"%>>
                                    <td>
                                        <input type="hidden" id="idInstalatie2" name="idInstalatie2" value="<%=maifi.getIdInstalatie2()%>">
                                        <input id="denInstalatie2" name="denInstalatie2" class="gsapinputtext" size="60" maxlength="100" value="<%=maifi.getDenInstalatie2()%>" autocomplete="off">

                                            
                                        <input id="tipInstalatie2" name="tipInstalatie2" type="hidden" class="gsapinputtext" size="10" maxlength="100" value="<%=maifi.getTipInstalatie2()%>">
                                        &nbsp;&nbsp;&nbsp;
                                        U: <input id="u2" name="u2" class="gsapinputtext" size="7" maxlength="100" value="<%=maifi.getU2()%>">
                                        [kV]
                                    </td>
                                </tr>
                            </tbody></table>
                        </td>
                    </tr>
                    </tbody>
                </table>
            </td>
        </tr>

        <tr>
            <td align="left"><b>4.</b>Descriere eveniment</td>
            <td>
        <textarea id="descriere" name="descriere" rows="6" maxlength="4000" cols="90" initialrows="6"><%=maifi.getDescriere()%></textarea>
            <span id="descrierecount" title="Numarul de caractere ramase de completat" style="font-size: 11px; color: black;">4000</span></td>
        </tr>
        <tr>
            <td align="left"><b>5.</b>Defect</td>
            <td>
        <textarea name="defect" id="defect" rows="3" maxlength="4000" cols="90" initialrows="3"><%=maifi.getDefect()%></textarea>
            <span id="defectcount" title="Numarul de caractere ramase de completat" style="font-size: 11px; color: black;">4000</span></td>
        </tr>
        <tr>
            <td align="left"><b>6.</b>Semnalizari</td>
            <td>
                Adaugare/Cautare: <input type="text" size="70" id="searchSemnalizare" class="gsapinputtext" onkeypress="return event.keyCode != 13" autocomplete="off"><br>
        <textarea rows="3" cols="90" id="semnalizari" maxlength="4000" name="semnalizari" initialrows="3"><%=maifi.getSemnalizari()%></textarea>
                    
            <span id="semnalizaricount" title="Numarul de caractere ramase de completat" style="font-size: 11px; color: black;">4000</span></td>
        </tr>
        <tr>
            <td align="left"><b>7.</b>Durata eveniment</td>
            <td>
                

                Minute: <input type="text" class="gsapinputtext" size="5" style="TEXT-ALIGN: right" autocomplete="off" id="durataOre" name="durataOre" value="0">&nbsp;
                Secunde: <input type="text" class="gsapinputtext" size="5" style="TEXT-ALIGN: right" autocomplete="off" id="durataMinute" name="durataMinute" value="0">
            </td>
        </tr>
        <tr>
            <td align="left"><b>8.</b>Putere Intrerupta</td>
            <td>
                <input type="text" class="gsapinputtext" style="TEXT-ALIGN: right" id="pi" name="pi" value="<%=maifi.getPi()%>">&nbsp;[kW]
                <input type="button" title="Selectati instalatiile afectate de eveniment" onclick="browseLFSearch()" value="Browse">
            </td>
        </tr>
        <tr>
            <td align="left"><b>9.</b>Gestionar</td>
            <td>
                <select name="SelectGestionar" id="SelectGestionarId" onchange="fillGestionarField(this)">
                    <option value="-1">Selectati gestionar</option>
                    
                </select>
                <input type="text" class="gsapinputtext" size="40" id="gestionar" name="gestionar" value="<%=maifi.getGestionar()%>">
            </td>
        </tr>
        <tr>
            <td align="left"><b>10.</b>Consumatori intrerupti</td>
            <td>
                <table>
					<tbody>
						<tr valign="top">
							<td>
								<table class="gSAPTHEAD" cellspacing="1">
									<tbody>
									<tr class="gSAPGroup" align="middle">
										<td>Inalta(IT)</td>
										<td>Medie(MT)</td>
										<td>Joasa(JT)</td>
									</tr>
									<tr>
										<td align="middle"><input class="gsapinputtext" style="TEXT-ALIGN: right" value="<%=maifi.getUtilizatoriIt()%>" onkeyup="updateTotalConsumatori()" autocomplete="off" id="utilizatoriIT" name="utilizatoriIT"></td>
										<td align="middle"><input class="gsapinputtext" style="TEXT-ALIGN: right" value="<%=maifi.getUtilizatoriMt()%>" onkeyup="updateTotalConsumatori()" autocomplete="off" id="utilizatoriMT" name="utilizatoriMT"></td>
										<td align="middle"><input class="gsapinputtext" style="TEXT-ALIGN: right" value="<%=maifi.getUtilizatoriJt()%>" onkeyup="updateTotalConsumatori()" autocomplete="off" id="utilizatoriJT" name="utilizatoriJT"></td>
									</tr>
									<tr>
										<td align="left">

										</td>
										<td align="right">
											<b>Total:</b>
										</td>
										<td align="center">
											<input type="text" class="gsapinputtext" style="TEXT-ALIGN: right" id="consumatoriIntr" name="consumatoriIntr" value="<%=maifi.getConsumatoriIntr()%>">
										</td>
									</tr>
									</tbody>
								</table>
							</td>
							<td width="10"></td>
							<td>
								<table class="gSAPTHEAD" cellspacing="1">
									<tbody>
									<tr class="gSAPGroup" align="middle">
										<td>Casnici</td>
										<td>Mici</td>
										<td>Mari</td>
									</tr>
									<tr>
										<td>
											<input class="gsapinputtext" style="TEXT-ALIGN: right" autocomplete="off" size="14" value="<%=maifi.getUtilizatoriCasnici()%>" id="utilizatoriCasnici" name="utilizatoriCasnici">
										</td>
										<td>
											<input class="gsapinputtext" style="TEXT-ALIGN: right" autocomplete="off" size="14" value="<%=maifi.getUtilizatoriMici()%>" id="utilizatoriMici" name="utilizatoriMici">
										</td>
										<td>
											<input class="gsapinputtext" style="TEXT-ALIGN: right" autocomplete="off" size="14" value="<%=maifi.getUtilizatoriMari()%>" id="utilizatoriMari" name="utilizatoriMari">
										</td>
									</tr>
									</tbody>
								</table>
							</td>
						</tr>
					</tbody>
				</table>
            </td>
        </tr>
        <tr>
            <td align="left"><b>11.</b>Observatii suplimentare</td>
            <td>
        <textarea rows="3" cols="90" name="observatii" id="observatii" maxlength="4000" initialrows="3"><%=maifi.getObservatii()%></textarea>
            <span id="observatiicount" title="Numarul de caractere ramase de completat" style="font-size: 11px; color: black;">4000</span></td>
        </tr>
        <tr>
            <td colspan="2" align="center">
                <input id="saveMaifi" type="button" value="Salveaza">&nbsp;&nbsp;&nbsp;
                <input type="button" onclick="window.location = '<%=AppConstants.APP_NAME%>?action=showMaifi'" value="Renunta">
            </td>
        </tr>
		</tbody>
	</table>
</form>

<script type="text/javascript">

var tipInstalatieSelected = <%=maifi.getTipInstalatieRadio()%>;
var tipInstalatieSelected2 = <%=maifi.getTipInstalatieRadio2()%>;

function onClickRadioTipInstalatie(oRadio, t) {
    if ($("radioStatie").checked) {
        Element.show("radiosChildStatie");
        Element.show("instalatie2Inputs");

    } else {
        Element.hide("radiosChildStatie");
        Element.hide("instalatie2Inputs");
        $('idInstalatie2').value = '';
        $('denInstalatie2').value = '';
    }

    if (t == 1) {
        $('denInstalatie').disabled = false;
        $('denInstalatie').value = "";
        $('tipInstalatie').value = "";
        $('u').value = "";
        $('denInstalatie').focus();
    } else if (t == 2) {
		$('denInstalatie2').disabled = false;
        $('denInstalatie2').value = "";
        $('tipInstalatie2').value = "";
        $('u2').value = "";
        $('denInstalatie2').focus();
    }

    if (oRadio) {
        if (t == 1) {
            tipInstalatieSelected = oRadio.value;
        }
        if (t == 2) {
            tipInstalatieSelected2 = oRadio.value;
        }
    }
}

function getDate(inputId) {
    var strDate = $(inputId).value;
	
    //if (strDate.length != 16) return null;
    return Date.parseDate(strDate, "%d.%m.%Y %H:%M:%S");
}

function updateDurataEveniment() {
    var dataProducere = getDate('dataProducere');
    var dataRealimentare = getDate('dataRealimentare');

    var ore = '';
    var minute = '';

    if (dataProducere != null && dataRealimentare != null) {
		
		var secProducere = parseInt($('dataProducere').value.split(' ')[1].split(':')[2]);
		var secRealimentare = parseInt($('dataRealimentare').value.split(' ')[1].split(':')[2]);
		
		console.log(secProducere);
		console.log(secRealimentare);
		
		var durataProducere = ((dataRealimentare.getTime() + (secRealimentare * 1000)) - (dataProducere.getTime() + (secProducere * 1000)))/1000;
		ore = Math.floor(durataProducere / 60);
		minute = (durataProducere % 60);
    }

    $("durataOre").value = ore;
    $("durataMinute").value = minute;
}

function updateEnergieSiNumarConsumatoriForPT(idPaPt) {
    new Ajax.Request("/emid-lpod/emid-lpod.default?action=getInstalatieInfoJSON", {
        method: "post",
        parameters: "idInstalatie=" + idPaPt,
        onComplete: function (originalRequest) {
            var response = getResponseMesg(originalRequest.responseText);

            try {
                var json = eval("(" + response + ")");
                if (json && json.error) {
                    alert("eroare la get info PA/PT : " + json.error);
                } else {
                    setTotalConsumatoriFromBrowse(
                        json.putere,
                        json.totalConsumatori,
                        json.consumatori_IT,
                        json.consumatori_MT,
                        json.consumatori_JT,
                        json.consumatori_casnici,
                        json.consumatori_mici,
                        json.consumatori_mari,
                        true
                    );
                }
            } catch (e) {
                alert("eroare la get info PA/PT : " + e.message);
            }
        }
    });
}

function setTotalConsumatoriFromBrowse(pi, totalConsumatori, it, mt, jt, casnici, mici, mari, notifyOverwrite) {
    var completeaza = true;
    if (notifyOverwrite) {
        var t = safeNumber($("pi")) +
                safeNumber($("consumatoriIntr")) +
                safeNumber($("utilizatoriIT")) +
                safeNumber($("utilizatoriMT")) +
                safeNumber($("utilizatoriJT")) +
                safeNumber($("utilizatoriCasnici")) +
                safeNumber($("utilizatoriMici")) +
                safeNumber($("utilizatoriMari"));

        if (t > 0) {
            completeaza = confirm(
                    "Exista valori completate in cimpurile Putere Intrerupta si Consumatori intrerupti.\n" +
                    "Doriti sa le suprascrieti cu valorile din nomenclator ?\n" +
                    " - Putere intrerupta : " + pi + "\n" +
                    " - Consumatori  IT : " + it + "\n" +
                    " - Consumatori  MT : " + mt + "\n" +
                    " - Consumatori  JT : " + jt + "\n" +
                    " - Casnici : " + casnici + "\n" +
                    " - Mici : " + mici + "\n" +
                    " - Mari : " + mari
            );
        }
    }

    if (completeaza) {

        $("pi").value = pi;
        $("consumatoriIntr").value = totalConsumatori;
        $("utilizatoriIT").value = it;
        $("utilizatoriMT").value = mt;
        $("utilizatoriJT").value = jt;
        $("utilizatoriCasnici").value = casnici;
        $("utilizatoriMici").value = mici;
        $("utilizatoriMari").value = mari;
    }
}

function safeNumber(el) {
    var v = el.value;
    var n = parseFloat(v);
    if (isNaN(n)) {
        return 0;
    } else {
        return n;
    }
}

function getTipInstalatieSelected() {
    return tipInstalatieSelected;
}

function getTipInstalatieSelected2() {
    return tipInstalatieSelected2;
}

function getIdLfSelected() {
    return $('idInstalatie').value;
}

var lfDataProvider = new AjaxDataProvider(function () {
    if(getTipInstalatieSelected() == '19')
		return "<%=AppConstants.APP_NAME%>?action=suggestPapt&sucursalaId=<%=maifi.getSucursalaId()%>&<%=SugestConstants.SUGEST_Q_QUERY%>=";
	
	return "<%=AppConstants.APP_NAME%>?action=suggestMaifiInstalatie&tip="+ getTipInstalatieSelected() +"&<%=SugestConstants.SUGEST_Q_QUERY%>=";
	//return "<%=AppConstants.APP_NAME%>?action=suggestInstalatie&codCe=<%=centru.getCodSap()%>&tip=" + getTipInstalatieSelected() + "&<%=SugestConstants.SUGEST_Q_QUERY%>=";
});

var eqDataProvider = new AjaxDataProvider(function () {
    return "/emid-lpod/emid-lpod.default?action=suggestInstalatieOd&tip=" + getTipInstalatieSelected2() + "&idParent=" + getIdLfSelected() + "&<%=SugestConstants.SUGEST_Q_QUERY%>=";
});

setTimeout(function () {
    new InputSugest($("denInstalatie"), $("idInstalatie"), lfDataProvider, {
        isValidSearchInput: function () {
            return true;
        },

        beforeRequest: function () {
            window.status = "before request";
            $("tipInstalatie").value = "";
        },

        onSelect: function (item) {
            $("tipInstalatie").value = item.tipInstalatie;
            $("u").value = item.u;


            if ($("radioPAPT").checked) {
                updateEnergieSiNumarConsumatoriForPT(item.key);
            }
        }
    });

    new InputSugest($("denInstalatie2"), $("idInstalatie2"), eqDataProvider, {
        isValidSearchInput: function () {
            return true;
        },

        beforeRequest: function () {
            window.status = "before request";
            $("tipInstalatie2").value = "";
        },

        onSelect: function (item) {
            $("tipInstalatie2").value = item.tipInstalatie;
            $("u2").value = item.u;

            $("radioStatie").checked = true;
            $("tipInstalatie").value = item.tipInstalatieParent;
            $("idInstalatie").value = item.idInstalatieParent;
            $("denInstalatie").value = item.descInstalatieParent;
            $("u").value = item.uInstalatieParent;
        }
    });
}, 200);

var semnalizareDataProvider = new AjaxDataProvider(function () {
    return "/emid-lpod/emid-lpod.default?action=sugestSetValue&tip=<%=SetValue.SEMNALIZARI%>&<%=SugestConstants.SUGEST_Q_QUERY%>=";
});

setTimeout(function () {
    new InputSugest($("searchSemnalizare"), $(), semnalizareDataProvider, {
        beforeRequest: function () {

        },
        onSelect: function (item) {
            try {
                var value = $("semnalizari").value;
                if (value.length > 0) value += "\n";
                value += item.value;
                $("semnalizari").value = value;
                $("searchSemnalizare").value = '';
            } catch (e) {
                alert(e.message);
            }
        }
    });
}, 200);

var browseFeatures = "menubar=no,location=no,resizable=yes,scrollbars=yes,status=yes,height=650,left=20,top=10,width=1000";
function buildParamsForCheckPaPt() {
    var statieId = -1;
    try {
        if (tipInstalatieSelected == <%=TipInstalatie.STATIE%>) {
            statieId = document.zaforma.idInstalatie.value;
        }
    } catch (ex) {}

    var linieId = -1;
    try {
        if (tipInstalatieSelected == <%=TipInstalatie.LINIE%>) {
           linieId = document.zaforma.idInstalatie.value;
        }
    } catch (ex) {
    }

    var postId = -1;
    try {
        if (tipInstalatieSelected == <%=TipInstalatie.PA_PT%>) {
            postId = document.zaforma.idInstalatie.value;
        }
    } catch (ex) {}

    var derivatieId = -1;
    try {
        if (tipInstalatieSelected2 == <%=TipInstalatie.DERIVATIE%>) {
            derivatieId = document.zaforma.idInstalatie2.value;
        }
    } catch (ex) {}

    var durataOre = document.zaforma.durataOre.value;
    var durataMinute = document.zaforma.durataMinute.value;

    return "&statieId=" + statieId + "&linieId=" + linieId + "&postId=" + postId + "&derivatieId=" + derivatieId + "&durataOre=" + durataOre + "&durataMinute=" + durataMinute;
}

var _browseLFSearch = null;

function browseLFSearch() {
    if (_browseLFSearch != null) _browseLFSearch.close();

    var params = buildParamsForCheckPaPt();
    var url = "<%=AppConstants.APP_NAME%>?action=openBrowseMaifiInstalatii&maifiId=<%=maifi.getId()%>" + params;
    _browseLFSearch = window.open(url, '', browseFeatures);
}
</script>

<script type="text/javascript" src="<%=AppConstants.WEB_RESOURCE_PATH%>/scripts/maifiDetail.js"></script>