
<style type="text/css">
    #InventoryServicesTable thead tr th {
        color:#555;
        border-bottom: 1px solid rgba(0,0,0,0.1);
    }
    #InventoryServicesTable tbody tr td input{
        width:100%;
        margin:0;
        border: 1px solid rgba(0,0,0,0.02);
        background-color:#e5e5e5;
    }
    #InventoryServicesTable tbody tr td {
        border:0;
        padding:3px 1px;
        position:relative;
    }
    #InventoryServicesTable tbody tr:first-child td{
        padding-top:10px;
    }
    #InvoiceDiscountInput{
        display: inline-block;
        width: 40px;
        padding: 3px;
        line-height: 20px;
        background: rgb(250, 250, 250);
        min-height: 12px;
        text-align: center;
        height: 25px;
        font-size: 12px;
        top: -2px;
        position: relative;
        margin: 0 3px;
    }
    #InvoiceVAT{
        display: inline-block;
        width: 92px;
        padding: 3px;
        line-height: 20px;
        background: rgb(250, 250, 250);
        min-height: 12px;
        text-align: center;
        height: 25px;
        font-size: 12px;
        top: -2px;
        position: relative;
        margin: 0 3px;
        margin-left: 23px;
    }
    #InventoryServicesTable .Hint{
        position: absolute;
        font-size: 10px;
        font-weight: bold;
        height: 20px;
        line-height: 20px;
        bottom: 2px;
        right: 4px;
        color: rgb(153, 153, 153);
    }
    #InventoryServicesTable .TotalTD{
        width: auto;
        display: inline-block;
        text-align: center;
        font-size: 20px;
        font-weight: bold;
    }
    #InventoryServicesTable .Disc{
        width:70px;
    }
    #InventoryServicesTable input.wrong{
        border: 1px solid rgba(255, 0, 0, 0.2);
        background: rgba(255, 0, 0, 0.05);
        /*        width:100%;*/
    }
    .DropDownForForms > .dropdown-menu{
        width:100%;
        height:200px;
        max-height:200px;
        overflow-y:scroll;
    }
    .DropDownForForms > .dropdown-menu{
        height:auto;
        cursor: pointer;
        overflow-y:auto;
    }
    .DropDownForForms > button{
        position:relative;
        z-index:999;
    }
    .DropDownForForms > button > input{
        position: absolute;
        left:5;
        top: 0;
        width:90%;
        cursor: pointer;
        -webkit-user-select:none;
        -moz-user-select:none;
        user-select:none;
        padding: 0;
        border: 0;
        background: transparent;
    }
    .Disabled{
        cursor:default;
        opacity:0.5;
    }
    #AdvanceValue{
        width: 102px;
        display: inline-block;
    }
    .datepicker thead tr .dow {
        color:#4c0870!important;
    }
    .datepicker table tr td.day:hover {
        background: #4c0870!important;
        color:#fff;
    }
    .datepicker table tr td.active {
        background-color: #4c0870!important;
color:#ed9421 !important;    }
    .datepicker thead tr .datepicker-switch {
        color: #4c0870 !important;
        font-size: 13px;
    }
    .datepicker table tr td span.active {
        background-color: #4c0870!important;
color:#ed9421 !important;    }
    .datepicker table tr td span:hover {
        background-color: #4c0870!important;
color:#ed9421 !important;        color:#fff;
    }
    datepicker thead tr .next:before, .datepicker thead tr .prev:before {
        color: #4c0870!important;
        font-family: 'FontAwesome';
        font-size: 10px;
    }
    .datepicker thead tr .next:before, .datepicker thead tr .prev:before {
        color: #4c0870!important;
        font-family: 'FontAwesome';
        font-size: 10px;
    }
    .select2-container > .select2-choice{
        background-color: #e5e5e5;
        width: 150px;
    }
    #InvoicePaymentSetup .nav.nav-tabs a {
        padding: 7px 14px;
        font-size: 11px;
    }
    .InputSpinner{
        width: 60px;
    }
    .InputSpinner > .form-control{
        border-color: rgb(221, 221, 221);
        height:36px;
        margin:0;
        padding:0;
        text-align: center;
        /*
        -webkit-border-radius: 3px 0px 0px 3px !important;
        -moz-border-radius: 3px 0px 0px 3px !important;
        border-radius: 3px 0px 0px 3px !important;
        */
    }
    .InputSpinner > .input-group-btn-vertical {
        position: relative;
        white-space: nowrap;
        width: 25px;
        vertical-align: middle;
        display: table-cell;
    }
    .InputSpinner > .input-group-btn-vertical > .btn {
        height:19px;
        display: block;
        float: none;
        width: 100%;
        max-width: 100%;
        padding: 8px;
        margin-left: -1px;
        position: relative;
        border-radius: 0;
    }
    .InputSpinner > .input-group-btn-vertical > .btn:first-child {
        border-top-right-radius: 4px;
    }
    .InputSpinner > .input-group-btn-vertical > .btn:last-child {
        margin-top: -2px;
        border-bottom-right-radius: 4px;
    }
    .InputSpinner > .input-group-btn-vertical i{
        position: absolute;
        top: 50%;
        left: 6px;
        margin-top:-9px;
        font-size: 18px;
    }
    .InputSpinner .input-group-btn-vertical .btn.btn-default{
        font-size: 10px;
        padding: 6px 10px;
    }
    #InvoicePaymentSetup .table tbody > tr:last-child > td{
        border:0;
    }
    .hideme{
        display:none;
    }
    .select2-container > .select2-choice {
        width: 100%;
    }
    .supInv{
        display:inline-flex;
    }
    .Account_Code{
        margin-left:10px;
    }
</style>
<script>
    function AddCommas(val) {
        val = parseFloat(val.toString()).toString();
        while (/(\d+)(\d{3})/.test(val.toString())) {
            val = val.toString().replace(/(\d+)(\d{3})/, '$1' + ',' + '$2');
        }
        return val.replace(/\.0$|\.00$/, "") || "0";
    }
    function FixNumber(val) {
        return AddCommas(public_round_number(parseFloat(val + "")));
    }
</script>
<script src="<?php echo THEME_PATH; ?>plugins/jquery-validation/js/jquery.validate.min.js"></script>
<div id="ServicesDisabler" style="position:absolute;left:0;right:0;top:0px;height:100%;background:rgba(255,255,255,0.9);z-index:2099;display:none"><img class="image-responsive-height demo-mw-50" src="img/demo/progress.svg" alt="Progress" style="position: absolute;left: 50%;top: 50%;margin: -25px 0 0 -25px;" /></div>
<form method="POST" action="" onsubmit="return false" >
    <div class="container-fluid container-fixed-lg">
        <div class="panel panel-default">
            <div class="panel-body">
                <div id="ServicesSuccess" class="hidden"></div>
                <div class="invoice padding-50 sm-padding-10">
                    <div class="container-sm-height">
                        <div class="row-sm-height">
                            <div class="col-md-9 col-sm-height sm-no-padding">
                                <h2 class="font-montserrat all-caps hint-text"><?php print CommonLanguage::getMessage('service_invoice'); ?></h2>
<!--                                  <div class='row'>
                                    <div class="col-md-4"><label><?php print CommonLanguage::getMessage('choose_customer'); ?></label><span class="fa fa-plus-circle m-l-5 openFrame" data-src="Inventory/CustomerList?is_pop=1" style="color:#8a7dbe;cursor:pointer"></span></div>
                                </div>-->
                                <div>
                                    <div class="input-group  col-md-4 center-margin pull-left">
                                        <label><?php print CommonLanguage::getMessage('choose_customer'); ?></label><span class="fa fa-plus-circle m-l-5 openFrame" data-src="Inventory/CustomerList?is_pop=1" style="color:#8a7dbe;cursor:pointer"></span>
                                        <input class="search_customer full-width" id="search_customer" name="search_customer" type="hidden"  />

                                    </div>
                                    <div class="clearfix"></div>
                                </div>
                                <br>
                                <div id="SupplierInfo">
                                    <input type="hidden" name="Customer_ID" required id="Customer_ID" />
                                    <div id="CustomerInfoContent">
                                    </div>
                                    <div id="SupplierAccInfo">
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-4 col-sm-height col-bottom sm-no-padding sm-p-b-20" style="vertical-align: top;">
                                <div class="sm-m-t-20">
                                    <h4> <?php print CommonLanguage::getMessage('service_invoice'); ?> #
                                        <?php
                                        if (empty($InvoiceNumber)) {
                                            echo 1;
                                        } else {
                                            echo $InvoiceNumber + 1;
                                        }
                                        ?></h4>
                                </div>
                                <div  class="form-group form-group-default input-group">
                                    <label><?php print CommonLanguage::getMessage('Date'); ?></label>
                                    <input id="Invoice_Date" name="Invoicee_Date" class="form-control" value="<?php echo ($today); ?>" />
                                    <span class="input-group-addon primary"><i class="fa fa-calendar"></i></span>
                                </div>
                                <div  class="form-group form-group-default input-group  ">
                                    <label><?php print CommonLanguage::getMessage('due_date'); ?></label>
                                    <input id="Invoice_Due_Date" name="Invoice_Due_Date" class="form-control" required>
                                    <span class="input-group-addon primary"><i class="fa fa-calendar-o"></i></span>
                                </div>
                                <div Default-Currency="<?php echo $DefaultCurrencyID; ?>" class="input-group-btn DropDownForForms Closable" id="CurrencyDropDown">
                                    <button type="button" class="btn btn-primary btn-block dropdown-toggle" data-toggle="dropdown" aria-expanded="false">
                                        <span><strong><?php print CommonLanguage::getMessage('Select_Currency'); ?></strong></span>
                                        <input type="hidden" value="<?php echo $DefaultCurrencyID; ?>" class="form-control ignore" onkeyup="return false" onkeydown="return false" required/>
                                    </button>
                                    <ul class="dropdown-menu">
<?php echo($currencyList); ?>
                                        <li class="divider"></li>
                                        <li><a class="LoadMore"><?php print CommonLanguage::getMessage('More'); ?>..</a></li>
                                    </ul>
                                </div>
                                <br>
                            </div>
                        </div>
                    </div>
                    <div>
                        <div class="clearfix"></div>
                    </div>
                    <div class="table-responsive">
                        <table class="table m-t-50 " id='InventoryServicesTable'>
                            <thead>
                                <tr>
                                    <th class="text-center" style="width:30%"><?php print CommonLanguage::getMessage('Description'); ?></th>
                                    <th class="text-center"style="width:15%"><?php print CommonLanguage::getMessage('account'); ?><span class="fa fa-plus-circle m-l-5 openFrame" data-src="ACC/viewlibrary/1?is_pop=1" style="color:#8a7dbe;cursor:pointer"></span></th>
                                    <th class="text-center" style="width:10%"><?php print CommonLanguage::getMessage('amount'); ?></th>
                                </tr>
                            </thead>
                            <tbody>
                                <tr>
                                    <td><input type="text" class="form-control ِtext-center Description" ></td>
                                    <td>
                                    <input class=" full-width" id="Account_Code" name="Account_Code" type="hidden"  />

<!--                                        <select  name="Account_Code" id="Account_Code"  class="full-width Account_Code " data-init-plugin="select2">
                                            <?php foreach ($salesAcc as $sal): ?>
                                                <option value="<?php echo $sal['Account_Code']; ?>"><?php echo $sal['Account_Name'] . ' - ' . $sal['Account_Code']; ?></option>
<?php endforeach; ?>
                                        </select>	-->
                                    </td>
                                    <td class="TotalTD"><input type="text" class="form-control ِAmount isnumber"></td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                    <br>
                    <div class="container-sm-height" >
                        <div class="row row-sm-height b-a b-grey" style="border:none">
                            <div class="col-sm-3  text-right bg-menu  padding-15 pull-right" style="text-align:left !important;">
                                <div style="text-align: left;display: inline-block;">
                                    <h5 class="font-montserrat all-caps small no-margin hint-text text-white bold"><?php print CommonLanguage::getMessage('total'); ?></h5>
                                    <h1 class="no-margin text-white Total"><span class="CurrencyIndicator"><?php echo $CurrSymbole; ?></span>&nbsp;<span id="ServicesInvoiceTotalDetails">0</span></h1>
                                </div>
                            </div>

                        </div>
                    </div>
                    <div class="container-sm-height" >
                        <button class=" btn btn-primary btn-cons m-b-10 pull-right" id="InvoiceSubmitButton" style="padding-top: 10px;top: 20px;min-width:253px;" type="button"><i class="pg-form"></i> <span class="bold"><?php echo CommonLanguage::getMessage('Save'); ?></span></button>
                    </div>
                    <hr>
                    <div>
                        <span class="m-l-20 text-black sm-pull-right"><?php echo $org_details[0]['Organization_Legal_Name']; ?></span>
                        <span class="m-l-20 text-black sm-pull-right"><?php echo $org_details[0]['Organization_Province']; ?> <?php echo $org_details[0]['Organization_Country']; ?> - <?php echo $org_details[0]['Organization_City']; ?></span>
                        <span class="m-l-20 text-black sm-pull-right">CR: <?php echo $org_details[0]['Organization_Commercial_Registry']; ?></span>
                        <span class="m-l-20 text-black sm-pull-right"><?php print CommonLanguage::getMessage('Phone'); ?>: <?php echo $org_details[0]['Organization_Phone']; ?></span>
                        <span class="m-l-40 text-black sm-pull-right"><?php print CommonLanguage::getMessage('Email'); ?>: <?php echo $org_details[0]['Organization_Email']; ?></span>
                    </div>
                </div>
            </div>
        </div>
    </div>
</form>
<script>
    var CompanyLang = <?php echo json_encode(CommonLanguage::getMessage('company')); ?>,
            EmailLang = <?php echo json_encode(CommonLanguage::getMessage('Email')); ?>,
            PhoneLang = <?php echo json_encode(CommonLanguage::getMessage('Phone')); ?>,
            AddressLang = <?php echo json_encode(CommonLanguage::getMessage('address')); ?>,
            CountryLang = <?php echo json_encode(CommonLanguage::getMessage('country')); ?>,
            FinancialNbLang = <?php echo json_encode(CommonLanguage::getMessage('financial_nb')); ?>,
            Failed_Submit = <?php echo json_encode(CommonLanguage::getMessage('Failed_Submit')); ?>,
            is_actual = <?php echo json_encode($IsActual); ?>,
            Submitted_Successfully = <?php echo json_encode(CommonLanguage::getMessage('Submitted_Successfully')); ?>;
    var TRvalue = 0;
    $(function () {
        build_select2($("#Account_Code"),( "xhr/accIDSearch?type=sales"))
                build_select2($(".search_customer"),"xhr/customerSearch")

        UpdateTotal()
        $("#search_customer").on("change", function () {
            var Data = {
                id: $(this).val()
            }
            $.ajax({
                url: "InventoryAjax/addServiceAjax",
                data: Data,
                dataType: 'json',
                complete: function (v1, v2) {
                    if (v2 == "success") {
                        var Data = (v1.responseJSON);
//                        console.log(Data)
                        $("#CustomerInfoContent").empty();
                        var Content = "";
                        Content += "<strong><span class='Name'>" + Data[0]['Customer_Name'] + "</span></strong>";
                        Content += "<div><strong>" + CompanyLang + ": </strong><span class='Company'>" + Data[0]['Customer_Company'] + "</span></div>";
                        Content += "<div><strong>" + EmailLang + ": </strong><span class='Email'>" + Data[0]['Customer_Email'] + "</span></div>";
                        Content += "<div><strong>" + PhoneLang + ": </strong><span class='Phone'>" + Data[0]['Customer_Phone'] + "</span></div>";
                        Content += "<div><strong>" + AddressLang + ": </strong><span class='Address'>" + Data[0]['Customer_Address'] + "</span></div>";
                        Content += "<div><strong>" + CountryLang + ": </strong>" + Data[0]['Country_Name'] + "</div>";
                        Content += "<div><strong>" + FinancialNbLang + ": </strong>" + Data[0]['Account_Code'] + "</div>";
                        Content += "<div id='Class_ID' style='display:none;'>" + Data[0]['Class_ID'] + "</div>";
                        $("#CustomerInfoContent").append(Content)
                        $("#Customer_ID-error").remove()
                        $("#Customer_ID").removeClass("error").val(Data[0]['Customer_ID']);
                    }
                }
            })
        })
        $("#InventoryServicesTable tbody").delegate("> tr input", "keyup", function (e) {
            var me = $(this), Parent = me.parents("tbody"), IsLastOneEmpty = true;
            $("tr", Parent).each(function (e) {
                if ($("tr", Parent).length > 1) {
                    var IsEmpty = true;
                    $(this).find("input").each(function () {
                        if ($(this).val() != "")
                            IsEmpty = false;
                    })
                    if (IsEmpty == true) {
                        if ($(this).index() <= $("#InventoryServicesTable tbody tr").length - 2) {
                            $(this).remove();
                        }
                    }
                }
            })
            $("tr:last-child input", Parent).each(function (e) {
                if ($(this).val() != "")
                    IsLastOneEmpty = false;
            })
            if (IsLastOneEmpty == false) {
                var ClonedRow = $("tr:first-child", Parent).clone()
//                ClonedRow.find("input").val("")
//                ClonedRow.find("input.AccountCode").removeAttr("value")
                ClonedRow.find("input").val("")
                Parent.append(ClonedRow);
//                alert()
                                $(".select2-container", ClonedRow).empty().remove()

                build_select2(ClonedRow.find("input[name=Account_Code]"),( "xhr/accSearch?type=sales"))
                $(".select2-container", ClonedRow).show()
                UpdateTotal()
            }
        })
        $("#CurrencyDropDown li").click(function () {
            $(".CurrencyIndicator").html($(this).attr("MySymbol"))
        })
        $("#Invoice_Date,#Invoice_Due_Date").datepicker({autoclose: true}).on("changeDate", function (e) {
            $(this).keyup();
        })
    })
    $("#InvoiceSubmitButton").on("click", function () {
        $("#ServicesSuccess").attr("class", "hidden");
        var Data = {
            Services: [],
            is_actual : is_actual,
            Customer_ID: $("#Customer_ID").val(),
            Invoice_Date: $("#Invoice_Date").val(),
            Invoice_Due_Date: $("#Invoice_Due_Date").val(),
            Currency_ID: $("#CurrencyDropDown input").val(),
            Invoice_Net_Total: $('#ServicesInvoiceTotalDetails').attr('total')
        }
        $("#InventoryServicesTable tbody tr").each(function (e) {
            var me = $(this);
            if (e < $(this).parent().children().length - 1) {
                Data.Services.push({
                    Service_Description: me.find(".Description").val(),
                    Account_Code: me.find("#Account_Code").val(),
                    Service_Amount: me.find(".isnumber").val()
                });
            }
            me.find(".Amount").each(function () {
                if ($.trim($(this).val()) == "" || ($(this).hasClass("isnumber") && $.trim($(this).val()).match(/^\s*?([\d]+(\.\d+)?|\.\d{1,2})\s*$/) == null)) {
                    $(this).addClass("wrong")
                    IsValidated = false;
                } else {
                    $(this).removeClass("wrong")
                }
            })
        })
        $("#ServicesDisabler").show();
        $.ajax({
            url: "InventoryAjax/addServiceAjax",
            method: "POST",
            dataType:'json',
            data: Data,
            complete: function (v1, v2) {
                if (v2 == "success") {
                    if(v1.responseJSON =="OK"){
                       $("#ServicesSuccess").attr("class", "alert alert-success").html(Submitted_Successfully)
                    $("#InvoiceSubmitButton").addClass("disabled", "disabled") 
                    }else{
                        $("#ServicesSuccess").attr("class", "alert alert-danger").html(v1.responseJSON[0])

                    }
                    
                } else {
                    $("#ServicesSuccess").attr("class", "alert alert-danger").html(Failed_Submit)
                }
                $(document.body).animate({scrollTop: 0}, 800)
                $("#ServicesDisabler").hide();
            }
        })
    })



    function UpdateTotal() {



        $("#InventoryServicesTable tbody").delegate("> tr input.isnumber", "keyup", function (e) {

            var totalBalance = 0;
            $("#InventoryServicesTable input.isnumber").each(function () {
                var amount = $(this).val(),
                        CurrentCurrency = $("#CurrencyDropDown input").val();

                CurVal = parseFloat(amount) || 0;


                totalBalance += parseFloat(CurVal);



            })
            $('#ServicesInvoiceTotalDetails').attr('total', public_round_number(totalBalance))
            $('#ServicesInvoiceTotalDetails').text(AddCommas(public_round_number(totalBalance)))
        })
    }

</script>
