<%@ Page Title="PCode Map" Language="C#" MasterPageFile="~/masterpages/eDashboard.master"
    AutoEventWireup="true" CodeBehind="PCode.aspx.cs" Inherits="WebSite.site.Administrative.ModelMap.PCode" %>

<%@ Register Src="~/Controls/PersistNav.ascx" TagName="PersistNav" TagPrefix="uc1" %>
<%@ Register Assembly="eSecuritel.HITS.UI.Components" Namespace="eSecuritel.HITS.UI.Components"
    TagPrefix="cc1" %>
<%@ Register Src="~/Controls/CustomSorter.ascx" TagName="CustomSorter" TagPrefix="uc1" %>
<%@ Register Assembly="eSecuritel.HITS.UI.Components" Namespace="eSecuritel.HITS.UI.Components"
    TagPrefix="cc1" %>
<asp:Content ID="Content1" ContentPlaceHolderID="eContent" runat="server">
    <asp:ScriptManagerProxy ID="ScriptManagerProxy1" runat="server">
        <Scripts>
            <asp:ScriptReference Path="~/script/jquery-1.8.3.min.js" />
            <%--<asp:ScriptReference Path="~/script/jquery-1.8.3.js" />
            <asp:ScriptReference Path="~/script/jquery-1.8.3-vsdoc.js" />--%>
        </Scripts>
    </asp:ScriptManagerProxy>

    <script type="text/javascript" language="javascript">

        PCode = function(tblPCode,
                        btnSave,
                        btnCancel,
                        btnClear,
                        txtPCode,
                        txtModelName,
                        txtModelAlias,
                        txtSku,
                        DdlPageSize,
                        lblLoading,
                        divLoading,
                        arrUsedPCodes) {

            this._TblPCode = tblPCode;
            this._BtnSave = btnSave;
            this._BtnCancel = btnCancel;
            this._BtnClear = btnClear;
            this._TxtPCode = txtPCode;
            this._TxtModelName = txtModelName;
            this._TxtModelAlias = txtModelAlias;
            this._TxtSku = txtSku;
            this._DdlPageSize = DdlPageSize;
            this._LblLoading = lblLoading;
            this._DivLoading = divLoading;
            this._UsedPCodes = arrUsedPCodes;

            this._DivLoadingTimer = null;
            this._UnusedOptionsString = null;
            this._YellowRows = new Array();

            /************** Delegates ***************/
            this._DivLoadingTimerDelegate = null;
            this._ClearButtonDelegate = null;
            this._CancelButtonDelegate = null;
            this._SaveButtonDelegate = null;
            /************** End Delegates ***********/
        }

        PCode.prototype = {
            /************* Getters and Setters **********************/
            get_TblPCode: function() {
                return this._TblPCode;
            },
            set_TblPCode: function(value) {
                this._TblPCode = value;
            },
            get_BtnSave: function() {
                return this._BtnSave;
            },
            set_BtnSave: function(value) {
                this._BtnSave = value;
            },
            get_BtnCancel: function() {
                return this._BtnCancel;
            },
            set_BtnCancel: function(value) {
                this._BtnCancel = value;
            },
            get_BtnClear: function() {
                return this._BtnClear;
            },
            set_BtnClear: function(value) {
                this._BtnClear = value;
            },
            get_TxtPCode: function() {
                return this._TxtPCode;
            },
            set_TxtPCode: function(value) {
                this._TxtPCode = value;
            },
            get_TxtModelName: function() {
                return this._TxtModelName;
            },
            set_TxtModelName: function(value) {
                this._TxtModelName = value;
            },
            get_TxtModelAlias: function() {
                return this._TxtModelAlias;
            },
            set_TxtModelAlias: function(value) {
                this._TxtModelAlias = value;
            },
            get_TxtSku: function() {
                return this._TxtSku;
            },
            set_TxtSku: function(value) {
                this._TxtSku = value;
            },
            get_DdlPageSize: function() {
                return this._DdlPageSize;
            },
            set_DdlPageSize: function(value) {
                this._DdlPageSize = value;
            },
            get_LblLoading: function() {
                return this._LblLoading;
            },
            set_LblLoading: function(value) {
                this._LblLoading = value;
            },
            get_DivLoading: function() {
                return this._DivLoading;
            },
            set_DivLoading: function(value) {
                this._DivLoading = value;
            },
            get_UsedPCodes: function() {
                return this._UsedPCodes;
            },
            set_UsedPCodes: function(value) {
                this._UsedPCodes = value;
            },
            /************* End Getters and Setters **********************/
            init: function() {
                this._DivLoading.hide();
                this._DivLoadingTimerDelegate = Function.createDelegate(this, this._LblLoadingTimerTick);
                this._ClearButtonDelegate = Function.createDelegate(this, this._ClearButtonEventHandler);
                this._CancelButtonDelegate = Function.createDelegate(this, this._CancelButtonClick);
                this._SaveButtonDelegate = Function.createDelegate(this, this._SaveButtonClick);

                this._DivLoadingTimer = window.setInterval(this._DivLoadingTimerDelegate, 500);
                this._BtnClear.bind('click', this._ClearButtonDelegate);
                this._BtnCancel.bind('click', this._CancelButtonDelegate);
                this._BtnSave.bind('click', this._SaveButtonDelegate);

                if (this._TblPCode.size() > 0) {
                    this._InitializeDropDowns(true);
                    $('.PCodeDropDown', this._TblPCode).bind('change', this._PCodeDropDownChange);
                }
            },
            dispose: function() {
                window.clearInterval(this._DivLoadingTimer);
                this._BtnClear.unbind('click', this._ClearButtonDelegate);
                this._BtnCancel.unbind('click', this._CancelButtonDelegate);
                this._BtnSave.unbind('click', this._SaveButtonDelegate);
                if (this._TblPCode.size() > 0) {
                    $('.PCodeDropDown', this._TblPCode).unbind('change', this._PCodeDropDownChange);
                }
            },
            _PCodeDropDownChange: function() {

                var dropDown = $(this);
                dropDown.context['PCodeObject']._ToggleDropDown(dropDown);
            },
            _ToggleDropDown: function(dropDown) {
                var row = dropDown.context['Row'];
                var hidNewPCode = dropDown.context['HidNewPCode'];
                var hidOriginalPCode = dropDown.context['HidOriginalPCode'];

                var origPCodeFromChange = hidNewPCode.val();
                var newPCodeFromChange = dropDown.val();
                var realThis = dropDown.context['PCodeObject'];
                var usedPCodes = realThis.get_UsedPCodes();


                var testIndex = jQuery.inArray(newPCodeFromChange, usedPCodes);
                if (testIndex >= 0) {
                    alert('This PCode has already been assigned to a different SKU.\nPlease select an unused SKU.');
                    dropDown.val(hidOriginalPCode.val());
                    return;
                }

                if (newPCodeFromChange != '') {
                    usedPCodes.push(newPCodeFromChange);
                }
                
                index = jQuery.inArray(origPCodeFromChange, usedPCodes);
                if (index >= 0) { // It was found in usedPCodesArray
                    usedPCodes.splice(index, 1);
                }

                hidNewPCode.val(newPCodeFromChange);

                if (hidNewPCode.val() == hidOriginalPCode.val()) {
                    row.css('backgroundColor', '');
                    realThis._RemoveYellowRow(row);
                } else {
                    row.css('backgroundColor', 'yellow');
                    realThis._AddYellowRow(row);
                }

                if (realThis._YellowRows.length <= 0) {
                    realThis._BtnCancel.attr('disabled', 'disabled');
                    realThis._BtnSave.attr('disabled', 'disabled');
                } else {
                    realThis._BtnCancel.removeAttr('disabled');
                    realThis._BtnSave.removeAttr('disabled');
                }
            },
            _AddYellowRow: function(row) {
                this._YellowRows.push(row);
            },
            _RemoveYellowRow: function(row) {
                var index = jQuery.inArray(row, this._YellowRows);
                if (index >= 0) {
                    this._YellowRows.splice(index, 1);
                }
            },
            _SaveButtonClick: function() {
                for (var i = 0; i < this._YellowRows.length; i++) {
                    this._YellowRows[i].css('backgroundColor', 'green');
                }
            },
            _CancelButtonClick: function() {
                $('.PCodeDropDown', this._TblPCode).each(function() {
                    var dropDown = $(this);
                    var row = dropDown.context['Row'];
                    var hidNewPCode = dropDown.context['HidNewPCode'];
                    var hidOriginalPCode = dropDown.context['HidOriginalPCode'];

                    if (hidNewPCode.val() != hidOriginalPCode.val()) {
                        dropDown.val(hidOriginalPCode.val());
                        dropDown.context['PCodeObject']._ToggleDropDown(dropDown);
                    }
                });
            },
            _InitializeDropDowns: function() {
                try {
                    var realThis = this;
                    $('tr', this._TblPCode).each(function() {
                        var row = $(this);
                        $('select', row).each(function() {
                            var dropDown = $(this);
                            dropDown.context['Row'] = row;
                            dropDown.context['PCodeObject'] = realThis;
                            dropDown.context['HidOriginalPCode'] = $(':input[type=hidden]:eq(0)', row);
                            dropDown.context['HidNewPCode'] = $(':input[type=hidden]:eq(1)', row);
                        });
                    });
                } catch (e) {
//                    debugger;
                }
            },
            _ClearButtonEventHandler: function() {
                this._TxtPCode.val('');
                this._TxtModelName.val('');
                this._TxtModelAlias.val('');
                this._TxtSku.val('');
                this._DdlPageSize.val('20');
                return false;
            },
            _LblLoadingTimerTick: function() {
                if (this._LblLoading.text() == 'Loading.') {
                    this._LblLoading.text('Loading..');
                } else if (this._LblLoading.text() == 'Loading..') {
                    this._LblLoading.text('Loading...');
                } else if (this._LblLoading.text() == 'Loading...') {
                    this._LblLoading.text('Loading.');
                }
            },
            _GetOptionString: function(pcodeValue) {
                return '<OPTION value="' + pcodeValue + '">' + pcodeValue + '</OPTION>';
            },
            _GetOptionsString: function(pcodeValues) {
                var strBuilder = new Sys.StringBuilder('');

                for (var i = 0; i < pcodeValues.length; i++) {
                    strBuilder.append(this._GetOptionString(pcodeValues[i]));
                }

                return strBuilder.toString();
            }
        };

        var objPCode = null;
        
        function GetPCodeReference() {
            return new PCode($('#<%= gvPCode.ClientID %>'),
                                    $('#<%= btnSave.ClientID %>'),
                                    $('#<%= btnCancel.ClientID%>'),
                                    $('#<%= btnClear.ClientID %>'),
                                    $('#<%= txtPCode.ClientID %>'),
                                    $('#<%= txtModelName.ClientID %>'),
                                    $('#<%= txtModelAlias.ClientID %>'),
                                    $('#<%= txtSku.ClientID %>'),
                                    $('#<%= ddlPageSize.ClientID %>'),
                                    $('#<%= lblLoading.ClientID %>'),
                                    $('#<%= divLoading.ClientID %>'),
                                    $(eval($('#<%= hidDistinctUsedPCodes.ClientID %>').val())));
        };

        function InitObject() {
            if (objPCode !== null) {
                objPCode.dispose();
                delete objPCode;
                objPCode = null;
            }
            objPCode = GetPCodeReference();
            objPCode.init();
        }

        $(document).ready(function() {           
            InitObject();
        });

        function UpdatePanelBeginRequest(sender, args) {
            try {
                objPCode.get_DivLoading().show();
            }
            catch (e) {
//                debugger;
            }
        }

        function UpdatePanelEndRequest(sender, args) {
            try {
                InitObject();
                objPCode.get_DivLoading().hide();
            }
            catch (e) {
//                debugger;
            }
        }

        Sys.WebForms.PageRequestManager.getInstance().add_endRequest(UpdatePanelEndRequest);
        Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(UpdatePanelBeginRequest);
    </script>

    <asp:UpdatePanel ID="UpdatePanel1" runat="server">
        <ContentTemplate>
            <div style="width: auto; height: 12px;">
                <div style="float: left;">
                    <h1>
                        <asp:Literal ID="litPCodeMap" runat="server" Text="<%$ Resources : LogisticsManagement,PCodeSKUMapMenuItem %>"></asp:Literal>
                    </h1>
                </div>
                <div style="float: right;">
                    <uc1:PersistNav ID="PersistNav1" runat="server" />
                </div>
            </div>
            <br />
            <hr style="width: auto;" />
            <br />
            <table width="100%" cellpadding="0" cellspacing="0" style="margin: auto;" class="greyblock">
                <tr>
                    <td align="right" style="width: 100px;">
                        <asp:Label ID="lblPCode2" runat="server" Text="PCode:"></asp:Label>
                    </td>
                    <td align="left">
                        <asp:TextBox ID="txtPCode" runat="server" Width="200px"></asp:TextBox>
                    </td>
                </tr>
                <tr>
                    <td align="right" style="width: 100px;">
                        <asp:Label ID="lblModelName" runat="server" Text="<%$ Resources : ModelManagement,LabelModelNameColon %>"></asp:Label>
                    </td>
                    <td align="left">
                        <asp:TextBox ID="txtModelName" runat="server" Width="200px"></asp:TextBox>
                    </td>
                </tr>
                <tr>
                    <td align="right" style="width: 100px;">
                        <asp:Label ID="lblModelAlias" runat="server" Text="<%$ Resources : ModelManagement,LabelModelAliasColon %>"></asp:Label>
                    </td>
                    <td align="left">
                        <asp:TextBox ID="txtModelAlias" runat="server" Width="200px"></asp:TextBox>
                    </td>
                </tr>
                <tr>
                    <td align="right" style="width: 100px;">
                        <asp:Label ID="lblSku" runat="server" Text="SKU:"></asp:Label>
                    </td>
                    <td align="left">
                        <asp:TextBox ID="txtSku" runat="server" Width="200px"></asp:TextBox>
                    </td>
                </tr>
                <tr>
                    <td align="right" style="width: 100px;">
                        <asp:Label ID="lblPageSize" runat="server" Text="<%$ Resources : Default,LabelPageSizeColon %>"></asp:Label>
                    </td>
                    <td align="left">
                        <asp:DropDownList ID="ddlPageSize" runat="server" Width="200px">
                            <asp:ListItem Text="20" Value="20" Selected="True"></asp:ListItem>
                            <asp:ListItem Text="50" Value="50" Selected="False"></asp:ListItem>
                            <asp:ListItem Text="100" Value="100" Selected="False"></asp:ListItem>
                            <asp:ListItem Text="<%$ Resources : Default,ListItemAll %>" Value="0" Selected="False"></asp:ListItem>
                        </asp:DropDownList>
                    </td>
                </tr>
                <tr>
                    <td align="right" style="width: 100px;">
                    </td>
                    <td align="left">
                        <asp:Button ID="btnSearch" runat="server" Text="<%$ Resources : Default,ButtonSearch %>" Width="100px" OnClick="btnSearch_Click" />
                        <asp:Button ID="btnClear" runat="server" Text="<%$ Resources : Default,ButtonClear %>" Width="100px" OnClientClick="return false;" />
                    </td>
                </tr>
            </table>
            <hr style="width: auto;" />
            <table width="100%" cellpadding="0" cellspacing="0" class="greyblock">
                <tr>
                    <td align="right" style="width: 100px;">
                    </td>
                    <td align="left" style="width: 225px;">
                        <asp:Button ID="btnSave" runat="server" Text="<%$ Resources : Default,ButtonSearch %>" Width="100px" Enabled="false"
                            OnClick="btnSave_Click" />
                        <asp:Button ID="btnCancel" runat="server" Text="<%$ Resources : Default,ButtonCancel %>" Width="100px" Enabled="false" />
                    </td>
                    <td align="left" style="width: 100px;">
                        <div id="divLoading" runat="server" style="display: none;">
                            <asp:Image ID="imgLoading" runat="server" ImageUrl="~/images/ajax-loader.gif" />
                            <asp:Label ID="lblLoading" runat="server" Text="<%$ Resources : SubscriberManagement,LoadingLabel %>"></asp:Label>
                        </div>
                    </td>
                    <td align="left" style="width: 300px;">
                        <asp:Label ID="lblErrorLabel" runat="server" Text="" Visible="false" Font-Bold="true"></asp:Label>
                    </td>                    
                    <td align="left">
                    </td>
                </tr>
            </table>
            <hr style="width: auto;" />
            <cc1:HitsSearchGridView ID="gvPCode" runat="server" AutoGenerateColumns="False"
                AllowPaging="True" ShowMenu="False" ShowSelectField="False" ShowActivateMenu="False"
                ShowDeActivateMenu="False" ShowEmailMenu="False" ShowPrintMenu="False" ShowHotlineMenu="False"
                ShowDeHotlineMenu="False" ShowDeleteMenu="False" ShowDeSelectMenu="True" ShowSelectMenu="True"
                HeaderStyle-Font-Size="XX-Small" AtlasScriptManagerID="" ClientFunctionActivateSelected=""
                ClientFunctionDeActivateSelected="" ClientFunctionDeHotline="" ClientFunctionDelete=""
                ClientFunctionEmailSelected="" ClientFunctionExportSelected="" ClientFunctionHotline=""
                ClientFunctionSetStatus="" CssClassCustomPaging="" CssClassMenu="" PropagateActionToChildID=""
                ShowExportCSV="False" ShowExportCSVWithSummary="False" ShowExportXML="False"
                CustomPagerID="HitsPager1" ShowExportXMLWithSummary="False" ShowSetStatus="False"
                OnRowDataBound="gvPCode_RowDataBound" Style="margin-left: 8px;" OnCustomPageIndexChanged="gvPCode_CustomPageIndexChanged"
                OnCustomPageIndexChanging="gvPCode_CustomPageIndexChanging">
                <Columns>
                    <asp:TemplateField>
                        <HeaderTemplate>
                            <asp:Literal ID="litSKUHeader" Text="SKU" runat="server" />
                            <br />
                            <uc1:CustomSorter ID="csSku" SortExpression="SKU" runat="server" OnSortAscendingClicked="customSorter_SortClicked"
                                OnSortDescendingClicked="customSorter_SortClicked" />
                        </HeaderTemplate>
                        <ItemStyle Width="150px" />
                        <ItemTemplate>
                            <asp:Literal ID="litSKU" runat="server"></asp:Literal>
                        </ItemTemplate>
                    </asp:TemplateField>
                    <asp:TemplateField>
                        <HeaderTemplate>
                            <asp:Literal ID="litModelMapID" runat="server" Text="<%$ Resources : ModelMapManagement,LabelModelMapID %>" />
                            <br />
                            <uc1:CustomSorter ID="csCompany2Model" SortExpression="COMPANY2MODEL_ID" runat="server" OnSortAscendingClicked="customSorter_SortClicked"
                                OnSortDescendingClicked="customSorter_SortClicked" />
                        </HeaderTemplate>
                        <ItemStyle Width="50px" />
                        <ItemTemplate>
                            <asp:HyperLink ID="hypModelMapID" runat="server"></asp:HyperLink>
                        </ItemTemplate>
                    </asp:TemplateField>                    
                    <asp:TemplateField>
                        <HeaderTemplate>
                            <asp:Literal ID="litModelHeader" runat="server" Text="<%$ Resources : ModelManagement,HeaderTextModel %>" />
                            <br />
                            <uc1:CustomSorter ID="csModel" SortExpression="MODEL_NAME" runat="server" OnSortAscendingClicked="customSorter_SortClicked"
                                OnSortDescendingClicked="customSorter_SortClicked" />
                        </HeaderTemplate>
                        <ItemStyle Width="150px" />
                        <ItemTemplate>
                            <asp:Literal ID="litModel" runat="server" />
                        </ItemTemplate>
                    </asp:TemplateField>
                    <asp:TemplateField>
                        <HeaderTemplate>
                            <asp:Literal ID="litModelAliasHeader" Text="<%$ Resources : ModelManagement,LabelModelAlias %>" runat="server" />
                            <br />
                            <uc1:CustomSorter ID="csModelAlias" SortExpression="ModelAlias" runat="server" OnSortAscendingClicked="customSorter_SortClicked"
                                OnSortDescendingClicked="customSorter_SortClicked" />
                        </HeaderTemplate>
                        <ItemStyle Width="500px" />
                        <ItemTemplate>
                            <asp:Literal ID="litModelAlias" runat="server" />
                        </ItemTemplate>
                    </asp:TemplateField>
                    <asp:TemplateField>
                        <HeaderTemplate>
                            <asp:Literal ID="litPCodeHeader" Text="PCode" runat="server" />
                            <br />
                            <uc1:CustomSorter ID="csPCode" SortExpression="PCode" runat="server" OnSortAscendingClicked="customSorter_SortClicked"
                                OnSortDescendingClicked="customSorter_SortClicked" />
                        </HeaderTemplate>
                        <ItemStyle HorizontalAlign="Left" />
                        <ItemTemplate>
                            <asp:DropDownList ID="ddlPCode" runat="server" Width="70px" class="PCodeDropDown"></asp:DropDownList>
                            <asp:Label ID="lblPCode" runat="server" Width="70px" Text="" class="PCodeLabel"></asp:Label>
                            <asp:HiddenField ID="hidPCodeOriginal" runat="server" Value="" />
                            <asp:HiddenField ID="hidPCodeNew" runat="server" Value="" />
                        </ItemTemplate>
                    </asp:TemplateField>
                </Columns>
                <PagerTemplate>
                    <cc1:HitsPager ID="HitsPager1" runat="server" />
                </PagerTemplate>
                <RowStyle HorizontalAlign="Left" VerticalAlign="Top" Font-Overline="False" Font-Size="XX-Small"
                    Font-Strikeout="False" Font-Underline="False" />
                <HeaderStyle Font-Size="XX-Small" Wrap="True" />
            </cc1:HitsSearchGridView>
            <!----------------------------------Data Source---------------------------------->
            <asp:ObjectDataSource ID="odsPCodeSkuMap" runat="server" TypeName="PCodeSkuMapDataSource"
                EnablePaging="True" SelectMethod="Select" SelectCountMethod="SelectCount">
                <SelectParameters>
                    <asp:SessionParameter DefaultValue="null" Name="objPCodeSkuMap" SessionField="PCodeSkuMapSearchCriteria_SessionKey"
                        Type="Object" />
                    <asp:ControlParameter ControlID="gvPCode" PropertyName="PageIndex" DefaultValue=""
                        Name="startRowIndex" Type="Int32" />
                    <asp:Parameter DefaultValue="10" Name="maximumRows" Type="Int32" />
                    <asp:SessionParameter Name="sortExpression" SessionField="PCodeSkuMapSortExpression_SessionKey"
                        Type="Object" />
                </SelectParameters>
            </asp:ObjectDataSource>
            <!-------------------------------------------------------------------------------->
            <asp:HiddenField ID="hidDistinctUsedPCodes" runat="server" Value="" />
            <%--<asp:HiddenField ID="hidDistinctUnusedPCodes" runat="server" Value="" />--%>
        </ContentTemplate>
    </asp:UpdatePanel>
</asp:Content>
