Thursday, 16 April 2015

Draggable Div and Droppable Table Columns

<%@ control language="C#" autoeventwireup="true" codebehind="ProjectOperationsControl.ascx.cs" inherits="Controls_ProjectOperationsControl" %>

<script src="../App_Themes/SolarTurbines/json2.js"></script>
<script src="../App_Themes/SolarTurbines/jquery.json-2.4.min.js"></script>

<script type="text/javascript">

    var swsOperations;
    var operationsToSend = "";
    var changeSequence = 0;
    var dropSqn = 0;
    var orderByGlobal = 2;


    $(window).load(function () {

        $('div.MembershipBar').hide();
        $('div.MembershipBarPlaceholder').hide();
        $('div#PageHeader').hide();
        $('div.Title').hide();
        $('div.OperationHeader').hide();
        $('div#PageFooterBar').hide();

        var w = window.innerWidth;
        var h = window.innerHeight;

        var lft = 840 + 'px'; //(w * 55) / 100;
        $('#swsdivcontainerparent').css('left', lft);

        window.resizeTo(w + 5, h);

    });


    $(document).ready(function () {
        BuildProject();

    });


    $(window).resize(function () {

        $('div.MembershipBar').hide();
        $('div.MembershipBarPlaceholder').hide();
        $('div#PageHeader').hide();
        $('div.Title').hide();
        $('div.OperationHeader').hide();
        $('div#PageFooterBar').hide();


    });


    function BuildProject() {

        if (typeof window.opener.projectId == 'undefined') {
            alert("The parent screen is closed or navigated to a different screen");
            window.close();
        }

        var dataPassed = new Object();
        dataPassed.projectId = window.opener.projectId;


        /*---------------Get Data [Start]----------------------*/
        //Web service call here to get data

        $.ajax({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            url: "../DAF/Project.asmx/GetProject",
            data: $.toJSON(dataPassed),
            dataType: "json",
            success:
                 function (msg) {
                     if (msg && msg.d) {
                         var project1 = "";
                         var obj = jQuery.parseJSON(msg.d);

                         $('#ProjectsTR').empty();

                         $.each(obj, function (i, val) {

                             project1 = $("<td>" + obj[i].Project + "</td>" + "<td>" + obj[i].Description + "</td>" + "<td>" + obj[i].Status + "</td>");

                             $('#ProjectsTR').append(project1);

                             project1 = "";

                         });

                         BuildOperations(2);

                     }
                     else {
                         alert("Error occurred while fetching data. Please contact Administrator");
                     }

                     //Build the list of SWS
                     BuildSWS();
                 },
            error:
                 function (XMLHttpRequest, textStatus, errorThrown) {
                     alert("An error occurred. Please contact administrator.");
                     window.location = '../Pages/Home.aspx';
                 }
        });

        /*---------------Get Data [End]----------------------*/
    }


    function BuildOperations(orderBy) {

        if (typeof window.opener.projectId == 'undefined') {
            alert("The parent screen is closed or navigated to a different screen");
            window.close();
        }

        var sortOrder = $('#' + orderBy + 'sortord').val();
        orderByGlobal = orderBy;

        var dataPassed = new Object();
        dataPassed.projectId = window.opener.projectId;
        dataPassed.orderBy = orderBy;
        dataPassed.sortOrder = sortOrder;
        dataPassed.swsOperations = operationsToSend;


        /*---------------Get Data [Start]----------------------*/
        //Web service call here to get data

        $.ajax({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            url: "../DAF/Project.asmx/GetAllOperations",
            data: $.toJSON(dataPassed),
            dataType: "json",
            success:
                 function (msg) {
                     if (msg && msg.d) {
                         BuildOperations2(msg.d);

                         var hiddenField = $('#' + orderBy + 'sortord'),
                         val = hiddenField.val();
                         hiddenField.val(val === "true" ? "false" : "true");
                     }
                     else {
                         alert("Error occurred while fetching data. Please contact Administrator");
                     }

                     //Build the list of SWS
                     BuildSWS();
                 },
            error:
                 function (XMLHttpRequest, textStatus, errorThrown) {
                     alert("An error occurred. Please contact administrator.");
                     window.location = '../Pages/Home.aspx';
                 }
        });

        /*---------------Get Data [End]----------------------*/
    }


    function BuildOperations2(operations) {
        var operation1 = "";
        var opSWS = "";


        var obj = jQuery.parseJSON(operations);
        swsOperations = obj;

        $('#MainStepsTR').empty();

        $.each(obj, function (i, val) {

            opSWS = "<div class='draggable ui-state-default' id='" + obj[i].SwsId + ":" + obj[i].WorkSequenceTitle + "'><p>" + obj[i].WorkSequence + "</p></div>";

            operation1 = $("<tr><td><input type='textbox' readonly='true' class='sqrtxt' maxlength='3' " + (obj[i].Disabled ? "disabled='true'" : " value = " + obj[i].Sequence) + " id='txtSqn" + obj[i].ItemId
                + "' ></input><input type='hidden' id='opid" + obj[i].ItemId + "' value='" + obj[i].OperationId
                + "'/><input type='hidden' id='prodordexist" + obj[i].ItemId + "' value='" + obj[i].ProdOrdExists + "'/></td><td><span class='operationtxt' id='txtOperation" + obj[i].ItemId + "'>" + obj[i].Operation
                + "</span></td><td><input type='textbox' " + (obj[i].Disabled ? "disabled='true' " : "") + " maxlength='40' class='operationnametxt' id='txtOperationName" + obj[i].ItemId
                + "' value='" + obj[i].OperationName.replace("~~", ":").replace("^~", "{").replace("~^", "}").replace("~*", ",").replace("&#39;", "`")
                + "' onblur=\"javascript:BuildJson(" + obj[i].ItemId + ", 'Changed');\"></input> <input type='hidden' id='swsid" + obj[i].ItemId + "' value='" + obj[i].SwsId + "'/>"
                + "</td><td><div class='droppableitem' id='op" + obj[i].ItemId + "'>" + (!obj[i].Disabled ? opSWS : "") + "</div></td></tr>");

            dropSqn = (obj[i].Sequence > 0 && obj[i].Sequence > dropSqn) ? obj[i].Sequence : dropSqn;

            $('#MainStepsTR').append(operation1);

            if (!obj[i].Disabled) {
                $('#op' + obj[i].ItemId).addClass("ui-state-highlight");
            }

            $(".droppableitem").droppable({
                activeClass: "ui-state-hover",
                hoverClass: "ui-state-active",
                drop: function (event, ui) {
                    try {
                        var draggableId = ui.draggable.attr("id");

                        var droppableId = $(this).attr("id");

                        var arr = draggableId.split(':');

                        var idNbr = droppableId.substr(2, droppableId.length - 1);

                        var sCount = $("#swscount" + arr[0]).text();

                        var sCountArr = sCount.split(':');


                        if (sCountArr[0] == 0 && sCountArr[1] != "SCAN_CARD_ONLY") {
                            alert("Cannot add this Standard Work Sequence as there are no steps associated with it.");

                            ui.draggable.draggable('option', 'revert', true);

                        }
                        else {

                            $(this).addClass("ui-state-highlight");

                            dropSqn += 1;

                            $('#txtSqn' + idNbr).attr('disabled', false);
                            ;
                            $('#txtSqn' + idNbr).val(dropSqn);
                            $('#txtOperationName' + idNbr).attr('disabled', false);
                            //$('#txtWorkTitle' + idNbr).text(arr[1]);
                            $('#swsid' + idNbr).val(arr[0]);

                            var draggable1 = ui.draggable.clone();
                            draggable1 = draggable1.clone();
                            draggable1.appendTo(this);


                            BuildJson(idNbr, 'Added');

                            $('#Text1').focus();
                        }


                    }
                    catch (exception) {
                        alert(exception);
                    }

                },
                accept: function (dropElem) {
                    //dropElem was the dropped element, return true or false to accept/refuse it
                    return (!$(this).hasClass("ui-state-highlight") && $(dropElem).hasClass("ui-state-default") && !$(dropElem).parent().hasClass("ui-state-highlight"));
                }
            });

            $(".droppableitem").sortable({ connectWith: ".draggable" });


            opSWS = "";
            operation1 = "";

        });

    }


    function BuildSWS() {

        /*---------------Get Data [Start]----------------------*/
        //Web service call here to get data
        var dataPassed = new Object();
        var swsHtml = "";
        var sws = "";
        var swscount = "";

        $.ajax({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            url: "../DAF/Project.asmx/GetAllSWS",
            //data: JSON.stringify(dataPassed),
            dataType: "json",
            success:
                 function (msg) {
                     if (msg && msg.d) {
                         var obj = jQuery.parseJSON(msg.d);
                         var count = 1;

                         $('#swsdiv').empty();
                         $('#swscount').empty();

                         $.each(obj, function (i, val) {

                             sws = sws + "<div class='draggable ui-state-default' id='" + obj[i].SwsId + ":" + obj[i].Title + "'><p class='swstitlep' title='"
                                 + obj[i].Title + "'>" + obj[i].StandarWorkSequence + "</p></div>";

                             swscount = swscount + "<div id='swscount" + obj[i].SwsId + "'>" + obj[i].SCount + ":" + obj[i].StandarWorkSequence + "</div>";

                             $('#swsdiv').append($(sws).draggable({
                                 helper: "clone",
                                 revert: "invalid",
                                 stack: "div",
                                 cursor: "move",
                                 cancel: null
                             }));


                             $('#swscount').append(swscount);

                             $("#swsdiv").droppable({
                                 drop: function (event, ui) {
                                     var dropped = ui.draggable;

                                     var parentDivId = $(dropped).parent().attr("id");
                                     var idNbr = parentDivId.substr(2, parentDivId.length - 1);

                                     if ($(dropped).parent().hasClass("ui-state-highlight")) {
                                         $(dropped).parent().removeClass("ui-state-highlight");
                                         $(dropped).detach().css({ top: 0, left: 0 });

                                         $('#txtSqn' + idNbr).attr('disabled', true);
                                         $('#txtSqn' + idNbr).val('');
                                         //$('#txtWorkTitle' + idNbr).text('');
                                         $('#txtOperationName' + idNbr).attr('disabled', true);

                                         BuildJson(idNbr, 'Deleted');
                                     }
                                     else {
                                         ui.draggable.draggable('option', 'revert', true);

                                     }

                                 },
                                 accept: ".draggable"
                             });

                             sws = "";
                             swscount = "";

                         });

                     }
                     else
                         alert("Error occurred while fetching data. Please contact Administrator");
                 },
            error:
                 function (XMLHttpRequest, textStatus, errorThrown) {
                     alert("An error occurred. Please contact administrator.");
                     window.location = '../Pages/Home.aspx';
                 }
        });

        /*---------------Get Data [End]----------------------*/
    }


    function SaveOperations() {
        var dataPassed = new Object();
        dataPassed.projectId = window.opener.projectId;
        dataPassed.swsOperations = operationsToSend;

        if (operationsToSend.length == 0) {
            alert("There are no changes made");
            return false;
        }
        else if (!ValidateSequence()) {
            alert("The sequence cannot be same");
            return false;
        } else if (!ValidateOperations()) {
            alert("The Operation Number and Operation Name should be unique");
            return false;

        }


        try {
            $.ajax({
                type: "POST",
                contentType: "application/json; charset=utf-8",
                url: "../DAF/Project.asmx/SaveOperations",
                data: $.toJSON(dataPassed),
                dataType: "json",
                success:
                     function (msg) {
                         //$('#2sortord').val('true');
                       
                         var sortOrdert = $('#' + orderByGlobal + 'sortord'),
                         val = sortOrdert.val();
                         sortOrdert.val(val === "true" ? "false" : "true");

                         BuildOperations(orderByGlobal);
                         operationsToSend = "";
                         alert("Changes have been saved successfully.");
                     },
                error:
                     function (XMLHttpRequest, textStatus, errorThrown) {
                         alert("An error occurred. Please contact administrator.");
                     }
            });
        } catch (exception) {
            alert(exception);
        }
    }


    function BuildJson(idNbr, operation) {

        var operationId = $('#opid' + idNbr).val();
        var swsId = $('#swsid' + idNbr).val();
        var workTitle = ''; //$('#txtWorkTitle' + idNbr).text();
        var operationNbr = $('#txtOperation' + idNbr).text();
        var operationName = $('#txtOperationName' + idNbr).val();
        var prodOrdExist = $('#prodordexist' + idNbr).val();
        var sCount = $("#swscount" + swsId).text();
        var sCountArr = sCount.split(':');

        var worksequence = sCountArr[1] != "undefined" ? sCountArr[1] : "";


        //if (workTitle.trim().length == 0 && operation == "Changed") {
        //    alert("Work Title cannot be empty");
        //    $('#txtWorkTitle' + idNbr).focus();
        //    return false;
        //}

        if (operationNbr.trim().length == 0 && operation == "Changed") {
            alert("Operation Number cannot be empty");
            $('#txtOperation' + idNbr).focus();
            return false;
        }


        if (operationName.trim().length == 0 && operation == "Changed") {
            alert("Operation Name cannot be empty");
            return false;
        }

        if (!ValidateOperations()) {
            alert("The Operation Number and Operation Name should be unique.");
            return false;
        }

        if (prodOrdExist > 0 && operation == "Deleted") {
            alert("You cannot perform this operation as there are Production Orders associated for this operation.")
            var sortOrdert = $('#' + orderByGlobal + 'sortord'),
            val = sortOrdert.val();
            sortOrdert.val(val === "true" ? "false" : "true");

            BuildOperations(orderByGlobal);
            return false;
        }




        workTitle = workTitle.replace(":", "~~");
        workTitle = workTitle.replace("{", "^~");
        workTitle = workTitle.replace("}", "~^");
        workTitle = workTitle.replace(",", "~*");

        operationNbr = operationNbr.replace(":", "~~");
        operationNbr = operationNbr.replace("{", "^~");
        operationNbr = operationNbr.replace("}", "~^");
        operationNbr = operationNbr.replace(",", "~*");

        operationName = operationName.replace(":", "~~");
        operationName = operationName.replace("{", "^~");
        operationName = operationName.replace("}", "~^");
        operationName = operationName.replace(",", "~*");


        worksequence = worksequence.replace(":", "~~");
        worksequence = worksequence.replace("{", "^~");
        worksequence = worksequence.replace("}", "~^");
        worksequence = worksequence.replace(",", "~*");
       

        var seqset = operation == "Deleted" ? -1 : $('#txtSqn' + idNbr).val();
        changeSequence += 1;

        var opObj = { "ItemId": changeSequence, "OperationId": operationId, "SwsId": swsId, "Sequence": seqset, "WorkSequenceTitle": workTitle, "ItemOperation": operation, "Operation": operationNbr, "OperationName": operationName, "WorkSequence": worksequence };

        operationsToSend = operationsToSend + JSON.stringify(opObj);
    }


    function ValidateSequence() {
        var seen = [];
        var validate = true;
        $('.sqrtxt').each(function () {
            if (!$(this).is(':disabled')) {
                var txt = $(this).val();

                for (var i = 0; i < seen.length; i++) {
                    if (seen[i] === txt) {
                        validate = false;
                        break;
                    }
                }

                seen.push(txt);
            }
        });

        return validate;
    }


    function ValidateOperations() {
        var seen = [];
        var validate = true;
        $('.operationtxt').each(function () {
            if (!$(this).is(':disabled')) {
                var txt = $(this).text().trim();
                var id = $(this).attr("id");
                var id2 = id.substr(12, id.length);

                var opname = $('#txtOperationName' + id2).val().trim();

                var culp = txt + opname;

                for (var i = 0; i < seen.length; i++) {
                    if (seen[i] === culp) {
                        validate = false;
                        break;
                    }
                }

                seen.push(culp);
            }
        });

        return validate;
    }


    function RefreshParent() {
        window.close();
        window.opener.refreshChildGrids();
    }


    function Search() {

        //if ($(obj).val().length) {
        var dataPassed = new Object();
        dataPassed.projectId = window.opener.projectId;
        dataPassed.opNbr = $("#opNbrs").val();
        dataPassed.opName = $("#opNameS").val();
        dataPassed.workSqn = $("#workSqns").val();
        dataPassed.swsOperations = operationsToSend;

        /*---------------Get Data [Start]----------------------*/
        //Web service call here to get data

        $.ajax({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            url: "../DAF/Project.asmx/SearchOperations",
            data: $.toJSON(dataPassed),
            dataType: "json",
            success:
                    function (msg) {
                        if (msg && msg.d) {
                            BuildOperations2(msg.d);
                        }
                        else {
                            alert("Error occurred while fetching data. Please contact Administrator");
                        }
                    },
            error:
                    function (XMLHttpRequest, textStatus, errorThrown) {
                        alert("An error occurred. Please contact administrator.");
                        window.location = '../Pages/Home.aspx';
                    }
        });

        /*---------------Get Data [End]----------------------*/
        //}
    }

 

</script>

<table style="width: 697px; margin-left: 5px">
    <tr>
        <td>
            <div class="OperationsDiv">
                <table class="OperationsTbl">
                    <tr class="Header">
                        <th>Project
                        </th>
                        <th>Description
                        </th>
                        <th>Status
                        </th>
                    </tr>
                    <tr id="ProjectsTR"></tr>
                </table>
            </div>
        </td>
    </tr>
</table>
<table>
    <tr>
        <td>
            <div id="operationsdiv" class="OperationsDiv">
                <div style="float: left;">
                    <table class="OperationsTbl">
                        <tr class="Header">
                            <th>
                                <p><a class="opHeaderLink" href="#" onclick="javascript:BuildOperations(1); return false;">Sequence</a></p>
                                <input type="text" class="searchTxtCls" id="Text1" onblur="javascript:Search(); return false;" style="visibility: hidden; width: 3px" />
                                <input type="hidden" id="1sortord" value="true" />
                            </th>
                            <th>
                                <p><a class="opHeaderLink" href="#" onclick="javascript:BuildOperations(2); return false;">Operation Nbr</a></p>
                                <input type="text" class="searchTxtCls" id="opNbrs" onblur="javascript:Search(); return false;" style="width: 50px;" tabindex="1" />
                                <input type="hidden" id="2sortord" value="true" />
                            </th>
                            <th>
                                <p><a class="opHeaderLink" href="#" onclick="javascript:BuildOperations(3);return false;">Operation Name</a></p>
                                <input type="text" class="searchTxtCls" id="opNameS" onblur="javascript:Search(); return false;" style="width: 160px;" tabindex="2"  />
                                <input type="hidden" id="3sortord" value="true" />
                            </th>
                           <%-- <th style="visibility:hidden">
                                <p><a class="opHeaderLink" href="#" onclick="javascript:BuildOperations(4);return false;">Work Title</a></p>
                                <input type="text" class="searchTxtCls" id="workTitles" onblur="javascript:Search(); return false;" style="width: 230px;" tabindex="3"  />
                                <input type="hidden" id="4sortord" value="true" />
                            </th>--%>
                            <th>
                                <p><a class="opHeaderLink" href="#" onclick="javascript:BuildOperations(5);return false;">Work Sequence</a></p>
                                <input type="text" class="searchTxtCls" id="workSqns" onblur="javascript:Search(); return false;" style="width: 130px;" tabindex="4"  />
                                <input type="hidden" id="5sortord" value="true" />
                            </th>
                        </tr>
                        <tbody id="MainStepsTR">
                        </tbody>
                    </table>
                </div>
            </div>
            <div id="swsdivcontainerparent">
                <div>
                    <button id="btnSave" onclick="javascript:SaveOperations();return false;" style="height: 35px; width: 95px; font-weight: bold;" tabindex="5" >Save</button>
                    <button id="btnReset" style="height: 35px; width: 95px; font-weight: bold;" tabindex="6" >Reset</button>
                    <button id="btnClose" onclick="javascript:RefreshParent();return false;" style="height: 35px; width: 95px; font-weight: bold;" tabindex="7"  >Close</button>
                </div>
                <div id="swsdivcontainer">
                    <div style="background-color: #ddd; font-weight: bold; font-family: tahoma; font-size: 8.5pt; padding: 5px;">Standard Work Sequence</div>
                    <div id="swsdiv">
                    </div>
                </div>
            </div>

            <div id="swscount" style="visibility: hidden"></div>
        </td>
    </tr>
</table>

No comments:

Post a Comment