
<style type="text/css">
    #OrderTable thead tr th {
        color:#555;
        border-bottom: 1px solid rgba(0,0,0,0.1);
    }
    #OrderTable tbody tr td input{
        width:100%;
        margin:0;
        border: 1px solid rgba(0,0,0,0.02);
        background-color:#e5e5e5;
    }
    #OrderTable tbody tr td {
        border:0;
        padding:3px 1px;
        position:relative;
    }
    #OrderTable 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;
    }
    #OrderTable .Hint{
        position: absolute;
        font-size: 10px;
        font-weight: bold;
        height: 20px;
        line-height: 20px;
        bottom: 2px;
        right: 4px;
        color: rgb(153, 153, 153);   
    }
    #OrderTable .TotalTD{
        width: auto;
        display: inline-block;
        text-align: center;
        font-size: 20px;
        font-weight: bold;
    }
    #OrderTable .Disc{
        width:70px;
    }
    #OrderTable 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;
    }
    .datepicker thead tr .datepicker-switch {
        color: #4c0870   !important;
        font-size: 13px;
    }
    .datepicker table tr td span.active {
        background-color: #4c0870  !important;
    }
    .datepicker table tr td span:hover {
        background-color: #4c0870  !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;
    }

</style>

<script src="<?php echo THEME_PATH; ?>plugins/jquery-validation/js/jquery.validate.min.js"></script>
<div id="OrderDisabler" 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" id="OrderForm">
    <div class="container-fluid container-fixed-lg">
        <div class="panel panel-default">
            <div class="panel-body">
                <div id="OrderSuccess" 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('edit_order');?></h2>
                                <div>
                                    <div class="input-group  col-md-4 center-margin" style="float: left;">
                                        <span class="input-group-addon bg-primary">
                                            <i class="fa fa-search"></i>
                                        </span>
                                        <input type="text" id="search_Customer" class="form-control" placeholder="<?php print CommonLanguage::getMessage('customer_name');?>" >
                                    </div>
                                    <div class="clearfix"></div>
                                </div>
                                <br>
                                <div id="CustomerInfo">
                                    <input type="hidden" name="Customer_ID" required id="Customer_ID" value="<?php $Edit_Sales[0]['Customer_ID']?>" />
                                    <div id="CustomerInfoContent">
                                       <strong><span class='Name'><?php echo $Edit_Sales[0]['Customer_Name']?></span></strong>
                                       <div><strong><?php print CommonLanguage::getMessage('company');?>: </strong><span class='Company'><?php echo $Edit_Sales[0]['Customer_Company']?></span></div>
                                       <div><strong><?php print CommonLanguage::getMessage('Email');?>: </strong><span class='Address'><?php echo $Edit_Sales[0]['Customer_Email']?></span></div>
                                       <div><strong><?php print CommonLanguage::getMessage('Phone');?>: </strong><span class='Phone'></span><?php echo $Edit_Sales[0]['Customer_Phone']?></div>
                                       <div><strong><?php print CommonLanguage::getMessage('address');?>: </strong><span class='Discount'></span><?php echo $Edit_Sales[0]['Customer_Address']?></div>
                                       <div><strong><?php print CommonLanguage::getMessage('country');?>: </strong><?php echo $Edit_Sales[0]['Country_Name']?></div>
                                        
                                    </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('order');?> # <span id="sales_order_id"><?php if(empty($Sales_ID)){echo 1;}else{echo $Sales_ID;} ?></span></h4>
                                </div>
                                <div  class="form-group form-group-default input-group">
                                    <label><?php print CommonLanguage::getMessage('Date');?></label>
                                    <input id="Sales_Order_Date" name="Sales_Order_Date" class="form-control" value="<?php echo ($today); ?>" />
                                    <span class="input-group-addon bg-primary"><i class="fa fa-calendar"></i></span>
                                </div>
                                <div class="form-group">
                                    <div class="input-group m-b">

                                        <select name="Zone_ID" id="Zone_ID" class="full-width" <?php echo ('value="'.$Edit_Sales[0]['Zone_ID'].'"'); ?>   data-init-plugin="select2">
                                            
                                            <?php foreach ($all_zones as $zonelist):?>
                                            <option value="<?php echo $zonelist['Zone_ID']; ?>"><?php echo $zonelist['Zone_Name']; ?></option>
                                            <?php endforeach; ?>
                                        </select>
                                        <span class="input-group-btn">
                                            <button type="button" class="btn" style="width:0 ;background-color:#4c0870 " ><i class="fa fa-compass"style="color:#fff;margin-left:-7px"></i> </button> </span> 

                                    </div>
                                </div>
								 <div><strong><?php print CommonLanguage::getMessage('submitted_by');?>: </strong><?php echo $Edit_Sales[0]['Employee_Name']?></div>

                                <br>
                            </div>
                        </div>
                    </div>
                    <div>
                        <div class="clearfix"></div>
                    </div>
                    <div class="table-responsive">
                        <table class="table m-t-50" id='OrderTable'>
                            <thead>
                                <tr>

                                    <th class="text-center"><?php print CommonLanguage::getMessage('Code');?></th>
                                    <th class="text-center"><?php print CommonLanguage::getMessage('product_name');?></th>
                                    <th class="text-center"><?php print CommonLanguage::getMessage('Quantity');?></th>

                                </tr>
                            </thead>
                            <tbody>
                                <?php
                                for($x=0;$x<count($Edit_Sales);$x++){
                                
                                        $CurItem = $Edit_Sales[$x];
                                
                                ?>
                                <tr data-id="<?php echo $CurItem['Product_ID']?>" data-item-id="<?php echo $CurItem['Item_ID']?>">
                                    <td><input type="text" class="form-control AutoComplete CODE" value="<?php echo $CurItem['Product_Code']?>"></td>
                                    <td><input type="text" class="form-control AutoComplete ProductName" value="<?php echo $CurItem['Product_Name']?>"></td>
                                    <td><span class="Hint"></span><input type="text" class="form-control Quantity isnumber" value="<?php echo $CurItem['Quantity']?>"></td>

                                </tr>
                                <?php } ?>
                            </tbody>
                        </table>
                    </div>
                    <br>



                    <div class="container-sm-height" >
                        <button class=" btn  btn-cons m-b-10 pull-right" id="OrderSubmitButton" style="color:#fff;background-color:#4c0870 ;padding-top: 10px;top: 20px;min-width:253px;" type="button"><i class="pg-form"></i> <span class="bold">Submit</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 Required_Fields = <?php echo json_encode(CommonLanguage::getMessage('Required_Fields'));?>,
        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'));?>,
        Submitted_Successfully = <?php echo json_encode(CommonLanguage::getMessage('Submitted_Successfully'));?>;
    $(function(){


        $("body").addClass("NoSearch")
        $("body .search-link[data-toggle='search']").html("<i class='pg-search'></i>Click here to <span class='bold'>search</span>")
        $("#search_Customer").autocomplete({
            source: 'xhr/ajaxCustomer',
            minLength: 2,
            select: function(event, ui){
                var Content = "";
                Content += "<strong><span class='Name'>"+ui.item.Customer_Name+"</span></strong>";
                Content += "<div><strong>"+CompanyLang+": </strong><span class='Company'>"+ui.item.Customer_Company+"</span></div>";
                Content += "<div><strong>"+EmailLang+": </strong><span class='Address'>"+ui.item.Customer_Email+"</span></div>";
                Content += "<div><strong>"+PhoneLang+": </strong><span class='Phone'>"+ui.item.Customer_Phone+"</span></div>";
                Content += "<div><strong>"+AddressLang+": </strong><span class='Discount'>"+ui.item.Customer_Address+"</span></div>";
                Content += "<div><strong>"+CountryLang+": </strong>"+ui.item.Country_Name+"</div>";
                Content += "<div><strong>"+FinancialNbLang+": </strong>"+ui.item.Account_Code+"</div>";
                $("#CustomerInfoContent").html(Content)
                $("#Customer_ID-error").remove()
                $("#Customer_ID").removeClass("error").val(ui.item.Customer_ID);
            }
        })     
            .autocomplete("instance")._renderItem = function(ul,item){
            return $("<li>").html("<table cellspacing='0' cellpadding='0'><tr><td class='Column1'><i class='fa fa-file-o'></i></td><td><strong>"+item.Customer_Name + "</strong></td></tr></table>").appendTo(ul)
        }
        $("#search_Customer").autocomplete("instance")._resizeMenu = function( ul, items ) {
            this.menu.element.outerWidth($("#search_Customer").width() + parseFloat($("#search_Customer").css("padding-left")) + parseFloat($("#search_Customer").css("padding-right")) + 2);
        }

        EnableAutoComplete($("#OrderTable .AutoComplete.CODE"));
        EnableAutoComplete($("#OrderTable .AutoComplete.ProductName"));
        $("#Sales_Order_Date").datepicker({autoclose:true}).on("changeDate",function(e){
            $(this).keyup();
        })
        $("#OrderTable").delegate(".Quantity","blur keyup",function(e){
            var me = $(this),TR = me.parents("tr");

            if(e.which == 13){
                if(me.hasClass("Quantity")){
                    TR.find(".UnitPrice").focus()
                }else if(me.hasClass("UnitPrice")){
                    TR.find(".Disc").focus()
                }else{
                    TR.next().find(".CODE").focus()
                }
            }
            if(TR.index() < $("#OrderTable tbody").children().length-1){
                if($.trim(me.val()).match(/^\s*?([\d]+(\.\d+)?|\.\d{1,2})\s*$/) == null){
                    me.addClass("wrong")
                }else{
                    me.removeClass("wrong")
                }
            }
        });

        $("#OrderTable tbody").delegate("> tr input","keydown",function(e){
            var me = $(this)
            if(e.which == 8){
                if(me.val() == "" && !me.hasClass("CODE")){
                    me.parents("td").prev().find("input").focus()
                }else if(me.val() == "" && me.hasClass("CODE")){
                    if(me.parents("tr").prev()){
                        me.parents("tr").prev().find(".Disc").focus()
                    }
                }
            }
        })
        $("#OrderTable 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() <= $("#OrderTable tbody tr").length-2){
                            me.parents("tr").prev().find(".Disc").focus()
                            $(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("")
                Parent.append(ClonedRow);
                EnableAutoComplete($(".AutoComplete.CODE",ClonedRow).removeClass("AutoAdded"));
                EnableAutoComplete($(".AutoComplete.ProductName",ClonedRow).removeClass("AutoAdded"));
                $(".Hint,.Total",ClonedRow).html("")
                $("input",ClonedRow).removeClass("wrong")
                $(".select2-container",ClonedRow).empty().remove()
                $(".Material_Category_ID",ClonedRow).show().select2()
                //ClonedSelect.find('select.Material_Category_ID option:selected').removeAttr('selected');
                //ClonedSelect.find('select.Material_Category_ID option:first').attr('selected','selected');
                //ClonedSelect.find('select.Material_Category_ID').trigger('change');
                /* ClonedRow HERE | Reset The select tag here hahah */

            }
        })



        $("#OrderSubmitButton").on("click",ApplyPostMethod);
        //UpdateSubmitButtonStatus()
    })

    function EnableAutoComplete(who){
        if(!who.hasClass("AutoAdded")){
            who.autocomplete({
                source: function(request, response){
                    var SEL = $("select.Material_Category_ID", this.element.parents("tr")).val();
                    $.getJSON('xhr/ajaxVendor?cmd=' + (who.hasClass("CODE") ? "1" : "2") + "&type=" + SEL, request, function( s, status, xhr ){
                        response( s );
                    });
                },
                minLength: 2,
                select: function(event, ui){
                    var TR = $(this).parents("tr");
                    TR.attr("data-id",ui.item.Product_ID)
                    TR.find("input.CODE").val(ui.item.Product_Code )            
                    TR.find("input.ProductName").val(ui.item.Product_Name )


                    TR.find("input.Quantity").focus().prev().text((ui.item.Product_Quantity ) + " in stock")
                    return false;
                }
            }).autocomplete("instance")._resizeMenu = function( ul, items ) {
                this.menu.element.outerWidth((who.width()*(this.element.hasClass("CODE") ? 1 : 2.3)) + parseFloat(who.css("padding-left")) + parseFloat(who.css("padding-right")) + 2);
            }
            who.autocomplete("instance")._renderItem = function(ul,item){
                var MyType = this.element.hasClass("CODE") ? (item.Product_Code ? item.Product_Code : item.Material_Code) : (item.Product_Name ? item.Product_Name : item.Material_Name);
                return $("<li>").html("<table cellspacing='0' cellpadding='0'><tr><td class='OnlyText'>"+MyType+"</td></tr></table>").appendTo(ul)
            }
            who.addClass("AutoAdded")
        }
        $(document).keydown(function(e){
            if(e.which == 8 && e.target.tagName.toLowerCase() != "input"){
                e.preventDefault()
            }
        })
    }
    function ApplyPostMethod(){
        $("#OrderSuccess").attr("class","hidden");
        if($("#OrderForm").valid()){
            var IsValidated=true,
                Data = {

                   
                    Products:[]

                };



            Data.Sales_Order_ID =      $("#sales_order_id").text();
            Data.Customer_ID =      $("#Customer_ID").val();
            Data.Sales_Order_Date =  $("#Sales_Order_Date").val();
            Data.Zone_ID =  $("#Zone_ID").val();

            Data.Products=[];



            $("#OrderTable tbody tr").each(function(e){
                var me = $(this);
            if(e < $(this).parent().children().length-1){



                    Data.Products.push({

                        Item_ID:me.attr("data-item-id"),
                        Product_ID:me.attr("data-id"),
//                        Product_Code:me.find(".CODE").val(),
//                        Product_Name:me.find(".ProductName").val(),
                        Product_Quantity:me.find(".Quantity").val()

                    });



                    me.find(".CODE,.ProductName,.Quantity").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")
                        }
                    })
           }
            })
            if(!IsValidated)return;
            $("#OrderDisabler").show();
            $.ajax({
                url:"InventoryAjax/EditOrderRequest",
                method:"POST",
                data:Data,
                complete:function(v1,v2){
                    if(v2 == "success"){
                        $("#OrderSuccess").attr("class","alert alert-success").html(Submitted_Successfully)
                    }else{
                        $("#OrderSuccess").attr("class","alert alert-danger").html(Failed_Submit)
                    }
                    $(document.body).animate({scrollTop:0},800)
                    $("#OrderDisabler").hide();
                }
            })
        }else{
            $(document.body).animate({scrollTop:0},800)
        }
    }


</script>