<%@ Page Language="C#" MasterPageFile="~/masterpages/eDashboard.master" AutoEventWireup="True" CodeBehind="Default.aspx.cs"
    Inherits="CarrierMMR2" Theme="eMain" Title="Brightstar Device Protection: Carrier Model Matrix Replacements" %>

<asp:Content ID="Content1" ContentPlaceHolderID="eContent" runat="server">
    <%--JAVASCRIPT--%>
    <script type="text/javascript" src="../../../script/ModelMatrixForCarriers/js/json2.js"></script>
    <script type="text/javascript" src="../../../script/ModelMatrixForCarriers/js/jquery-ui.js"></script>
    <script type="text/javascript" src="../../../script/ModelMatrixForCarriers/js/jquery.metadata.js"></script>
    <script type="text/javascript" src="../../../script/ModelMatrixForCarriers/js/jquery.tablesorter.js"></script>
    <script type="text/javascript" src="../../../script/ModelMatrixForCarriers/js/jquery.tablesorter.pager.js"></script>
    <script type="text/javascript" src="../../../script/ModelMatrixForCarriers/js/jquery.validity.min.js.js"></script>
    <script type="text/javascript" src="../../../script/ModelMatrixForCarriers/js/jquery.tablesorter.widgets.js"></script>
    <script type="text/javascript" src="../../../script/ModelMatrixForCarriers/js/jquery.tooltipster.js"></script>
    <script type="text/javascript">
        var isIE7 = false;
        var IsVertical = false;
        <% if (GetIsVerticalCMMR()){ %>
            IsVertical = true;    
        <% } %>
    </script>
    <!--[if gt IE 7]><!-->
    <script type="text/javascript" src="../../../script/ModelMatrixForCarriers/js/chosen.jquery.js"></script>
    <!--<![endif]-->
    <!--[if IE 7]>
        <link href="../../../style/ModelMatrixForCarriers/css/jquery-ui.css" rel="stylesheet" />
        <script type="text/javascript">isIE7 = true;</script>
        <script type="text/javascript" src="../../../script/ModelMatrixForCarriers/js/jquery-ui-Combobox-IE7.js"></script>
    <![endif]-->

    <%-- CSS --%>
    <link href="../../../style/ModelMatrixForCarriers/css/chosen.css" rel="stylesheet" />
    <link href="../../../style/ModelMatrixForCarriers/css/jquery-ui-1.8.18.custom.css" rel="stylesheet" />
    <link href="../../../style/ModelMatrixForCarriers/css/jquery.tablesorter.pager.css" rel="stylesheet" />
    <link href="../../../style/ModelMatrixForCarriers/css/jquery.validity.css" rel="stylesheet" />
    <link href="../../../style/ModelMatrixForCarriers/css/style.css" rel="stylesheet" />
    <link href="../../../style/ModelMatrixForCarriers/css/tablesorter.org.css" rel="stylesheet" />
    <link href="../../../style/ModelMatrixForCarriers/css/tooltipster.css" rel="stylesheet" />
    <link href="../../../style/ModelMatrixForCarriers/css/themes/tooltipster-punk.css" rel="stylesheet" />

    <table width="100%">
    <tr>
        <td>
            <h1>
                <asp:Literal ID="m_litHeader" runat="server" Text="<%$ Resources: HandsetManagement, LabelTiltleCarrierModelMatrixReplacements %>"  />
            </h1>
        </td>
    </tr>
    </table>

    <div class="mastersearch">
        <table cellspacing="0" cellpadding="0">
            <tbody>
                <tr>
                    <td style="padding-right: 0px">
                        <img onclick="toogle('search-content')" class="showstate" alt="contract" src="../../../images/Collapse_13x13.jpg" />
                    </td>
                    <td width="100%">
                        <%= Resources.Default.LabelSearchCriteria %>
                    </td>
                </tr>
            </tbody>
        </table>
    </div>
    <div id="search-content" style="background-color: #DBDCDE">
        <style type="text/css">
            #tiersList tr:hover > td,
            #dialog-tiers-tbody tr:hover > td,
            #dialog-tiers-tbody tr:hover > td label {
                background: #DBDCDE;
                cursor: pointer;
            }

            .ftable {
                background: #DEDEF4 !important;
            }

            .auto-style1 {
                width: 474px;
            }

            .hidden {
                display: none;
            }
        </style>
        <div style="width: 48%; float: right;">
            <div style="height: 130px; overflow: auto">
                <div style="display: inline-block; width: 320px; height: 130px; float: right; overflow: auto;">
                    <table id="tiersList" style="width: 300px; margin-left: auto;" class="tablesorter" cellspacing="1">
                        <thead>
                            <tr>
                                <th style="width: 50px"><%= Resources.ModelMatrixManagement.HeaderTextTier %></th>
                                <th style="width: 100px"><%= Resources.ModelMatrixManagement.ColumnHeaderLowerBound %></th>
                                <th style="width: 100px"><%= Resources.ModelMatrixManagement.ColumnHeaderUpperBound %></th>
                            </tr>
                        </thead>
                        <tbody>
                            <% foreach (var item in GetTiersList())
                               {
                                   if (!item.Tier.Equals(0))
                                   {%>
                            <tr id="rowTier<%= item.Tier %>">
                                <td class="tierID" align="center" style="width: 50px"><%= item.Tier %></td>
                                <td class="tierLB" align="right" style="width: 100px"><%= item.Lower.ToString("C") %></td>
                                <td class="tierUB" align="right" style="width: 100px"><%= item.Upper.ToString("C") %></td>
                            </tr>
                            <%   }
                                   else
                                   { %>
                            <tr>
                                <td colspan="3" align="center"><%= Resources.ModelMatrixManagement.LabelNoTierDefinitionsFound %></td>
                            </tr>
                            <%}
                               } %>
                        </tbody>
                    </table>
                </div>
                <div id="piechart" style="width: 130px; height: 130px; float: right; margin-right: 20px;"></div>
            </div>
        </div>
        <div style="width: 48%; float: left;">
            <table cellspacing="0" cellpadding="0">
                <tr>
                    <td>
                        <asp:Label runat="server" ID="lbl_cliet" Text="<%$ Resources: OrganizationManagement, LabelClientColon %>"></asp:Label>
                    </td>
                    <td>
                        <asp:DropDownList runat="server" ID="ddl_clientList" CssClass="ddlClientList" OnSelectedIndexChanged="ddl_clientList_SelectedIndexChanged" AutoPostBack="true"></asp:DropDownList>
                    </td>
                    <td>&nbsp;</td>
                    <td>
                        <asp:Button CssClass="" Text="<%$ Resources: ModelMatrixManagement, ButtonLoadMatrix %>" ID="btn_LoadMatrix" runat="server" OnClick="btn_LoadMatrix_Click" Height="20px" />
                    </td>
                    <td></td>

                </tr>
                <tr>
                    <td>
                        <asp:Label runat="server" ID="lbl_carrier" Visible="false" Text="<%$ Resources: OrganizationManagement, LabelCarrierColon %>"></asp:Label></td>
                    <td>
                        <asp:DropDownList runat="server" ID="ddl_carrier" CssClass="ddlCarrier" Visible="false" OnSelectedIndexChanged="ddl_carrier_SelectedIndexChanged"></asp:DropDownList></td>
                    <td></td>
                    <td></td>
                    <td></td>

                </tr>
                <tr>
                    <td>
                        <asp:Label runat="server" ID="lbl_programType" Text="<%$ Resources: OrganizationManagement, LabelProgramTypeColon %>"></asp:Label></td>
                    <td>
                        <asp:DropDownList runat="server" ID="ddl_programType" CssClass="ddlProgramType" OnSelectedIndexChanged="ddl_programType_SelectedIndexChanged"></asp:DropDownList></td>
                    <td></td>
                    <td></td>
                    <td></td>

                </tr>
                <tr>
                    <td>&nbsp</td>
                </tr>
            </table>
        </div>
        <div style="width: 100%; height: 2px; font-size: 1px; float: none; clear: both;"></div>

    </div>
    <br />

    <div>
        <div class="mastersearch">
            <table cellspacing="0" cellpadding="0">
                <tbody>
                    <tr>
                        <td style="padding-right: 0px">
                            <img class="showstate" onclick="toogle('acctions-buttons')" alt="contract" src="../../../images/Collapse_13x13.jpg" />
                        </td>
                        <td width="100%">
                            <%= Resources.ModelMatrixManagement.LabelPerformAction %>
                        </td>
                    </tr>
                </tbody>
            </table>
        </div>
        <div id="acctions-buttons" style="background-color: #DBDCDE;">
            <table id="table_action" <%= IsReadOnly ? "style=\"width: 600px;\"" : "style=\"width: 600px; margin: auto\"" %> >
                <tr id="tr_actions">
                    <td>
                        <asp:Button runat="server" ID="btnFindAndReplace" />
                    </td>
                    <asp:Panel ID="plchActionBtns" runat="server">
                        <td style="display: none;">
                            <asp:Button CssClass="" ID="btnLock" Text="<%$ Resources: ModelMatrixManagement, TextActionLock %>" runat="server" Visible="false" />
                        </td>
                        <td>
                            <asp:Button CssClass="" ID="btnReset" Text="<%$ Resources: ModelMatrixManagement, TextActionReset %>" runat="server" Visible="false" />
                        </td>
                        <td>
                            <asp:Button CssClass="" ID="btnApprove" Text="<%$ Resources: ModelMatrixManagement, TextActionApprove %>" runat="server" Visible="false" />
                        </td>
                        <td>
                            <asp:Button CssClass="" ID="btnUpdateAcction" Text="<%$ Resources: ModelMatrixManagement, TextActionUpdate %>" runat="server" Visible="false" />
                        </td>
                        <td>
                            <asp:Button CssClass="" ID="btnSendback" Text="<%$ Resources: ModelMatrixManagement, TextActionSendBack %>" runat="server" Visible="false" />
                        </td>
                        <td>
                            <asp:Button CssClass="" ID="btnPushprod" Text="<%$ Resources: ModelMatrixManagement, TextActionPushProduction %>" runat="server" Visible="false" />
                        </td>
                    </asp:Panel>
                </tr>
            </table>
            <asp:PlaceHolder ID="pchUpdateSubmit" runat="server">
                <table style="width: 300px; margin: auto">
                    <tr>
                        <td>
                            <asp:Button CssClass="" ID="btnUpdate" Text="<%$ Resources: ModelMatrixManagement, TextActionSaveData %>" runat="server" />
                        </td>
                        <td>
                            <asp:Button CssClass="" ID="btnSubmit" Text="<%$ Resources: ModelMatrixManagement, TextActionSubmitEsec %>" runat="server" />
                        </td>
                    </tr>
                </table>
            </asp:PlaceHolder>
        </div>
        <br />
        <div>

            <div class="mastersearch">
                <table cellspacing="0" cellpadding="0">
                    <tbody>
                        <tr>
                            <td style="padding-right: 0px">
                                <img onclick="toogle('display-columns')" class="showstate" alt="contract" src="../../../images/Collapse_13x13.jpg" />
                            </td>
                            <td width="100%">
                                <%= Resources.Default.LabelColumnsVisibility %>
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>
            <br />
            <div id="display-columns" style="background-color: #DBDCDE; margin-bottom: 25px;">
                <table>
                    <tr>
                        <td style="width: 150px">
                            <input type="checkbox" id="Tier"/><%= Resources.ModelMatrixManagement.HeaderTextTier %></td>
                        <td style="width: 150px">
                            <input type="checkbox" id="TierJumpers"/><%= Resources.ModelMatrixManagement.ColumnHeaderTierJump %></td>
                        <td style="width: 150px">
                            <input type="checkbox" id="TechType"/><%= Resources.ModelMatrixManagement.ColumnHeaderTechType %></td>
                        <td style="width: 150px">
                            <input type="checkbox" id="NewCost"/><%= Resources.ModelMatrixManagement.ColumnHeaderNewCost %><br/></td>
                        <td style="width: 150px">
                            <input type="checkbox" id="NewRetailPrice"/><%= Resources.ModelMatrixManagement.ColumnHeaderNewRetailPrice %></td>
                    </tr>
                    <tr>
                        <td style="width: 150px">
                            <input type="checkbox" id="NonNewCost"/><%= Resources.ModelMatrixManagement.ColumnHeaderNonNewCost %><br/></td>
                        <td style="width: 150px">
                            <input type="checkbox" id="NonNewRetailPrice"/><%= Resources.ModelMatrixManagement.ColumnHeaderNonNewRetailPrice %></td>
                        <td style="width: 150px">
                            <input type="checkbox" id="NonNewCostRatio"/><%= Resources.ModelMatrixManagement.ColumnHeaderNonNewCostRatio %></td>
                        <td style="width: 150px">
                            <input type="checkbox" id="ChargebackFee"/><%= Resources.ModelMatrixManagement.ColumnChargebackFee %></td>
                    </tr>
                </table>
            </div>

            <asp:Panel ID="matrixPropPnl" runat="server">
                <div class="mastersearch" style="margin-bottom:10px;">
                    <table cellspacing="0" cellpadding="0">
                        <tbody>
                            <tr>
                                <td style="padding-right: 0px">
                                    <img onclick="toogle('display-columns-matrixProp')" class="showstate" alt="contract" src="../../../images/Collapse_13x13.jpg" />
                                </td>
                                <td width="100%">
                                    <%= Resources.Default.LabelMatrixProperties %>
                                </td>
                            </tr>
                        </tbody>
                    </table>
                </div>

                <div id="display-columns-matrixProp" class="displayColumnsMatrixProp">
                    <input type="checkbox" id="chckNewCostAutoCalc" checked="checked" /><%= Resources.ModelMatrixManagement.LabelAutoCalcNewCost %>
                </div>
            </asp:Panel>

            <div style="width: 48%; float: left;">
                <table>
                    <tr>
                        <td>
                            <div id="lblMatrixStatus">
                                <h2 id="lblMatrixStatusTitle"></h2>
                                <asp:Label ID="lblMatrixHistory" runat="server" Font-Bold="true" />
                            </div>
                            <asp:Label Text="[lbl_isVertical]" ID="lbl_isVertical" runat="server" Visible="false" />
                        </td>
                        <td></td>
                        <td>
                            <asp:Label Text="[lblRetailPriceNew]" runat="server" ID="lblRetailPriceNew" Visible="false" />
                        </td>
                        <td>
                            <asp:Label Text="[lblNonNewCost]" runat="server" ID="lblNonNewCost" Visible="false" />
                        </td>
                        <td>
                            <asp:Label Text="[lblRetailPriceNonNew]" runat="server" ID="lblRetailPriceNonNew" Visible="false" />
                        </td>
                    </tr>
                </table>
            </div>

            <div style="width: 48%; float: right;">
                <div id="info-div" class="info" style="display: none; width: 250px; height: 20px; margin-left: auto"><%= Resources.ModelMatrixManagement.LabelUnsavedChangesInMatrix %></div>
            </div>
            <div style="width: 100%; height: 2px; font-size: 1px; float: none; clear: both;"></div>
        </div>
        <div>
            <table id="myTable" class="tablesorter  somethinglese" cellspacing="1">
                <thead>
                    <tr>
                        <th><%= Resources.ModelMatrixManagement.ColumnHeaderModel %></th>
                        <th><%= Resources.ModelMatrixManagement.HeaderTextTier %></th>
                        <th><%= Resources.ModelMatrixManagement.ColumnHeaderTierJump %></th>
                        <th><%= Resources.ModelMatrixManagement.ColumnHeaderTechType %></th>
                        <th><%= Resources.ModelMatrixManagement.ColumnHeaderNewCost %></th>
                        <th><%= Resources.ModelMatrixManagement.ColumnHeaderNewRetailPrice %></th>
                        <th><%= Resources.ModelMatrixManagement.ColumnHeaderNonNewCost %></th>
                        <th><%= Resources.ModelMatrixManagement.ColumnHeaderNonNewRetailPrice %></th>
                        <th><%= Resources.ModelMatrixManagement.ColumnHeaderNonNewCostRatio %></th>
                        <th><%= Resources.ModelMatrixManagement.ColumnChargebackFee %></th>
                        <th style="display: none"><%= Resources.ModelMatrixManagement.ColumnHeaderPrimary %></th>
                        <th style="display: none"><%= Resources.ModelMatrixManagement.ColumnHeaderSecondary %></th>
                        <th id="tertiary_header" style="display: none"><%= Resources.ModelMatrixManagement.ColumnHeaderTertiary %></th>
                    </tr>
                </thead>
                <%
                    System.Web.Script.Serialization.JavaScriptSerializer js = new System.Web.Script.Serialization.JavaScriptSerializer();
                    int totalrecords = 0;
                    var rep = new ModelJsonObject();
                    var lMatrix = GetMatrixTable();
                    string currencySymbol = System.Globalization.CultureInfo.CurrentCulture.NumberFormat.CurrencySymbol;
                    int currencyPattern = System.Globalization.CultureInfo.CurrentCulture.NumberFormat.CurrencyPositivePattern;
                %>
                <tbody id="matrix_tbody" <% if (lMatrix.Count != 0)
                                            { %>style="display: none"
                    <% } %>>
                    <%
                        if (lMatrix.Count == 0)
                        {
                            for (int i = 0; i < 10; i++)
                            {%>
                    <tr>
                        <td>&nbsp;</td>
                        <td>&nbsp;</td>
                        <td>&nbsp;</td>
                        <td>&nbsp;</td>
                        <td>&nbsp;</td>
                        <td>&nbsp;</td>
                        <td>&nbsp;</td>
                        <td>&nbsp;</td>
                        <td>&nbsp;</td>
                        <td>&nbsp;</td>
                        <td style="display: none">&nbsp;</td>
                        <td style="display: none">&nbsp;</td>
                        <td style="display: none">&nbsp;</td>
                    </tr>
                    <%}
                        }
                        else
                        {
                            foreach (var item in lMatrix)
                            {
                                totalrecords++;
                    %>

                    <%-- Please dont format tr below its required to look like this because of the strange IE9 bug --%>

                    <tr class="<%=ShowAllClients() ? (item.ChangedBy > 1 ? "changedtd " : (item.IsEdited ? "updatedtd ":"")) : (item.IsEdited ? "updatedtd ":"") %>ui-widget-content<%= (totalrecords % 2) == 0 ? " odd":" even" %>" id="<%= totalrecords %>"><td style="min-width: 200px"><label id="lbl_<%= totalrecords %>" class='<%=item.TierEx && GetTierLevel(item) == 2 ? "tier_exeption label_pointer": item.TierEx && GetTierLevel(item) == 1 ? "tier_exeption_lower label_pointer" : "label_pointer" %>' onclick='<%=  HasSecurityClearanceVClient() ?"OpenModal(this)":"" %>'>
                                <%= item.ModelName %>
                            </label>
                            <input id="td_model_id_<%= totalrecords %>" type="text" value="<%= item.ModelID %>" style="display: none" />
                            <input id="input_vertical_models_<%= totalrecords %>" type="text" value='<%= GetReplacementModels(item) %>' style="display: none" /></td><td><%= item.Tier %></td><td><%= item.TierJumpCount ? Resources.Default.ButtonYes : Resources.Default.ButtonNo %></td><td align="right" style="min-width: 50px" id="td_techType_<%= totalrecords %>"><%= item.TechType %></td><td align="right" style="min-width: 50px" id="td_newCost_<%= totalrecords %>">
                            <label class="label-pointer" <%= IsReadOnly ? "" : "onclick=\"changeToInput(this)\"" %>><%= item.NewCost.ToString("C") %></label>
                            <input autocomplete="off" id="input_newCost_<%= totalrecords %>" type="text" style="width: 47px; display: none" value="<%= decimal.Round(item.NewCost, 2, MidpointRounding.AwayFromZero) %>" /></td><td align="right" id="td_retailprice_<%= totalrecords%>">
                            <label class="label-pointer" <%= IsReadOnly ? "" : "onclick=\"changeToInput(this)\"" %>><%= item.RetailPriceNew.ToString("C") %></label>
                            <input autocomplete="off" id="input_retailprice_<%= totalrecords %>" type="text" style="width: 47px; display: none" value="<%= decimal.Round(item.RetailPriceNew, 2, MidpointRounding.AwayFromZero) %>" /></td><td align="right" id="td_refurbcost_<%= totalrecords%>">
                            <label class="label-pointer" <%= IsReadOnly ? "" : "onclick=\"changeToInput(this)\"" %>><%= item.RefurbCost.ToString("C") %></label>
                            <input autocomplete="off" id="input_refurbcost_<%= totalrecords %>" type="text" style="width: 47px; display: none" value="<%= decimal.Round(item.RefurbCost, 2, MidpointRounding.AwayFromZero) %>" /></td><td align="right" id="td_retailpricenonnew_<%= totalrecords%>">
                            <label class="label-pointer" <%= IsReadOnly ? "" : "onclick=\"changeToInput(this)\"" %>><%= item.RetailPriceNonNew.ToString("C") %></label>
                            <input autocomplete="off" id="input_retailpricenonnew_<%= totalrecords %>" type="text" style="width: 47px; display: none" value="<%= decimal.Round(item.RetailPriceNonNew, 2, MidpointRounding.AwayFromZero) %>" /></td><td align="right" id="td_costratio_<%= totalrecords%>"><%= Convert.ToInt32(item.CostRatio) %>%</td><td align="right" id="td_other_<%= totalrecords%>">
                            <label class="label-pointer" <%= IsReadOnly ? "" : "onclick=\"changeToInput(this)\"" %>><%= item.Other.ToString("C") %></label>
                            <input autocomplete="off" id="input_other_<%= totalrecords %>" type="text" style="width: 47px; display: none" value="<%= decimal.Round(item.Other, 2, MidpointRounding.AwayFromZero) %>" /></td><% for (int a = 0; a < 3; a++){ %><td style="min-width: 100px; display: none">
                            <div id='<%=String.Format("{0}{1}",(a == 0? "primary_":(a==1?"secondary_":"tertiary_")), totalrecords )%>'>
                                <input id='<%=String.Format("{0}{1}",(a==0?"input_primary_current_":(a==1?"input_secondary_current_":"input_tertiary_current_")), totalrecords) %>' type="hidden" value='<%= SerializeModelJsonObject(item.Replacements[0])  %>' />

                                <% if (item.Replacements.Count > a)
                                   {
                                       rep = item.Replacements[a];
                                   }
                                   else
                                   {
                                       rep = new ModelJsonObject();
                                   } 
                                %>
                                <label class='<%=!GetIsVerticalCMMR() ? "label-pointer":"" %> <%=string.IsNullOrEmpty(rep.ModelName)?"": rep.TierEx ? "tier_exeption":"" %>' onclick='<%= !GetIsReplacementsReadonly() ?"changeToSelect(this)":"" %>'><%= string.IsNullOrEmpty(rep.ModelName)?"&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;":rep.ModelName %></label>
                        </div></td><% } %></tr>
                    <% }
                        } %>
                </tbody>
            </table>
            <% if (totalrecords > 0)
               { %>
            <div id="message_loading" style="text-align: center; padding: 5px 0; border: 1px solid #CCC; margin: 10px 0;">
                <label style="font-size: 16px; padding-top: 5px; padding-bottom: 10px"><%= Resources.ModelMatrixManagement.LabelGeneratingRecords %></label>
            </div>
            <% } %>

            <!-- pager -->
            <div class="pager">
                <img src="../../../style/ModelMatrixForCarriers/css/first.png" class="first" />
                <img src="../../../style/ModelMatrixForCarriers/css/prev.png" class="prev" />
                <span class="pagedisplay"></span>
                <!-- this can be any element, including an input -->
                <img src="../../../style/ModelMatrixForCarriers/css/next.png" class="next" />
                <img src="../../../style/ModelMatrixForCarriers/css/last.png" class="last" />
                <select class="pagesize" title="<%= Resources.ModelMatrixManagement.LabelSelectPageSize%>">
                    <option value="10">10</option>
                    <option value="20">20</option>
                    <option value="30">30</option>
                    <option value="40">40</option>
                </select>
                <select class="gotoPage" title="<%= Resources.ModelMatrixManagement.LabelSelectPageNumber %>"></select>
            </div>
        </div>
        <br />
        <div>
            <table cellspacing="0" cellpadding="0" style="width: 878px">
                <tr>
                    <td>
                        <label><%= Resources.ModelMatrixManagement.LabelNewCostEquipament %></label>
                    </td>
                </tr>
                <tr>
                    <td>
                        <label><%= Resources.ModelMatrixManagement.LabelNewRetailPriceEquipament %></label>
                    </td>
                </tr>
                <tr>
                    <td>
                        <label><%= Resources.ModelMatrixManagement.LabelNonNewCostEquipament %></label>
                    </td>
                </tr>
                <tr>
                    <td>
                        <label><%= Resources.ModelMatrixManagement.LabelNoNewRetailPriceEquipament %></label>
                    </td>
                </tr>
                <tr>
                    <td class="auto-style1">
                        <span style="float: left">
                            <img src="../../../style/ModelMatrixForCarriers/css/alertWarning.png" /></span>
                        <span style="align-items: stretch">
                            <label><%= Resources.ModelMatrixManagement.LabelTierException %></label></span>
                    </td>
                </tr>
                <tr>
                    <td class="auto-style1">
                        <span style="float: left">
                            <img src="../../../style/ModelMatrixForCarriers/css/alert.png" /></span>
                        <span style="align-items: stretch">
                            <label><%= Resources.ModelMatrixManagement.LabelLowerTierException %></label></span>
                    </td>
                </tr>
                <tr>
                    <td>
                        <span style="float: left">
                            <label style="background-color: yellow; width: 16px; height: 16px; display: inline-block;"></label>
                        </span>
                        <span><%= Resources.ModelMatrixManagement.LabelMatrixRecordUpdated %></span>
                    </td>
                </tr>
                <tr>
                    <td>
                        <span style="float: left">
                            <label style="background-color: #F78181; width: 16px; width: 16px; height: 16px; display: inline-block;"></label>
                        </span>
                        <span><%= Resources.ModelMatrixManagement.LabelNonNewCostRatioGreaterThanOrganizationDefault %></span>
                    </td>
                </tr>
                <tr>
                    <td>
                        <span style="float: left">
                            <label style="background-color: #bde5f8; width: 16px; width: 16px; height: 16px; display: inline-block;"></label>
                        </span>
                        <span><%= Resources.ModelMatrixManagement.LabelCellsChangedByTheLastSave %></span>
                    </td>
                </tr>
                <tr style="<%=ShowAllClients() ? "": "visibility : hidden " %>">
                    <td>
                        <span style="float: left">
                            <label style="background-color: #3cb371; width: 16px; width: 16px; height: 16px; display: inline-block;"></label>
                        </span>
                        <span><%= Resources.ModelMatrixManagement.LabelChangedBy %></span>
                    </td>
                </tr>
            </table>
        </div>
    </div>
    <div id="dialog-form" title="Vertical Model Matrix" style="display: none">
        <input id="current_rowid_popup" style="display: none" value="0" />
        <p class="validateTips">Matrix</p>
        <table id="model_verticalmatrix" class="tablesorter modelverticalmatrix_table_margine_bottom">
            <thead>
                <tr>
                    <th class="th1"><%= Resources.ModelMatrixManagement.ColumnHeaderPosition %></th>
                    <th class="th2"><%= Resources.ModelMatrixManagement.ColumnHeaderReplacement %></th>
                    <% if (GetIsVerticalCMMR()){%>
                    <th class="th3"><%= Resources.ModelMatrixManagement.ColumnHeaderCondition %></th>
                    <% } %>
                     <% if (!IsReadOnly){%>
                    <th class="th4"><%= Resources.ModelMatrixManagement.ColumnHeaderRemove %></th>
                    <% } %>
                </tr>
            </thead>
            <tbody id="model_verticalmatrix_tbody">
                <tr style="text-align: center">
                    <td colspan="4">
                        <label>Loading models...</label></td>
                </tr>
            </tbody>
        </table>
        <input id="btn_add" class="" type="button" value="Add" onclick="AddRow(this)" />
    </div>
    <div id="loading_dialog"></div>
    <!-- Tiers -->
    <div id="dialog-tiers" title="Vertical Model Matrix" style="display: none">
        <input id="Text1" style="display: none" value="0" />
        <p class="validateTips"></p>
        <table id="Table1" class="tablesorter">
            <thead>
                <tr style="text-align: center">
                    <th><%= Resources.ModelMatrixManagement.ColumnHeaderModel %></th>
                </tr>
            </thead>
            <tbody id="dialog-tiers-tbody">
                <tr style="text-align: center">
                    <td>
                        <label>Loading models...</label>
                    </td>
                </tr>
            </tbody>
        </table>
        <br />
    </div>
    <!-- Fin Tiers -->
    <div id="dialog-replacement" title="<%= IsReadOnly ? Resources.ModelMatrixManagement.LabelFindModel : Resources.ModelMatrixManagement.LabelModelReplacement %>" style="display: none">
        <table class="tableModels">
            <tr>
                <td>
                    <label><%= Resources.ModelMatrixManagement.LabelFindModel %>:</label>
                </td>
                <td>
                    <label id="lblModelToReplace"></label>
                    <input id="btn_Find" class="btnFind" type="button" value="<%= Resources.ModelMatrixManagement.LabelBtnFind %>"/>
                </td>
            </tr>
            <asp:PlaceHolder ID="plchFindAndReplaceActions" runat="server">
                <tr>
                    <td>
                        <label><%= Resources.ModelMatrixManagement.LabelAction %>:</label>
                    </td>
                    <td>
                        <input type="radio" name="cbAction" id="cbReplaceWith" checked="checked" /><%= Resources.ModelMatrixManagement.LabelReplaceWith %>
                        <label id="lblModelToReplaceWith"></label>
                    </td>
                </tr>
                <tr>
                    <td></td>
                    <td>
                        <input type="radio" name="cbAction" id="cbRemove" /><%= Resources.ModelMatrixManagement.LabelRemove %>                
                    </td>
                </tr>
            </asp:PlaceHolder>
            <tr>
                <td></td>
                <td>
                    <table id="tblAllModelsWithSelectedRep" class="tablesorter" style="width:500px;display:none;">
                        <thead>
                            <tr>
                                <th class="th1"><input type="checkbox" id="chckAllModels"/></th>
                                <th class="th2"><%= Resources.ModelMatrixManagement.LabelTblModel %></th>
                                <th  id="appendVertical" class="th2"><%= Resources.ModelMatrixManagement.LabelTblReplacementModel %></th>
                                <th class="th3"><%= Resources.ModelMatrixManagement.LabelTblPosition %></th>
                            </tr>
                        </thead>
                        <tbody id="tblAllModelsWithSelectedRep_tbody">
                            <tr style="text-align: center">
                                <td colspan="3">
                                    <label><%= Resources.ModelMatrixManagement.LabelTblLoading %></label>
                                </td>
                            </tr>
                        </tbody>
                    </table>
                </td>
            </tr>
        </table>
    </div>

    <%--<input type="hidden" id="jsonModels" value='<= GetModels() %>' />--%>
    <asp:TextBox runat="server" ID="jsonModels" CssClass="hidden" Text="" />
    <asp:TextBox runat="server" ID="masterModels" CssClass="hidden" Text="" TextMode="MultiLine" />
    <input type="hidden" id="jsonTier" value='<%= GetTiers() %>' />
    <input type="hidden" id="inputActive" value="0" />
    <input type="hidden" id="inputConditions" value='<%= GetConditions() %>' />


    <div id="dialog-TimeoutPanel" title="Timeout Warning" style="display: none;">
        <p>
            Your session will expire in
            <label id="spTimeoutCount">1 min.</label> Your changes will be saved automatically.
              <br />
            <br />
            If you wish to save your changes, click the save button, or if you want to continue using the session, click the continue button.
        </p>

        <p style="text-align: center;">
            <input id="btnPreserveSession" title="Update matrix" type="button" value="Save Changes" onclick="PreserveSession()" />
            <input id="btnCancelDialog" type="button" title="Close" value="Continue Session" onclick="HideUserTimeout()" />
        </p>
    </div>
    
    <asp:HiddenField ID="hdUpdateFlag" runat="server"/>

    <script type="text/javascript" src="https://www.google.com/jsapi"></script>
    <script type="text/javascript">
        google.load("visualization", "1", {packages:["corechart"]});
        var graphic = null;
        function drawChart(d) {
            var chart = new google.visualization.PieChart(document.getElementById('piechart'));
            var data = google.visualization.arrayToDataTable(d);
            var options = {
                legend: 'none',
                backgroundColor: '#DBDCDE',
                chartArea:  {
                    width:'90%',
                    height:'90%'
                },
                tooltip: {
                    textStyle: {
                        fontSize: 10
                    },
                    trigger: 'none'
                },
                //is3D: true,
                pieSliceTextStyle: {
                    fontSize: 10
                },
                colors:['#0a294f','#1860b8','#3081e4','#6ca6ec','#e4effc']
            };

            this.setData = function(d) {
                data = google.visualization.arrayToDataTable(d);
            }
            
            this.createChart = function() {
                chart.draw(data, options); 
            }

            this.closeChart = function() {
                data = null;
                chart.clearChart();
            }

            this.getSelect = function() {
                return chart.getSelection();
            }

            this.setSelect = function(r) {
                if(r != null)   chart.setSelection([{row: r, column: null}]);
                else    chart.setSelection();
            }

            google.visualization.events.addListener(chart, 'select', function() {
                var selection = chart.getSelection();
                if(selection != null && selection[0] != null) {
                    $("#rowTier" + (selection[0].row+1)).click();
                }
                chart.setSelection(null);
                
            });           
            google.visualization.events.addListener(chart, 'onmouseover', function(e) {
                if(e != null && e.row != null) {
                    $("#rowTier" + (e.row+1)).find("td").addClass("ftable");
                }
            });        
            google.visualization.events.addListener(chart, 'onmouseout', function(e) {
                if(e != null && e.row != null) {
                    $("#rowTier" + (e.row+1)).find("td").removeClass("ftable");
                }
            }); 
        }   
        
        <% 
        if (_ModelMatrix.chartTiers != "")
        { 
        %>
        $(document).ready(function() {
            <%= _ModelMatrix.chartTiers %>
            graphic = new drawChart(data);
            graphic.createChart();
        });
        <% } %>

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


        function ShowHideColumns() {
            //TechType
            var columnsPar = new Object();
            if ($("#TechType").prop('checked')) {
                columnsPar.TechType = true;
            } else {
                columnsPar.TechType  = false;
            }
            //Chargeback Fee
            if ($("#ChargebackFee").prop('checked')) {
                columnsPar.ChargebackFee = true;
            } else {
                columnsPar.ChargebackFee  = false;
            }
            //New Cost
            if ($("#NewCost").prop('checked')) {
                columnsPar.NewCost = true;
            } else {
                columnsPar.NewCost  = false;
            }
            //New Reatil Price
            if ($("#NewRetailPrice").prop('checked')) {
                columnsPar.NewRetailPrice = true;
            } else {
                columnsPar.NewRetailPrice  = false;
            }
            //Non-New Reatil Price
            if ($("#NonNewRetailPrice").prop('checked')) {
                columnsPar.NonNewRetailPrice = true;
            } else {
                columnsPar.NonNewRetailPrice  = false;
            }
            //Non-New Cost
            if ($("#NonNewCost").prop('checked')) {
                columnsPar.NonNewCost = true;
            } else {
                columnsPar.NonNewCost  = false;
            }
            //Tier
            if ($("#Tier").prop('checked')) {
                columnsPar.Tier = true;
            } else {
                columnsPar.Tier  = false;
            }
            //Tier Jumpers
            if ($("#TierJumpers").prop('checked')) {
                columnsPar.TierJumpers = true;
            } else {
                columnsPar.TierJumpers  = false;
            }
            //NonNewCostRatio
            if ($("#NonNewCostRatio").prop('checked')) {
                columnsPar.NonNewCostRatio = true;
            } else {
                columnsPar.NonNewCostRatio  = false;
            }

            //Matrix Properties
            columnsPar.AutoCalcNewCost = $("#chckNewCostAutoCalc").prop('checked');

            updateColumnsVisibility(columnsPar);
        };

        function ShowHideColumnsInitial(json) {
            //TechType
            if (json.TechType) {
                $('#myTable th:nth-child(4)').show();
                $('#myTable td:nth-child(4)').show();
            } else {
                $('#myTable th:nth-child(4)').hide();
                $('#myTable td:nth-child(4)').hide();
            }
            //Chargeback Fee
            if (json.ChargebackFee) {
                $('#myTable th:nth-child(10)').show();
                $('#myTable td:nth-child(10)').show();
            } else {
                $('#myTable th:nth-child(10)').hide();
                $('#myTable td:nth-child(10)').hide();
            }
            //New Cost
            if (json.NewCost) {
                $('#myTable th:nth-child(5)').show();
                $('#myTable td:nth-child(5)').show();

            } else {
                $('#myTable th:nth-child(5)').hide();
                $('#myTable td:nth-child(5)').hide();
            }
            //New Reatil Price
            if (json.NewRetailPrice) {
                $('#myTable th:nth-child(6)').show();
                $('#myTable td:nth-child(6)').show();
            } else {
                $('#myTable th:nth-child(6)').hide();
                $('#myTable td:nth-child(6)').hide();
            }
            //Non-New Reatil Price
            if (json.NonNewRetailPrice) {
                $('#myTable th:nth-child(8)').show();
                $('#myTable td:nth-child(8)').show();
            } else {
                $('#myTable th:nth-child(8)').hide();
                $('#myTable td:nth-child(8)').hide();
            }
            //Non-New Cost
            if (json.NonNewCost) {
                $('#myTable th:nth-child(7)').show();
                $('#myTable td:nth-child(7)').show();

            } else {
                $('#myTable th:nth-child(7)').hide();
                $('#myTable td:nth-child(7)').hide();
            }
            //Tier
            if (json.Tier) {
                $('#myTable th:nth-child(2)').show();
                $('#myTable td:nth-child(2)').show();

            } else {
                $('#myTable th:nth-child(2)').hide();
                $('#myTable td:nth-child(2)').hide();
            }
            //TierJumpers
            if (json.TierJumpers) {
                $('#myTable th:nth-child(3)').show();
                $('#myTable td:nth-child(3)').show();

            } else {
                $('#myTable th:nth-child(3)').hide();
                $('#myTable td:nth-child(3)').hide();
            }
            //Non New Cost Ratio
            if (json.NonNewCostRatio) {
                $('#myTable th:nth-child(9)').show();
                $('#myTable td:nth-child(9)').show();

            } else {
                $('#myTable th:nth-child(9)').hide();
                $('#myTable td:nth-child(9)').hide();
            }

        };

        function setCheckBoxes(json) {
            $("#TechType").prop('checked', json.TechType);
            $("#ChargebackFee").prop('checked', json.ChargebackFee);
            $("#NewCost").prop('checked', json.NewCost);
            $("#NewRetailPrice").prop('checked', json.NewRetailPrice);
            $("#NonNewRetailPrice").prop('checked', json.NonNewRetailPrice);
            $("#NonNewCost").prop('checked', json.NonNewCost);
            $("#Tier").prop('checked', json.Tier);
            $("#TierJumpers").prop('checked', json.TierJumpers);
            $("#NonNewCostRatio").prop('checked', json.NonNewCostRatio);

            //Matrix Properties
            $("#chckNewCostAutoCalc").prop('checked', json.AutoCalcNewCost);
        };


        $(":checkbox").change(function() {
            ShowHideColumns();
        });

    </script>

    <script type="text/javascript">

        var WarnMills;
        var TimeoutMills;
        var CheckInternal = 10000; //10 sec.
        var sessionTimeoutMills = 0;
        var lastMinute = 60000;
        var intval;
        var timeOut;
 
        function clientReceiveServerData(returnValue) {}

        function StartTimeout(timeoutValue, warnValue, URLValue)
        {
            TimeoutMills = timeoutValue;
            WarnMills = warnValue;//120000 miliseconds = 2 min.
            sessionTimeoutMills = timeoutValue;
            setTimeout('CheckSessionTimeOut()', CheckInternal);
        }

        function CheckSessionTimeOut()
        {
            if(TimeoutMills <= (WarnMills + CheckInternal))
            {
                intval=setInterval('updateAndSignOut()', 1000);
                WarnTimeout();
            }
            else
            {
                TimeoutMills = TimeoutMills - CheckInternal;
                setTimeout('CheckSessionTimeOut()', CheckInternal);
            }
        }
 
        function WarnTimeout()
        {
            $('#dialog-TimeoutPanel').dialog({
                modal: true, 
                closeOnEscape: false, 
                open: function(event, ui) { $(".ui-dialog-titlebar-close").hide(); }, 
                width: 500, 
                dialogClass: 'modal-matrix'
            });
        }
 
        function PreserveSession()
        {
            var $masterModel = $('#<%=masterModels.ClientID%>');
            if (!$masterModel.val()) {

                alert("<%= Resources.ModelMatrixManagement.LabelNothingToUpdate %>");

                //Refresh timeout
                HideUserTimeout();
                return;
            }
            $('#' + '<%= btnUpdateAcction.ClientID %>').click();
        }

        function HideUserTimeout() {
            $('#' + '<%= hdUpdateFlag.ClientID %>').val("0");// flag '1' will perform sign out but flag '0' will not.
            $('#dialog-TimeoutPanel').dialog('close');
            if(intval) clearInterval(intval);
            TimeoutMills = sessionTimeoutMills;
            lastMinute = 60000;
            $('#spTimeoutCount').text("1 min.");
            setTimeout('CheckSessionTimeOut()', CheckInternal);

            //Refresh session timeout on the Server side.
            clientCallServer();
        }

        function updateAndSignOut() {
            if (lastMinute == 0) {
                if(intval) clearInterval(intval);
                $('#' + '<%= hdUpdateFlag.ClientID %>').val("1");
                $('#dialog-TimeoutPanel').dialog('close');
                Update();
            } else if (lastMinute <= 30000) {
                var secLeft = lastMinute / 1000;
                $('#spTimeoutCount').text(secLeft + " " + "sec.");
                lastMinute -= 1000;
                return;
            }
            lastMinute -= 1000;
            return;
        }

        function setColumnsViability() {
            $.ajax({
                type: "POST",
                url: "Default.aspx/GetVisibility",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (e) {
                    var json = JSON.parse(e.d);
                    ShowHideColumnsInitial(json);
                    setCheckBoxes(json);
                },
                error: function (response) {
                    ErrorHandler(e,"Default.aspx/GetVisibility");
                }
            });

        };

        function updateColumnsVisibility (columnsPar) {
            $.ajax({
                type: "POST",
                url: "Default.aspx/UpdateColumnsVisibility",
                data: JSON.stringify({columns: columnsPar}),
                contentType: "application/json",
                dataType: "json",
                success: function(result) {
                    ShowHideColumnsInitial(columnsPar);
                    setCheckBoxes(columnsPar);
                },
                error: function(e) {
                    ErrorHandler(e,"Default.aspx/UpdateColumnsVisibility");
                }
            });
        }

        function updateChart() {
            var tiers = JSON.parse($("#jsonTier").val());
            var jsonModels = JSON.parse($('#<%=jsonModels.ClientID%>').val());
            var counts = new Array(tiers.length + 1);
            
            counts[0] = new Array("Tiers","Number of Phones");

            for(i=1; i<counts.length; i++) {                
                counts[i] = new Array("Tier " + (i), 0);
            }
            
            for(i=0; i<jsonModels.length; i++) {
                counts[(jsonModels[i].Tier)][1]++;
            }
            graphic.closeChart();
            graphic.setData(counts);
            graphic.createChart();
        }

        function removeFocusClass() {
            $('#matrix_tbody .ftable').removeClass('ftable');
        }

        function SearchModel(modelID) {
            closeTierDialog();
            var position = getModelPosition(modelID);
            var itemsPage = $('.pagesize').val();
            var pag = getPageNumber(position, itemsPage);
            $('.gotoPage').val(pag);
            $('.gotoPage').change();
        }

        function getPageNumber(pos, items) {
            var pag = parseInt(pos/items);
            var pagRes = pos%items;
            if(pagRes > 0)  pag++;
            return pag;
        }

        function closeTierDialog() {
            $('#dialog-tiers-tbody').html("<tr style='text-align: center'><td><label>Loading models...</label></td></tr></tbody>");
            $('#dialog-tiers .validateTips').empty();
            $('#dialog-tiers').dialog("close");
        }

        function getModelPosition(modelID) {
            var pos = 0;
            var mid;
            var id;
            $('#matrix_tbody').find('tr').each(function() {
                id = $(this).attr('id');
                mid = $(this).find('#td_model_id_' + id).val();
                pos++;
                if(modelID == mid) {
                    removeFocusClass();
                    $('#' + id).find('td').addClass('ftable');
                    return false;
                }
            });
            return pos;
        }
        
        function ShowTierModels(tierID){
            var jsonModels = JSON.parse($('#<%=jsonModels.ClientID%>').val());
            var tier = $(tierID).find('.tierID').text().trim();
            var lower = $(tierID).find('.tierLB').text().trim();
            var upper = $(tierID).find('.tierUB').text().trim();
            var tiers = "";
            var tiers_tbody = $("#dialog-tiers-tbody");
            tiers_tbody.empty();            

            for (var i = 0; i < jsonModels.length; i++) {
                if(tier == jsonModels[i].Tier){
                    tiers_tbody.append( 
                        $("<tr>")
                        .bind("click", { id: jsonModels[i].ModelID }, function(e) {  SearchModel(e.data.id); })
                        .append(
                            $("<td>")
                            .append(
                                $("<label>")
                                .html(jsonModels[i].ModelName)
                            )
                        )
                    );
                }
            }

            $('#dialog-tiers .validateTips').html('Tier ' + tier + ' => Lower Bound: ' + lower + ', Upper Bound: ' + upper);
            $('#dialog-tiers').dialog("open"); 
            $(".ui-widget-overlay").height( $(document).height());
            $('.ui-button.ui-widget.ui-state-default.ui-corner-all.ui-button-icon-only.ui-dialog-titlebar-close').hide();
        }

        function GetCurrentCarrier(){
                
            var selectedCurrent = 0;

            if ($(".ddlCarrier option").length > 0)
            {
                selectedCurrent = parseInt($(".ddlCarrier :selected").val()) <= 0 ? parseInt($(".ddlClientList :selected").val()) : parseInt($(".ddlCarrier :selected").val());

            }
            else
            {
                selectedCurrent = parseInt($(".ddlClientList :selected").val());
            }

            return selectedCurrent;
        }
        
        // Loading wingent
        (function ($) {

            $('#matrix_tbody tr').click(function() {
                removeFocusClass();
                $(this).find('td').addClass('ftable');
            });
            
            $('#tiersList tbody tr').click(function(){
                ShowTierModels(this);
            });

            $('#tiersList tbody tr').mouseover(function() {
                var tier = $(this).find(".tierID").text().trim();
                if(graphic != null) graphic.setSelect(tier-1);
            });

            $('#tiersList tbody tr').mouseout(function() {
                if(graphic != null) graphic.setSelect();
            });

            $.widget("artistan.loading", $.ui.dialog, {
                options: {
                    // your options
                    spinnerClassSuffix: 'spinner',
                    spinnerHtml: "<%= Resources.ModelMatrixManagement.LabelLoading %>",// allow for spans with callback for timeout...
                    maxHeight: false,
                    maxWidth: false,
                    minHeight: 80,
                    minWidth: 220,
                    height: 80,
                    width: 220,
                    modal: true

                },
                _create: function () {
                    $.ui.dialog.prototype._create.apply(this);
                    // constructor
                    $(this.uiDialog).children('*').hide();
                    var self = this,
                    options = self.options;
                    self.uiDialogSpinner = $('.ui-dialog-content', self.uiDialog).html(options.spinnerHtml).addClass('ui-dialog-' + options.spinnerClassSuffix);
                },
                _setOption: function (key, value) {
                    var original = value;
                    $.ui.dialog.prototype._setOption.apply(this, arguments);
                    // process the setting of options
                    var self = this;

                    switch (key) {
                        case "innerHeight":
                            // remove old class and add the new one.
                            self.uiDialogSpinner.height(value);
                            break;
                        case "spinnerClassSuffix":
                            // remove old class and add the new one.
                            self.uiDialogSpinner.removeClass('ui-dialog-' + original).addClass('ui-dialog-' + value);
                            break;
                        case "spinnerHtml":
                            // convert whatever was passed in to a string, for html() to not throw up
                            self.uiDialogSpinner.html("" + (value || '&#160;'));
                            break;
                    }
                },
                _size: function () {
                    $.ui.dialog.prototype._size.apply(this, arguments);
                },
                // other methods
                loadStart: function (newHtml) {
                    if (typeof (newHtml) != 'undefined') {
                        this._setOption('spinnerHtml', newHtml);
                    }
                    this.open();
                },
                loadStop: function () {
                    this._setOption('spinnerHtml', this.options.spinnerHtml);
                    this.close();
                }
            });
        })(jQuery);
        
        $(function () {
            if(<%=totalrecords%> > 0){
                // Table sorting settings
                MakeTableSorteable($('#myTable'));                
                $('#matrix_tbody').fadeIn('fast', function() {
                    $('#message_loading').remove();
                });               
                // get Matrix status
                LoadMatrixStatus();
                // create tooltips
                for (var i = 1; i <= <%=totalrecords%>; i++) {
                    ToolTipModels(i);
                }
            }

            $("#loading_dialog").loading();
            $("#loading_dialog").loading("loadStop");
            
            $.validity.setup({ outputMode:"label" });
            $('#lblMatrixStatus').hide();
            
            $('#' + '<%= ddl_clientList.ClientID %>').change(function () {
                $("#loading_dialog").loading();
                $(".ui-widget-overlay").height( $(document).height());
            });
            $('#' + '<%= ddl_carrier.ClientID %>').change(function (e) {
                e.preventDefault();
            });
            $('#' + '<%= ddl_programType.ClientID %>').change(function (e) {
                e.preventDefault();
            });
            $('#' + '<%= btn_LoadMatrix.ClientID %>').click(function (e) {
                $.validity.start();
                if($("#<%= ddl_carrier.ClientID %> > option").size()>1){
                    $("#<%= ddl_carrier.ClientID %>").greaterThan(0,"<%= Resources.ModelMatrixManagement.LabelErrorSelectValidCarrier %>");
                }
                if($("#<%= ddl_programType.ClientID %> > option").length>1){
                    $("#<%= ddl_programType.ClientID %>").greaterThan(0,"<%= Resources.ModelMatrixManagement.LabelErrorSelectValidProgramType %>");
                }
                var result = $.validity.end();
                if(result.valid) {
                    $("#loading_dialog").loading();
                    $(".ui-widget-overlay").height( $(document).height());
                }else{
                    e.preventDefault();
                }
            });
            // LOCK
            $('#' + '<%= btnLock.ClientID %>').click(function (e) {
                e.preventDefault();
                Lock();
            });
            // APPROVE
            $('#' + '<%= btnApprove.ClientID %>').click(function (e) {
                e.preventDefault();
                Approve();
            });
            // RESET
            $('#' + '<%= btnReset.ClientID %>').click(function (e) {
                e.preventDefault();
                Reset();
            });
            // SAVE CHANGES (UPDATE)
            $('#' + '<%= btnUpdate.ClientID %>').click(function (e) {
                e.preventDefault();
                Update();
            });
            // UDATE Action
            $('#' + '<%= btnUpdateAcction.ClientID %>').click(function (e) {
                e.preventDefault();
                Update();
            });
            // SEND BACK TO CARRIER
            $('#' + '<%= btnSendback.ClientID %>').click(function (e) {
                e.preventDefault();
                SendBackToCarrier();
            });
            // SUBMIT
            $('#' + '<%= btnSubmit.ClientID %>').click(function (e) {
                e.preventDefault();
                Save();
            });
            // PUSH PROD
            $('#' + '<%= btnPushprod.ClientID %>').click(function (e) {
                e.preventDefault();
                PushProd();
            });

            function checkDuplicates() {
                var isValid = true;
                $('#model_verticalmatrix_tbody').find('tr').each(function() {
                    var model = JSON.parse($(this).find('td').find("input").val()); 
                    var modelId = model.ModelID;
                    var statusId = $("#vertical_currentSelect" + $(this).attr("id")).val();
                    var duplicationCounter = 0;
                    $('#model_verticalmatrix_tbody').find('tr').each(function() {
                        var compareModel = JSON.parse($(this).find('td').find("input").val());
                        compareModel.StatusId = $("#vertical_currentSelect" + $(this).attr("id")).val();
                        if (compareModel.ModelID == modelId && compareModel.StatusId == statusId) {
                            duplicationCounter++;
                            if (duplicationCounter >= 2) {
                                isValid=false;
                            }
                            
                        }
                    });
                });
                return isValid;
            }

            // Find and Replace
            $('#' + '<%= btnFindAndReplace.ClientID%>').click(function(e) {
                e.preventDefault();
                //LoadDataForReplacementPopup was used for loading popup data and saving when matrix was not loaded
                //LoadDataForReplacementPopup();

                OpenReplacementDialog();
            });

            function OpenReplacementDialog() {
                isReplace = true;
                
                var buttonsOpt = {
                    "<%= Resources.ModelMatrixManagement.LabelBtnCancel %>": function() {
                        CloseDialog(this);
                    },
                    "<%= Resources.ModelMatrixManagement.LabelBtnSave %>": function() { 

                        var selectedReplaceModelId = parseInt($("#currentSelect_lblModelToReplace :selected").val());

                        //get checkbox selected modelIDs
                        var selectedModelIds = $(":checkbox:checked", "#tblAllModelsWithSelectedRep_tbody").map(function(index) {
                            var id = parseInt(this.id);
                            var statusId = parseInt(this.value);
                            return { ModelID : id, StatusId : statusId};
                        });

                        if(selectedReplaceModelId === 0){
                            alert("<%= Resources.ModelMatrixManagement.LabelSelectReplacementModel %>");
                            return false;
                        }

                        if(selectedModelIds.length === 0){
                            alert( "<%= Resources.ModelMatrixManagement.LabelSelectReplacementModelWith %>");
                            return false;
                        }
                                
                        //get all models
                        var masterModels = JSON.parse($('#<%=masterModels.ClientID%>').val());

                        var isUpdated = false;

                        var isReplace = $('input:radio[name="cbAction"]:checked').prop('id') === "cbReplaceWith";
                        if(isReplace){
                            var selectedReplaceWithModelId = parseInt($("#currentSelect_lblModelToReplaceWith :selected").val());

                            if(selectedReplaceWithModelId === 0){
                                alert("<%= Resources.ModelMatrixManagement.LabelSelectReplacementModel %>");
                                return false;
                            }

                            var modelToReplace;
                            var modelToReplaceWith;

                            //get combobox selected models
                            $.each(masterModels, function(index, value) {
                                if(selectedReplaceModelId === value.ModelID){
                                    modelToReplace = value;
                                    if(modelToReplaceWith != undefined)
                                        return false;
                                }
                                if(selectedReplaceWithModelId === value.ModelID){
                                    modelToReplaceWith = value;
                                    if(modelToReplace != undefined)
                                        return false;
                                }
                            });

                            //Replace replacement model
                            $.each(masterModels, function(index, value) {

                                var exist = $.grep(selectedModelIds, function( val, index) {
                                    return ( val.ModelID === value.ModelID );
                                });

                                if(exist.length > 0){
                                    $.each(value.Replacements, function(i, val) {
                                        if(val != undefined && val.ModelID === selectedReplaceModelId){
                                            $.each(exist, function(ind, ex) {
                                                if(val.StatusId === ex.StatusId){
                                                    val.ModelID = modelToReplaceWith.ModelID;
                                                    val.ModelName = modelToReplaceWith.ModelName;
                                                    val.NewCost = modelToReplaceWith.NewCost;
                                                    val.RetailPriceNew = modelToReplaceWith.RetailPriceNew;
                                                    val.Tier = modelToReplaceWith.Tier;
                                                    val.TierEx = modelToReplaceWith.TierEx;
                                                    val.TierLevel = modelToReplaceWith.TierLevel;
                                                    value.IsEdited = true;
                                                    isUpdated = true;
                                                    //Update cell color if matrix is loaded
                                                    if('<%= _ModelMatrix.LoadMatrix %>'.toLowerCase() === 'true'){
                                                        $('#matrix_tbody [value="' + value.ModelID + '"]').closest("td").attr("style", "background-color: #bde5f8 !important").addClass("unsavedChanges");
                                                    }
                                                    DisableButtons();
                                                }
                                            });
                                        }
                                    });
                                }
                            });
                        }
                        else
                        {
                            var modelToReplace;

                            //get combobox selected model
                            $.each(masterModels, function(index, value) {
                                if(selectedReplaceModelId === value.ModelID){
                                    modelToReplace = value;
                                    return false;
                                }
                            });

                            //Remove replacement model
                            var modelNamesExceptions = '';
                                
                            $.each(masterModels, function(index, value) {

                                var exist = $.grep(selectedModelIds, function( val, index) {
                                    return ( val.ModelID === value.ModelID );
                                });

                                if(exist.length > 0){
                                    var slicedPos = false;

                                    var replacementsCount = $.grep(value.Replacements, function( val, ind ) {
                                        return ( val.ModelID != null && val.ModelID != undefined );
                                    }).length;

                                    if(replacementsCount <= 1){
                                        modelNamesExceptions += "\n" + value.ModelName;
                                        return true;
                                    }

                                    if(value.Replacements != undefined){
                                        for( var i=0; i<value.Replacements.length; i++){
                                            if(value.Replacements[i] != undefined && value.Replacements[i].ModelID === selectedReplaceModelId){
                                                $.each(exist, function(ind, ex) {
                                                    if(value.Replacements[i].StatusId === ex.StatusId){
                                                        value.Replacements.splice(i, 1);
                                                        slicedPos = true;
                                                        value.IsEdited = true;
                                                        isUpdated = true;
                                                    }
                                                });
                                            }
                                        }

                                        //if we have throw out some element, then reset positions
                                        if(slicedPos){
                                            $.each(value.Replacements, function(i, val) {
                                                val.Priority = i + 1;
                                            });
                                        }
                                    }

                                    //Update cell color if matrix is loaded
                                    if('<%= _ModelMatrix.LoadMatrix %>'.toLowerCase() === 'true'){
                                        $('#matrix_tbody [value="' + value.ModelID + '"]').closest("td").attr("style", "background-color: #bde5f8 !important").addClass("unsavedChanges");
                                    }
                                    DisableButtons();
                                }
                            });

                            if(modelNamesExceptions.length > 1)
                                alert("<%= Resources.ModelMatrixManagement.LabelAlertRemoveException %>" + modelNamesExceptions);
                        }

                        if(isUpdated){
                            $("#info-div").fadeIn("fast");
                        }

                        $('#<%= masterModels.ClientID %>').val(JSON.stringify(masterModels));
                        CloseDialog(this);
                    }
                };

                <%= IsReadOnly ? String.Format("delete buttonsOpt['{0}'];", Resources.ModelMatrixManagement.LabelBtnSave ) : "" %>

                var opt = {
                    autoOpen: false,
                    modal: true,
                    width: 700,
                    height: 480,
                    closeOnEscape: true,
                    resizable: false,
                    dialogClass: 'modal-matrix',
                    buttons: buttonsOpt
                };

                

                $("#dialog-replacement").dialog(opt).dialog("open");
                $(".ui-widget-overlay").height($(document).height());
                $('.ui-button.ui-widget.ui-state-default.ui-corner-all.ui-button-icon-only.ui-dialog-titlebar-close').hide();

                createAutoComplete(document.getElementById('lblModelToReplace'), '435px', true);
                $("#currentSelect_lblModelToReplace").change(function() {
                    refreshAutoComplete(document.getElementById('lblModelToReplaceWith'), '435px');
                });
                
                createAutoComplete(document.getElementById('lblModelToReplaceWith'), '405px', false);
            }

            function LoadDataForReplacementPopup(){
                $("#loading_dialog").loading();
                $(".ui-widget-overlay").height( $(document).height());
                $.ajax({
                    type: "POST",
                    url: "Default.aspx/LoadDataForReplacementPopup",
                    data: JSON.stringify({carrier: GetCurrentCarrier(), selectedOrganizationId: $(".ddlClientList :selected").val(), selectedProgramType: $(".ddlProgramType :selected").val()}),
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function(result) {
                        var parsedJson = JSON.parse(result.d);
                        $('#<%=masterModels.ClientID%>').val(JSON.stringify(parsedJson.MasterModels));
                        $('#<%=jsonModels.ClientID%>').val(parsedJson.JsonModels);
                        IsVertical = parsedJson.IsVertical;
                        $('#inputConditions').val(parsedJson.Conditions);
                    },
                    error: function(e) {
                        ErrorHandler(e,"Default.aspx/LoadDataForReplacementPopup");
                    }
                }).done(function() {
                    $("#loading_dialog").loading("loadStop");
                    $("#acctions-buttons input:disabled").prop("disabled", false);
                    OpenReplacementDialog();
                });
            }

            function CloseDialog(sender){
                $("#tblAllModelsWithSelectedRep_tbody").html('<tr style="text-align: center;"><td colspan="3">Loading models...');
                $("#tblAllModelsWithSelectedRep").hide();
                $( sender ).dialog( "close" );
            }

            $('input:radio[name="cbAction"]').click(function(){
                if(this.id==="cbReplaceWith"){
                    $('#currentSelect_lblModelToReplaceWith').prop('disabled', false).trigger("chosen:updated");
                }
                else {
                    $('#currentSelect_lblModelToReplaceWith').prop('disabled', true).trigger("chosen:updated");
                }
            });

            $('#btn_Find').click(function() {
                var selectedModelId = parseInt($("#currentSelect_lblModelToReplace :selected").val());

                if(selectedModelId === 0){
                    alert("<%= Resources.ModelMatrixManagement.LabelSelectReplacementModel %>");
                    return false;
                }

                var modifiedModels = [];
                var masterModels = JSON.parse($('#<%=masterModels.ClientID%>').val());
                $.each(masterModels, function(index, value) {
                    $.each(value.Replacements, function(i, val) {
                        if (selectedModelId === val.ModelID){
                            val.ParentModelID = value.ModelID;
                            val.ParentModelName = value.ModelName;
                            modifiedModels.push(val);
                        }
                    });
                });

                $("#tblAllModelsWithSelectedRep").show();
                if($("#thCondition").length === 0 && IsVertical){
                    $('<th id="thCondition" class="th3">' + "<%= Resources.ModelMatrixManagement.LabelTblCondition %>" + '</th>').insertAfter("#appendVertical", "#tblAllModelsWithSelectedRep");
                }
                $("#tblAllModelsWithSelectedRep_tbody").html("");

                $.each(modifiedModels, function(i, val) {
                    $("#tblAllModelsWithSelectedRep_tbody").append('<tr><td><input type="checkbox" id="' + val.ParentModelID + '" value="' + val.StatusId + '"/><td style="text-align: left;">' + val.ParentModelName + '<td style="text-align: left;">' + val.ModelName + (IsVertical ? '<td>' + getConditionStatus(val) : '') + '<td>' + val.Priority)
                });

                //check-uncheck allModels checkbox
                $("#tblAllModelsWithSelectedRep_tbody :checkbox").click(function() {

                    //select unchecked checkboxes
                    if($(":checkbox:not(:checked)", "#tblAllModelsWithSelectedRep_tbody").length==0){
                        $('#chckAllModels').prop('checked', true);
                    }
                    else{
                        $('#chckAllModels').prop('checked', false);
                    }
                });

            });

            function getConditionStatus(value){
                if(value == undefined)
                    return '';

                var jsonconditions = JSON.parse($('#inputConditions').val());
                for (var i = 0; i < jsonconditions.length; i++) {
                    var json = jsonconditions[i];
                    if(json.Value == value.StatusId){
                        return json.Text;
                    }
                }

                return '';
            }

            //Check-uncheck all models in table
            $('#chckAllModels').click(function() {
                $(":checkbox", "#tblAllModelsWithSelectedRep_tbody").prop('checked', this.checked);
            });

            function createAutoComplete(labelId, autoCompleteWidth, alphabeticalSort) {
	            var selectedModel = 0;
	            //var newSelectedModel = 0;
	            //var newSelectedModeltxt = 0;
	            var label = $(labelId);
	            var exists = $('#' + "currentSelect_" + label.attr('id'));
	
	            if (exists.length) return false;

	            var td = label.parent();
	            var jsonModels = JSON.parse($('#<%=jsonModels.ClientID%>').val());
                
                var select = $("<select>").attr("id","currentSelect_"+ label.attr('id'));

	            //Sort Replacements
	            if (alphabeticalSort) {
		
		            //Sort Replacements alphabetically
		            jsonModels.sort(function(a, b) {
			            if (a.ModelName < b.ModelName) return -1;
			            if (a.ModelName > b.ModelName) return 1;
			            return 0;
		            });
	            } else {
		            var selectedModelId = parseInt($("#currentSelect_lblModelToReplace :selected").val());
		            var currentModelTier = 0;

		            for(var i=0; i<jsonModels.length; i++) {
			            if (jsonModels[i].ModelID == selectedModelId)
				            currentModelTier = jsonModels[i].Tier;
		            }

		            for(var i=0; i<jsonModels.length; i++) {
			            if (jsonModels[i].Tier == currentModelTier)
				            jsonModels[i].SortByTier = -1;
			            else
				            jsonModels[i].SortByTier = jsonModels[i].Tier;
		            }

		            //Sort Replacements
		            jsonModels.sort(function(a, b) {
			            var o1 = a.SortByTier;
			            var o2 = b.SortByTier;

			            var p1 = a.ModelName;
			            var p2 = b.ModelName;

			            if (o1 != o2) 
			            {
				            if (o1 < o2) return -1;
				            if (o1 > o2) return 1;
				            return 0;
			            }
			            if (p1 < p2) return -1;
			            if (p1 > p2) return 1;
			            return 0;
		            });
	            }

	            var option = $("<option>");
	            option.attr("value", 0);
	            select.append(option);

	            for(i=0;i<jsonModels.length;i++){
		            var model = jsonModels[i];
		            option = $("<option>");
		            option.attr("value",model.ModelID).html(model.ModelName + "<%= Resources.ModelMatrixManagement.LabelNRPText %>" + parseFloat(Math.round( model.RetailPriceNew * 100) / 100).toFixed(2) + "<%= Resources.ModelMatrixManagement.LabelNewCostText %>" + parseFloat(Math.round( model.NewCost * 100) / 100).toFixed(2) );

		            if(model.ModelID == selectedModel){
		                option.attr("selected",true);
		            }
		            select.append(option);
                }
                td.append(select);

                            //Use different plugin if IE7
                if(isIE7 == true)
                {
                    select.combobox({width: autoCompleteWidth});
                }
                else
                {
                    if(select.hasClass("chosenSelect") == false){
                        select.addClass("chosenSelect");
                    }
                    select.chosen({ width: autoCompleteWidth }); 
                    //Focus on plugin so we can use blur
                    $("#currentSelect_chosen .chosen-search input", select.parent()).focus();
                }
	
                select.focus();
                label.hide();
                return true;
            };

            var buttonsOpt = {
                "<%= Resources.ModelMatrixManagement.LabelBtnOk %>": function() {
                    if (checkDuplicates()) {
                        var rows = 0;
                        var row = $('#current_rowid_popup').val();
                        /*Save the data to the input*/ //$('#model_verticalmatrix_tbody tr')
                        var newVmodels = Array();
                        var isTierExModel = false;
                        var tierLevel = 0;
                        var tierLevelForMatrix = 0;

                        $("#primary_" + row).find("label").html("").removeClass("tier_exeption");
                        $("#primary_" + row).find("label").html("").removeClass("tier_exeption_lower");
                        $("#secondary_" + row).find("label").html("").removeClass("tier_exeption");
                        $("#secondary_" + row).find("label").html("").removeClass("tier_exeption_lower");
                        $("#tertiary_" + row).find("label").html("").removeClass("tier_exeption");
                        $("#tertiary_" + row).find("label").html("").removeClass("tier_exeption_lower");
                        $('#model_verticalmatrix_tbody').find('tr').each(function() {
                            if ($(this).find('td').find("input").val().length > 0) {

                                var model = JSON.parse($(this).find('td').find("input").val());

                                model.StatusId = $("#vertical_currentSelect" + $(this).attr("id")).val();
                                model.Priority = rows + 1;
                                    
                                switch (rows) {
                                    case 0:
                                        $("#primary_" + row).find("label").html(model.ModelName).removeClass("tier_exeption");
                                        $("#primary_" + row).find("label").html(model.ModelName).removeClass("tier_exeption_lower");
                                        $("#primary_" + row).find("input").val(JSON.stringify(model));
                                        var _newprice = parseFloat($('#input_retailprice_' + row).val());
                                        var _newcost = parseFloat(model.RetailPriceNew);
                                        model.TierEx = IsTierException(_newprice, _newcost);
                                        tierLevel = TierLevelException(_newprice, _newcost);
                                        if (model.TierEx) {
                                            if(tierLevel==1)
                                                $("#primary_" + row).find("label").addClass("tier_exeption");
                                            if(tierLevel==2)
                                                $("#primary_" + row).find("label").addClass("tier_exeption_lower");
                                            isTierExModel = true;
                                            model.TierLevel = tierLevel;
                                        }
                                        if (tierLevel == 2 && tierLevelForMatrix == 1 )
                                            tierLevelForMatrix = 1;
                                        if (tierLevel > 0 && tierLevelForMatrix != 1)
                                            tierLevelForMatrix = tierLevel;
                                        break;
                                    case 1:
                                        $("#secondary_" + row).find("label").html(model.ModelName).removeClass("tier_exeption");
                                        $("#secondary_" + row).find("label").html(model.ModelName).removeClass("tier_exeption_lower");
                                        $("#secondary_" + row).find("input").val(JSON.stringify(model));
                                        var _newprice = parseFloat($('#input_retailprice_' + row).val());
                                        var _newcost = parseFloat(model.RetailPriceNew);
                                        model.TierEx = IsTierException(_newprice, _newcost);
                                        tierLevel = TierLevelException(_newprice, _newcost);
                                        if (model.TierEx) {
                                            if(tierLevel==1)
                                                $("#secondary_" + row).find("label").addClass("tier_exeption");
                                            if(tierLevel==2)
                                                $("#secondary_" + row).find("label").addClass("tier_exeption_lower");
                                            isTierExModel = true;
                                            model.TierLevel = tierLevel;
                                        }
                                        if (tierLevel == 2 && tierLevelForMatrix == 1 )
                                            tierLevelForMatrix = 1;
                                        if (tierLevel > 0 && tierLevelForMatrix != 1)
                                            tierLevelForMatrix = tierLevel;
                                        break;
                                    case 2:
                                        $("#tertiary_" + row).find("label").html(model.ModelName).removeClass("tier_exeption");
                                        $("#tertiary_" + row).find("label").html(model.ModelName).removeClass("tier_exeption_lower");
                                        $("#tertiary_" + row).find("input").val(JSON.stringify(model));
                                        var _newprice = parseFloat($('#input_retailprice_' + row).val());
                                        var _newcost = parseFloat(model.RetailPriceNew);
                                        model.TierEx = IsTierException(_newprice, _newcost);
                                        tierLevel = TierLevelException(_newprice, _newcost);
                                        if (model.TierEx) {
                                            if(tierLevel==1)
                                                $("#tertiary_" + row).find("label").addClass("tier_exeption");
                                            if(tierLevel==2)
                                                $("#tertiary_" + row).find("label").addClass("tier_exeption_lower");
                                            isTierExModel = true;
                                            model.TierLevel = tierLevel;
                                        }
                                        if (tierLevel == 2 && tierLevelForMatrix == 1 )
                                            tierLevelForMatrix = 1;
                                        if (tierLevel > 0 && tierLevelForMatrix != 1)
                                            tierLevelForMatrix = tierLevel;
                                        break;
                                    default:
                                        var _newprice = parseFloat($('#input_retailprice_' + row).val());
                                        var _newcost = parseFloat(model.RetailPriceNew);
                                        model.TierEx = IsTierException(_newprice, _newcost);
                                        if (model.TierEx) {
                                            isTierExModel = true;
                                            model.TierLevel = TierLevelException(_newprice, _newcost);
                                            tierLevel = model.TierLevel;
                                            if (tierLevel == 2 && tierLevelForMatrix == 1 )
                                                tierLevelForMatrix = 1;
                                            if (tierLevel > 0 && tierLevelForMatrix != 1)
                                                tierLevelForMatrix = tierLevel;
                                        }
                                        break;
                                }
                                newVmodels.splice(rows, 0, model);
                                rows++;
                            }
                            //console.log(newVmodels);
                            //{"ModelID":null,"ModelName":null,"StatusNew":false,"StatusOrg":false,"StatusRef":false,"Status":null,"RetailPriceNew":0,"TierEx":true,"Tier":0,"Priority":0,"StatusId":0}
                        });

                        /** Join vmodel matrix to master model replacement list **/
                        var masterModels = JSON.parse($('#<%=masterModels.ClientID%>').val());
                        var masterModelID = $("#td_model_id_" + row).val();
                        for (var i = 0; i < masterModels.length; i++) {
                            if (masterModelID == masterModels[i].ModelID) {

                                UpdateModelCellColor(masterModels[i], newVmodels);

                                masterModels[i].Replacements = newVmodels;
                                masterModels[i].IsEdited = true;
                                $("#info-div").fadeIn("fast");
                            }
                        }
                        $('#<%=masterModels.ClientID%>').val(JSON.stringify(masterModels));
                        /** end **/

                        $("#input_vertical_models_" + row).val(JSON.stringify(newVmodels));
                        $("#td_model_id_" + row).parent("td").find('label').removeClass("tier_exeption");
                        $("#td_model_id_" + row).parent("td").find('label').removeClass("tier_exeption_lower");
                        if (isTierExModel) {
                            if(tierLevelForMatrix==1)
                                $("#td_model_id_" + row).parent("td").find('label').addClass("tier_exeption");
                            if(tierLevelForMatrix==2)
                                $("#td_model_id_" + row).parent("td").find('label').addClass("tier_exeption_lower");
                        }
                        // update tooltip
                        ToolTipModels(row);
                        /*clean up*/
                        $('#model_verticalmatrix_tbody').html("<tbody id='model_verticalmatrix_tbody'><tr style='text-align: center'><td colspan='4'><label>Loading models...</label></td></tr></tbody>");
                        $(this).dialog("close");
                        $('#current_rowid_popup').val('0');
                    } else {
                        alert("There are duplicated replacements with the same condition, please review and try again.");
                    }
                },
                "<%= Resources.ModelMatrixManagement.LabelBtnCancel %>": function() {
                    $('#model_verticalmatrix_tbody').html("<tbody id='model_verticalmatrix_tbody'><tr style='text-align: center'><td colspan='4'><label>Loading models...</label></td></tr></tbody>");
                    // MakeTableSorteable($('#myTable'));
                    $( this ).dialog( "close" );
                    $('#current_rowid_popup').val('0');
                }
            };
            <%= IsReadOnly ? String.Format("delete buttonsOpt['{0}'];", Resources.ModelMatrixManagement.LabelBtnOk ) : "" %>
            // Modal pop up settings
            $( "#dialog-form" ).dialog({
                autoOpen: false,
                height: 400,
                width: 600,
                modal: true,
                resizable: false,
                buttons: buttonsOpt
            });

            //Modal Tiers
            $( "#dialog-tiers" ).dialog({
                autoOpen: false,
                height: 400,
                width: 600,
                modal: true,
                resizable: false,
                buttons: {
                    Cancel: function() {
                        $('#dialog-tiers-tbody').html("<tr style='text-align: center'><td><label>Loading models...</label></td></tr></tbody>");
                        $('#dialog-tiers .validateTips').empty();
                        $( this ).dialog( "close" );
                    }
                }
            });

        });

        function refreshAutoComplete(labelId, autoCompleteWidth) {
	        console.log('entered refreshAutoComplete');
	        var selectedModel = 0;
	        var label = $(labelId);
	
	        var exists = $('#' + "currentSelect_" + label.attr('id'));
	
	        var jsonModels = JSON.parse($('#<%=jsonModels.ClientID%>').val());

	        var select = exists.prop("id", exists.id);

	        $('#' + "currentSelect_" + label.attr('id')).empty();

	        //Sort Replacements
	        var selectedModelId = parseInt($("#currentSelect_lblModelToReplace :selected").val());
	        var currentModelTier = 0;

	        for(var i=0; i<jsonModels.length; i++) {
		        if (jsonModels[i].ModelID === selectedModelId)
			        currentModelTier = jsonModels[i].Tier;
	        }

	        for(var i=0; i<jsonModels.length; i++) {
		        if (jsonModels[i].Tier === currentModelTier)
			        jsonModels[i].SortByTier = -1;
		        else
			        jsonModels[i].SortByTier = jsonModels[i].Tier;
	        }

	        jsonModels.sort(function(a, b) {
		        var o1 = a.SortByTier;
		        var o2 = b.SortByTier;

		        var p1 = a.ModelName;
		        var p2 = b.ModelName;

		        if (o1 != o2) 
		        {
			        if (o1 < o2) return -1;
			        if (o1 > o2) return 1;
			        return 0;
		        }
		        if (p1 < p2) return -1;
		        if (p1 > p2) return 1;
		        return 0;
	        });

	        var option = $("<option>");
	        option.attr("value", 0);
	        select.append(option);

	        for(i=0;i<jsonModels.length;i++){
		        var model = jsonModels[i];
		        option = $("<option>");
		        option.attr("value",model.ModelID).html(model.ModelName + "<%= Resources.ModelMatrixManagement.LabelNRPText %>" + parseFloat(Math.round( model.RetailPriceNew * 100) / 100).toFixed(2) + "<%= Resources.ModelMatrixManagement.LabelNewCostText %>" + parseFloat(Math.round( model.NewCost * 100) / 100).toFixed(2) );

		        if(model.ModelID == selectedModel){
		            option.attr("selected",true);
		        }
		        select.append(option);
            }

            //Use different plugin if IE7
            if(isIE7 == true)
            {
                select.combobox({width: autoCompleteWidth});
            }
            else
            {
                if(select.hasClass("chosenSelect") == false){
                    select.addClass("chosenSelect");
                }
                select.chosen({ width: autoCompleteWidth }); 
                //Focus on plugin so we can use blur
                $("#currentSelect_chosen .chosen-search input", select.parent()).focus();
            }
	
            $('#' + "currentSelect_" + label.attr('id')).trigger('chosen:updated');
		
            select.focus();
            label.hide();
            return true;
        }

        ///Set blueish colors for modified model
        function UpdateModelCellColor(masterModel, newModel){

            if(masterModel.Replacements != null && masterModel.Replacements != undefined) { 

                if(newModel.length > masterModel.Replacements.length && newModel[masterModel.Replacements.length].ModelID != null){
                    $('#matrix_tbody [value="' + masterModel.ModelID + '"]').closest("td").attr("style", "background-color: #bde5f8 !important").addClass("unsavedChanges");
                    DisableButtons();
                    return true;
                }

                for(var j = 0; j<masterModel.Replacements.length; j++)
                {
                    var oldRepModel = masterModel.Replacements[j];

                    if(oldRepModel.ModelID != null && (newModel[j] === null || newModel[j] === undefined))
                    {
                        $('#matrix_tbody [value="' + masterModel.ModelID + '"]').closest("td").attr("style", "background-color: #bde5f8 !important").addClass("unsavedChanges");
                        DisableButtons();
                        break;
                    }

                    if(newModel[j] != undefined && (newModel[j].ModelID != oldRepModel.ModelID || (IsVertical && newModel[j].StatusId != oldRepModel.StatusId)))
                    {
                        $('#matrix_tbody [value="' + masterModel.ModelID + '"]').closest("td").attr("style", "background-color: #bde5f8 !important").addClass("unsavedChanges");
                        DisableButtons();
                        break;
                    }
                }
                                        
            }
            else
            {
                if(newModel.length > 0)
                    $('#matrix_tbody [value="' + masterModel.ModelID + '"]').closest("td").attr("style", "background-color: #bde5f8 !important").addClass("unsavedChanges");
            }

        }

        function toogle(selector){
            $("#" + selector).fadeToggle("fast");
        }

        // create tooltip on selector label
        function ToolTipModels(id) { 
            var label = $("#lbl_"+id);            
            var rowId = label.parent('td').parent('tr').attr('id');             
            var repText = "";
            var masterModels = JSON.parse($('#<%=masterModels.ClientID%>').val());
            var replacements = Array();
            var mmodelId = $("#td_model_id_"+rowId).val();
            for (var b = 0; b < masterModels.length; b++) {
                if(mmodelId == masterModels[b].ModelID){
                    replacements = masterModels[b].Replacements;
                    break;
                }
            }

            var ul = $("<ul>");
            for (var i = 0; i < replacements.length; i++) {
                
                if(replacements[i].ModelName == null )
                    continue;


                var condition = '';
                if (replacements[i].StatusId == 172)
                    condition = ' - ' + "<%= Resources.ModelMatrixManagement.LabelConditionNew %>";
                else if(replacements[i].StatusId == 171)
                    condition = ' - ' + "<%= Resources.ModelMatrixManagement.LabelConditionNonNew %>";
                
                ul.append($("<li>").text(replacements[i].ModelName + condition).addClass((replacements[i].TierEx ? "tier-ex":"")));
            }
            
            label.tooltipster({content:ul,theme: "tooltipster-punk"});
            label.tooltipster('content',ul);
        }

        function GetModifiedData(updateYellow) {
            
            var modified = Array();
            var $masterModel = $('#<%=masterModels.ClientID%>');
            if ($masterModel.val()) {
                var masterModels = JSON.parse($masterModel.val());
                for (var i = 0; i < masterModels.length; i++) {
                    var tr = $('input[value="' + masterModels[i].ModelID + '"]').closest('tr');
                    if (masterModels[i].IsEdited && updateYellow === undefined || (updateYellow && $(".unsavedChanges", tr).length > 0)) {
                        if (!$("#chckNewCostAutoCalc").prop('checked')) {
                            var autoCalcFields = tr.val();
                            if (autoCalcFields) {

                                var modifiedModel = JSON.parse(autoCalcFields);

                                masterModels[i].RetailPriceNew = modifiedModel.RetailPriceNew;
                                masterModels[i].RefurbCost = modifiedModel.RefurbCost;
                                masterModels[i].RetailPriceNonNew = modifiedModel.RetailPriceNonNew;
                                masterModels[i].CostRatio = modifiedModel.CostRatio;
                            }
                        }

                        modified.splice(1, 0, masterModels[i]);
                    }
                }
            }

            //console.log(JSON.stringify(modified));
            return modified;
        }

        // Update Action
        function Update() {
            <%= IsReadOnly ? "return;" : String.Empty %>
            var masterModels = GetModifiedData(true);
            $("#loading_dialog").loading("loadStart","<%= Resources.ModelMatrixManagement.LabelUpdating %> " + masterModels.length + " <%= Resources.HandsetManagement.LabelTitleModels %>");
            $(".ui-widget-overlay").height( $(document).height());
            //$(window).unbind('beforeunload');
            $.ajax({
                type: "POST",
                url: "Default.aspx/UpdateMatrix",
                data: JSON.stringify({"mmodels":masterModels}),
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                timeout: 20000,
                success: function (e) {
                    if ($('#' + '<%= hdUpdateFlag.ClientID %>').val() == "1") {
                        $("#loading_dialog").loading("loadStop");
                        __doPostBack();
                        return;
                    }
                    SuccessHandler(e);
                    var json = JSON.parse(e.d);
                    if(!json.Error){
                        $('#' + '<%= btn_LoadMatrix.ClientID %>').click();
                    }
                },
                error: function (e) {
                    ErrorHandler(e,"Default.aspx/UpdateMatrix");
                    //ApplyBeforeunload();
                },
                timeout: function (e) {
                    TimeOutHandler(e, "Default.aspx/UpdateMatrix");
                    //ApplyBeforeunload();
                    console.log("Server time out.");
                }
            });
        }

        // Approve Action
        function Approve() {
            var masterModels = GetModifiedData();
            $("#loading_dialog").loading("loadStart","<%= Resources.ModelMatrixManagement.LabelUpdating %>");
            $(".ui-widget-overlay").height( $(document).height());
            //$(window).unbind('beforeunload');
            $.ajax({
                type: "POST",
                url: "Default.aspx/ApproveMatrix",
                data: "{}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                timeout: 20000,
                success: function (e) {
                    SuccessHandler(e);
                    var json = JSON.parse(e.d);
                    if(!json.Error){
                        $('#' + '<%= btn_LoadMatrix.ClientID %>').click();
                    }
                },
                error: function (e) {
                    ErrorHandler(e,"Default.aspx/ApproveMatrix");
                    //ApplyBeforeunload();
                },
                timeout: function (e) {
                    TimeOutHandler(e,"Default.aspx/ApproveMatrix");
                    //ApplyBeforeunload();
                    console.log("Server time out.");
                }
            });
        }

        // Save Action
        function Save() {
            //GetModifiedData();
            var masterModels = GetModifiedData();
            ///$(window).unbind('beforeunload');
            $.ajax({
                type: "POST",
                url: "Default.aspx/SaveMatrix",
                data: JSON.stringify({"mmodels":masterModels}),
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                timeout: 20000,
                success: function (e) {
                    SuccessHandler(e);
                    var json = JSON.parse(e.d);
                    if(!json.Error){
                        $('#' + '<%= btn_LoadMatrix.ClientID %>').click();
                }
                },
                error: function (e) {
                    ErrorHandler(e, "Default.aspx/SaveMatrix");
                    //ApplyBeforeunload();
                },
                timeout: function (e) {
                    TimeOutHandler(e, "Default.aspx/SaveMatrix");
                    //ApplyBeforeunload();
                    console.log("Server time out.");
                }
            });
    }

    // Push to Prod Action
    function PushProd() {
        var masterModels = GetModifiedData();
        $("#loading_dialog").loading("loadStart","<%= Resources.ModelMatrixManagement.LabelUpdating %>");
        $(".ui-widget-overlay").height( $(document).height());
        //$(window).unbind('beforeunload');
        $.ajax({
            type: "POST",
            url: "Default.aspx/PushToProductionMatrix",
            data: "{}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            timeout: 20000,
            success: function (e) {
                SuccessHandler(e);
                var json = JSON.parse(e.d);
                if(!json.Error){
                    $('#' + '<%= btn_LoadMatrix.ClientID %>').click();
                }
            },
            error: function (e) {
                ErrorHandler(e,"Default.aspx/PushToProductionMatrix");
                //ApplyBeforeunload();
            },
            timeout: function (e) {
                TimeOutHandler(e,"Default.aspx/PushToProductionMatrix");
                //ApplyBeforeunload();
                console.log("Server time out.");
            }
        });
    }

    // Send Back To Carrier Action
    function SendBackToCarrier() {
        var masterModels = GetModifiedData();
        $("#loading_dialog").loading("loadStart","<%= Resources.ModelMatrixManagement.LabelUpdating %>");
            $(".ui-widget-overlay").height( $(document).height());
            //$(window).unbind('beforeunload');
            $.ajax({
                type: "POST",
                url: "Default.aspx/SendBackToCarrierMatrix",
                data: "{}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                timeout: 20000,
                success: function (e) {
                    SuccessHandler(e);
                    var json = JSON.parse(e.d);
                    if(!json.Error){
                        $('#' + '<%= btn_LoadMatrix.ClientID %>').click();
                    }
                },
                error: function (e) {
                    ErrorHandler(e,"Default.aspx/SendBackToCarrierMatrix");
                    //ApplyBeforeunload();
                },
                timeout: function (e) {
                    TimeOutHandler(e,"Default.aspx/SendBackToCarrierMatrix");
                    //ApplyBeforeunload();
                    console.log("Server time out.");
                }
            });
        }

        // Reset Action
        function Reset() {
            var masterModels = GetModifiedData();
            $("#loading_dialog").loading("loadStart","<%= Resources.ModelMatrixManagement.LabelUpdating %>");
            $(".ui-widget-overlay").height( $(document).height());
            //$(window).unbind('beforeunload');
            $.ajax({
                type: "POST",
                url: "Default.aspx/ResetMatrix",
                data: "{}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                timeout: 20000,
                success: function (e) {
                    SuccessHandler(e);
                    var json = JSON.parse(e.d);
                    if(!json.Error){
                        $('#' + '<%= btn_LoadMatrix.ClientID %>').click();
                    }
                },
                error: function (e) {
                    ErrorHandler(e,"Default.aspx/ResetMatrix");
                    //ApplyBeforeunload();
                },
                timeout: function (e) {
                    TimeOutHandler(e,"Default.aspx/ResetMatrix");
                    //ApplyBeforeunload();
                    console.log("Server time out.");
                }
            });
        }

        // Lock Action
        function Lock() {
            var masterModels = GetModifiedData();
            $("#loading_dialog").loading("loadStart","<%= Resources.ModelMatrixManagement.LabelUpdating %>");
            $(".ui-widget-overlay").height( $(document).height());

            $.ajax({
                type: "POST",
                url: "Default.aspx/LockMatrix",
                data: "{}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (e) {
                    SuccessHandler(e);
                    LoadMatrixStatus();
                },
                error: function (e) {
                    ErrorHandler(e,"Default.aspx/LockMatrix");
                }
            });
        }
        
        //
        function SuccessHandler(resp){
            $("#loading_dialog").loading("loadStop");
            var json = JSON.parse(resp.d);
            if(json.Error){alert("<%= Resources.ModelMatrixManagement.ErrorAlertTryLater %> " +json.Message); return;}
            alert(json.Message);
        }

        //
        function ErrorHandler(resp, method){
            console.log(resp);
            $("#loading_dialog").loading("loadStop");
            var json  = "";
            try {
                json = JSON.parse(resp);
            } catch(err) {
                console.log(err)
                json = eval(resp);
            }
            if(json.status!=200){
                alert("<%= Resources.ModelMatrixManagement.ErrorAlertTryLater %> " + json.status + "\nModule:"+ method);    
            } else {
                alert("<%= Resources.ModelMatrixManagement.ErrorAlertTryLater %> " + json.Message + "\nModule:"+ method);    
            }
            console.log(json);
        }

        function TimeOutHandler(resp, method){
            console.log(resp);

            $("#loading_dialog").loading("loadStop");
            var json  = "";
            try {
                json = JSON.parse(resp);
            } catch(err) {
                json = resp;
            }
            alert("<%= Resources.ModelMatrixManagement.ErrorTimeOutAlertTryLater %> " + method + ".\n"+json.Message);
            console.log(json);
        }
        // Update Master Model
        function UpdateMasterModel(model){
            if(model == undefined){return;}
            if(model.ModelID.length == 0){return;}

            var masterModels = JSON.parse($('#<%=masterModels.ClientID%>').val());
            var replacements = Array();

            for (var i = 0; i < masterModels.length; i++) {
                if(model.ModelID == masterModels[i].ModelID){
                    replacements = masterModels[i].Replacements;
                    masterModels[i] = model;
                    masterModels[i].IsEdited = true;
                    $("#info-div").fadeIn("fast");
                    //console.log("Master Model updated!! [UpdateMasterModel]");
                }
            }
            $('#<%=masterModels.ClientID%>').val(JSON.stringify(masterModels));
        }
        
        // Update Replacements for Master Model
        function UpdateReplacement(rowId,iid,model){
            if(model == undefined){model = JSON.parse('{"ModelID":null,"ModelName":null,"StatusNew":false,"StatusOrg":false,"StatusRef":false,"Status":null,"RetailPriceNew":0,"TierEx":true,"Tier":0,"Priority":0,"StatusId":0}');}
            var mastermodelID = $("#td_model_id_"+rowId).val();
            var masterModels = JSON.parse($('#<%=masterModels.ClientID%>').val());
            var replacements = Array();
            var priority = 0;
            if(iid.indexOf("primary_") != -1){
                priority = 0;    
            }
            if(iid.indexOf("secondary_") != -1){
                priority = 1;    
            }
            if(iid.indexOf("tertiary_") != -1){
                priority = 2;    
            }
            model.Priority = priority;
            for (var i = 0; i < masterModels.length; i++) {
                if(mastermodelID == masterModels[i].ModelID){
                    model.Priority = priority + 1;
                    masterModels[i].Replacements[priority] = model;
                    masterModels[i].IsEdited = true;
                    $("#info-div").fadeIn("fast");
                }
            }
            $('#<%=masterModels.ClientID%>').val(JSON.stringify(masterModels));
        }

        // Update costs for Master Model
        function UpdateMasterModelCosts(Id) {

            //console.log("Updating Master model");
            var mastermodelID = $("#td_model_id_"+Id).val();
            var masterModels = JSON.parse($('#<%=masterModels.ClientID%>').val());
            //console.log(JSON.stringify(masterModels));
            for (var i = 0; i < masterModels.length; i++) {
                //console.log(mastermodelID + " == " + masterModels[i].ModelID + " ? ");
                //console.log("==?> " + (mastermodelID == masterModels[i].ModelID));
                if(mastermodelID == masterModels[i].ModelID){
                    //console.log("-----> " + JSON.stringify(masterModels[i]))
                    masterModels[i].NewCost = parseFloat(Math.round( parseFloat( $("#input_newCost_" + Id).val()) * 100) / 100).toFixed(2);
                    masterModels[i].RetailPriceNew = parseFloat(Math.round( parseFloat( $("#input_retailprice_" + Id).val()) * 100) / 100).toFixed(2);
                    masterModels[i].RefurbCost = parseFloat(Math.round( parseFloat( $("#input_refurbcost_" + Id).val()) * 100) / 100).toFixed(2);
                    masterModels[i].RetailPriceNonNew = parseFloat(Math.round( parseFloat( $("#input_retailpricenonnew_" + Id).val()) * 100) / 100).toFixed(2);
                    masterModels[i].CostRatio = $("#td_costratio_" + Id).text().replace("%","");
                    masterModels[i].IsEdited = true;
                    $("#info-div").fadeIn("fast");
                    ///console.log("Master Model Updated!");
                }
                // Update replacements
                //console.log("Updating replacements");
                for (var a = 0; a < masterModels[i].Replacements.length; a++) {
                    if(mastermodelID == masterModels[i].Replacements[a].ModelID){
                        masterModels[i].Replacements[a].RetailPriceNew = parseFloat(Math.round( parseFloat( $("#input_retailprice_" + Id).val()) * 100) / 100).toFixed(2);
                        masterModels[i].Replacements[a].NewCost = parseFloat(Math.round( parseFloat( $("#input_newCost_" + Id).val()) * 100) / 100).toFixed(2);
                        //masterModels[i].IsEdited = true;
                        $("#info-div").fadeIn("fast");
                        //console.log("Replacement Updated");
                    }
                }
                // update Tier Ex Rep
                for (var a = 0; a < masterModels[i].Replacements.length; a++) {
                    //console.log(JSON.stringify(masterModels[i].Replacements[a]));
                    var _newcost = parseFloat(masterModels[i].Replacements[a].RetailPriceNew);
                    var _newprice = parseFloat(masterModels[i].RetailPriceNew);
                    //console.log("UpdateMasterModelCosts");
                    masterModels[i].Replacements[a].TierEx  = IsTierException(_newprice,_newcost);
                    masterModels[i].Replacements[a].TierLevel = TierLevelException(_newprice,_newcost);
                    //masterModels[i].IsEdited = true;
                }
                var isTierEx = false;
                // update Tier Ex Master
                for (var a = 0; a < masterModels[i].Replacements.length; a++) {
                    if(!isTierEx)
                        isTierEx = masterModels[i].Replacements[a].TierEx;
                }

                $("#"+Id).first('td').first('label').removeClass('tier_exeption');
       
                if(isTierEx)
                    $("#"+Id).first('td').first('label').addClass('tier_exeption');
                masterModels[i].TierEx = isTierEx;
                //console.log(JSON.stringify(masterModels[i]));
            }
            

            // Tier
            var replacements  = Array();
            for (var b = 0; b < masterModels.length; b++) {
                if(mastermodelID == masterModels[b].ModelID){
                    replacements = masterModels[b].Replacements;
                    $("#td_model_id_"+Id).parent("td").find('label').removeClass("tier_exeption");
                    if(masterModels[b].TierEx)
                    {
                        $("#td_model_id_"+Id).parent("td").find('label').addClass("tier_exeption");
                    }
                }
            }
           
            for (var a = 0; a < replacements.length; a++) {
                var model = replacements[a];
                if(model.ModelID != undefined){
                    switch (model.Priority) {
                        case 1:
                            $("#input_primary_current_"+Id).val(JSON.stringify(model));
                            $("#primary_"+Id).find('label').removeClass('tier_exeption');
                            if(model.TierEx){
                                $("#primary_"+Id).find('label').addClass('tier_exeption');
                            }
                            break;
                        case 2:
                            $("#input_secondary_current_"+Id).val(JSON.stringify(model));
                            $("#secondary_"+Id).find('label').removeClass('tier_exeption');
                            if(model.TierEx){
                                $("#secondary_"+Id).find('label').addClass('tier_exeption');
                            }
                            break;
                        case 3:
                            $("#input_tertiary_current_"+Id).val(JSON.stringify(model));
                            $("#tertiary_"+Id).find('label').removeClass('tier_exeption');
                            if(model.TierEx){
                                $("#tertiary_"+Id).find('label').addClass('tier_exeption');
                            }
                            break;
                    }
                }
            }
           
            $('#<%=masterModels.ClientID%>').val(JSON.stringify(masterModels));
            //console.log(JSON.stringify(masterModels));
            UpdateModelCosts(Id);
        }
        
        // Update replacement costs
        function UpdateModelCosts(Id){
            var mastermodelID = $("#td_model_id_"+Id).val();
            var jsonModels = JSON.parse($('#<%=jsonModels.ClientID%>').val());

            for (var i = 0; i < jsonModels.length; i++) {
                if(mastermodelID == jsonModels[i].ModelID){
                    jsonModels[i].NewCost =parseFloat(Math.round( parseFloat( $("#input_newCost_" + Id).val()) * 100) / 100).toFixed(2);
                    jsonModels[i].RetailPriceNew = parseFloat(Math.round( parseFloat( $("#input_retailprice_" + Id).val()) * 100) / 100).toFixed(2);//parseFloat( $("#input_newCost_" + Id).val());
                    jsonModels[i].Tier = GetTierBasedOnCost(jsonModels[i].RetailPriceNew);
                    //jsonModels[i].RetailPriceNew = parseFloat( $("#input_retailprice_" + Id).val());
                    break;
                }
            }
            $('#<%=jsonModels.ClientID%>').val(JSON.stringify(jsonModels));
            updateChart();
        }

        function formatCurrency (val){
            var retVal = '';
            var pattern = '<%=currencyPattern%>';
            switch(parseInt(pattern)){
                case 0: //$n
                    retVal = '<%=currencySymbol%>' + val;
                    break;
                case 1: //n$
                    retVal = val + '<%=currencySymbol%>';
                    break;
                case 2: //$ n
                    retVal = '<%=currencySymbol%> ' + val;
                    break;
                case 3: //n $
                    retVal = val + ' <%=currencySymbol%>';
                    break;
            }
            return retVal;
        }
        
        // Gets the new recalculated costs based on the new cost value
        function GetNewCosts(newcost, tdId)
        {
            if (tdId != undefined)
            {
                if ($("#chckNewCostAutoCalc").prop('checked'))
                {
                    $.ajax(
                    {
                        type:           "POST",
                        url:            "Default.aspx/RecalculateCosts",
                        data:           JSON.stringify({"newCost":newcost}),
                        contentType:    "application/json; charset=utf-8",
                        dataType:       "json",

                        success:        function (msg)
                        {
                            var json = JSON.parse(msg.d);
                            $("#input_retailprice_"+tdId).val(json.RetailPriceNew).parent('td').find('label').html(formatCurrency(parseFloat(Math.round(json.RetailPriceNew * 100) / 100).toFixed(2)));
                            $("#input_refurbcost_"+tdId).val(json.RefurbCost).parent('td').find('label').html(formatCurrency(parseFloat(Math.round(json.RefurbCost * 100) / 100).toFixed(2)));
                            $("#input_retailpricenonnew_"+tdId).val(json.RetailPriceNonNew).parent('td').find('label').html(formatCurrency(parseFloat(Math.round(json.RetailPriceNonNew * 100) / 100).toFixed(2)));
                            $('#td_costratio_'+tdId).html(parseInt(json.CostRatio) + '%');

                            if (json.CostRatioEx)
                            {
                                $('#'+tdId).addClass('errortd');
                            }
                            else
                            {
                                $('#'+tdId).removeClass('errortd');
                            }
                            UpdateMasterModelCosts(tdId);
                        },

                        error:          function (e)
                        {
                            alert("<%= Resources.ModelMatrixManagement.ErrorAlertNewCostTryLater %>");
                        }
                    });
                }
            }
            else
            {
                alert("<%= Resources.ModelMatrixManagement.ErrorAlertNewCostTryLater %>");
            }
        }

            // Gets the Matrix status
            function LoadMatrixStatus() {
                $.ajax({
                    type: "POST",
                    url: "Default.aspx/LoadMatrixStatus",
                    data: "{}",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (msg) {
                        //alert(msg.d);
                        $('#lblMatrixStatus').show();
                        $('#lblMatrixStatusTitle').text(msg.d + " ");
                    },
                    error: function (msg) {
                        ErrorHandler(msg , "Default.aspx/LoadMatrixStatus");
                        console.log("An unknown error occured trying\nto load the matrix status.\nPlease ty again later.");
                    }
                });
            }
            
            // Changes the view from label to select
            //THIS METHOD IS OBSOLETE (Task 6013), use changeToSelectVertical
            function changeToSelect(label){
                var selectedModel = 0;
                var newSelectedModel = 0;
                var newSelectedModeltxt = 0;

                var label = $(label);
                var myDiv = label.parent('div');
                var input = myDiv.find('input');
                var rowId = myDiv.parent('td').parent('tr').attr('id'); 

                var jsonModels = JSON.parse($('#<%=jsonModels.ClientID%>').val());
                var select = $('<select>').attr('id','currentSelect');

                select.focusout(function () {
                    newSelectedModel = $(this).val();
                    newSelectedModeltxt = $(this).find('option:selected').text();
                
                    label.html(newSelectedModeltxt);
                
                    if(newSelectedModel==0){
                        label.removeClass('tier_exeption');
                        input.val('{"ModelID":null,"ModelName":null,"StatusNew":false,"StatusOrg":false,"StatusRef":false,"Status":null,"RetailPriceNew":0,"TierEx":true,"Tier":0,"Priority":0,"StatusId":0}');
                        UpdateReplacement(rowId,input.attr('id'),JSON.parse(input.val()));
                    }else{
                        for(i=0;i<jsonModels.length;i++){
                            var model = jsonModels[i];
                            if(model.ModelID == newSelectedModel){
                            
                                // check for tier exception
                                var _newcost = parseFloat(model.RetailPriceNew);//
                                var _newprice = parseFloat(Math.round( parseFloat( $("#input_retailprice_" + rowId).val()) * 100) / 100).toFixed(2);
                                model.TierEx  = IsTierException(_newprice,_newcost);
                                model.TierLevel = TierLevelException(_newprice,_newcost);
                                //console.log("Select.FocusOut: " + model.TierEx);
                                if(model.TierEx){
                                    if(model.TierEx > 1) 
                                        label.addClass('tier_exeption');
                                    else
                                        label.addClass('tier_exeption');
                                }else{
                                    label.removeClass('tier_exeption');
                                }
                                input.val(JSON.stringify(model));
                                UpdateReplacement(rowId,input.attr('id'),model);
                            }
                        }
                    }
                    label.show();
                    $(this).remove();
                });

                selectedModel = JSON.parse(input.val()).ModelID;
                if(selectedModel == undefined){selectedModel = 0;}
                
                var option = $('<option>');
                option.attr('value',0).html('&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;');
                select.append(option);

                for(i=0;i<jsonModels.length;i++){
                    var model = jsonModels[i];
                    option = $('<option>');
                    option.attr('value',model.ModelID).html(model.ModelName);
                    if(model.ModelID == selectedModel){
                        option.attr('selected',true);
                    }
                    select.append(option);
                }
                myDiv.append(select);

                select.focus();
                label.hide();
            }

        // Opens the modal dialog to edit models
        function OpenModal(input){
            var opt = {
                autoOpen: false,
                modal: true,
                width: isIE7 ? 720 : 710,
                height: 400,
                title: 'Details',
                dialogClass: 'modal-matrix'
            };

            //Check is vertical
            var isVertical = false;
            <% if (GetIsVerticalCMMR())
            {%>
            isVertical = true;    
            <% } %>

            var label = $(input);
            //console.log(label);
            //console.log($(this));
            var mytr = label.parent().parent();
            var modelIdInput = $('#td_model_id_' + mytr.attr('id'));
            var modelId = modelIdInput.val();    
            var tbody = $("#model_verticalmatrix_tbody");
            var jsons = Array();
            var currentModelTier;
            $('#current_rowid_popup').val(mytr.attr('id'));
            var masterModels = JSON.parse($('#<%=masterModels.ClientID%>').val());
            
            for (var i = 0; i < masterModels.length; i++) {
                if(modelId == masterModels[i].ModelID){
                    jsons = masterModels[i].Replacements;
                    currentModelTier = masterModels[i].Tier;
                }
            }
            
            var arrylength = 0;

            if(!isVertical && jsons.length >= 3)
            {
                arrylength = 3;
            }
            else
            {
                arrylength = jsons.length;
            }
            
            tbody.html('');
            for (var a = 0; a < arrylength; a++) {
                var randomId = Math.floor((Math.random()*1000)+1); 

                if(!isVertical && jsons[a].ModelName == null)
                    continue;
                var tierLevel = TierLevelException(parseFloat($("#input_retailprice_" + mytr.attr('id')).val()), jsons[a].RetailPriceNew);
                var tierLevelClass = "tier_exeption";
                if (tierLevel == 2)
                    tierLevelClass = "tier_exeption_lower";

                tbody.append(
                    $("<tr>").attr({"id":"_"+(randomId+"_")})
                    .append($("<td>").append( $("<input >").attr({"id":(randomId+"_"), "style":"display:none", "value":JSON.stringify(jsons[a])})).append($('<label>').prop('class', 'labelPopUp-align').append(jsons[a].Priority)).append('<a class="up">&#8593;</a><a class="down">&#8595;</a>'))//jsons[a].Priority
                    .append($("<td>").append( $('<label>').bind('click',{json:randomId},function(e){changeToSelectVertical(this, mytr.attr("id"), e.data.json, currentModelTier);}).addClass((jsons[a].TierEx ? (tierLevelClass): "")).html(jsons[a].ModelName + "<%= Resources.ModelMatrixManagement.LabelNRPText %>" + parseFloat(Math.round( jsons[a].RetailPriceNew * 100) / 100).toFixed(2) + "<%= Resources.ModelMatrixManagement.LabelNewCostText %>" + parseFloat(Math.round( jsons[a].NewCost * 100) / 100).toFixed(2))))
                    .append((isVertical) ? $("<td>").addClass("center_all").append(selectConditions(jsons[a].StatusId, randomId)) : '')
                    .append((<%= (!IsReadOnly).ToString().ToLower() %>) ? $("<td>").addClass("center_all").append($("<label>").addClass("label_pointer").bind("click",{id:randomId},function(e)
                    {
                        removeRow(e.data.id);
                    }).html('X')) : '')
                    );
            }

            $("#dialog-form").dialog(opt).dialog("open");
            $(".ui-widget-overlay").height($(document).height());
            $('.ui-button.ui-widget.ui-state-default.ui-corner-all.ui-button-icon-only.ui-dialog-titlebar-close').hide();

            initialHeight = $("#dialog-form").height();

            var currentTrLength = $("tr", tbody).length;

            if(!$("#dialog-form").hasClass("ui-dialog-content-NoScroll"))
                $("#dialog-form").addClass("ui-dialog-content-NoScroll");

            if(currentTrLength < 12 && currentTrLength > 7)
            {
                $("#dialog-form").height($("#dialog-form").height() + (currentTrLength - 7)* $("tr", tbody).height());
            }
            else if(currentTrLength >= 12)
            {
                $("#dialog-form").height(initialHeight);
                $("#dialog-form").removeClass("ui-dialog-content-NoScroll");
            }

            var retailPrice = parseFloat($("#input_retailprice_" + mytr.attr('id')).val());
            var newCost = parseFloat($("#input_newCost_" + mytr.attr('id')).val());
            $("#ui-id-2").text(label.text() + "<%= Resources.ModelMatrixManagement.LabelNRPText %>" + parseFloat(Math.round( retailPrice * 100) / 100).toFixed(2) + "<%= Resources.ModelMatrixManagement.LabelNewCostText %>" + parseFloat(Math.round( newCost * 100) / 100).toFixed(2));
            
            if(<%= (!IsReadOnly).ToString().ToLower() %> && (isVertical || (!isVertical && tbody[0].childNodes.length < 3))){
                $("#btn_add").show();
            }else{
                $("#btn_add").hide();
            }

            UpDownTrigger();
        }

        //Move items up or down in pop up
        function UpDownTrigger(){
            $(".up,.down").click(function(){
                var row = $(this).parents("tr:first");
                var currentIndex = parseInt($(".labelPopUp-align", row).text().trim());
                if ($(this).is(".up")) {
                    if(currentIndex > 1){
                        $(".labelPopUp-align", row).text(row.index());
                        $(".labelPopUp-align", row.prev()).text(parseInt(row.index())+1);
                    }
                    row.insertBefore(row.prev());

                } else {
                    if($("tr", row.parent()).length > currentIndex){
                        $(".labelPopUp-align", row.next()).text(row.index()+1);
                        $(".labelPopUp-align", row).text(row.index()+2);
                    }
                    row.insertAfter(row.next());
                }
            });
        }

        // Remove Modal PopUp table row
        function removeRow(id){
            <%= IsReadOnly ? "return;" : "" %>
            if($('#model_verticalmatrix_tbody tr').length === 1){
                alert("<%= Resources.ModelMatrixManagement.LabelAlertRemoveSingleException %>");
                return false;
            }

            if(confirm("<%= Resources.ModelMatrixManagement.LabelAskAreYouSure %>")){
                var tbody = $('#model_verticalmatrix_tbody');
                var previousTrLength = $("tr", tbody).length;

                $("#_"+id+"_").remove();
                $('#model_verticalmatrix_tbody tr').each(function(index) {
                    var lab = $('.labelPopUp-align', this);
                    lab.html(++index);
                });

                //Check is vertical
                var isVertical = false;
                <% if (GetIsVerticalCMMR())
                   {%>
                isVertical = true;    
                <% } %>

                if(!$("#dialog-form").hasClass("ui-dialog-content-NoScroll"))
                    $("#dialog-form").addClass("ui-dialog-content-NoScroll");

                var currentTrLength = $("tr", tbody).length;
                if(currentTrLength > 7 && currentTrLength < 12)
                {
                    if(previousTrLength >= 12){
                        $("#dialog-form").height($("#dialog-form").height() + (currentTrLength - 7) * $("tr", tbody).height());
                    }
                    else
                    {
                        $("#dialog-form").height($("#dialog-form").height() - $("tr", tbody).height());
                    }
                }
                else if(currentTrLength >= 12)
                {
                    $("#dialog-form").height(initialHeight);
                    $("#dialog-form").removeClass("ui-dialog-content-NoScroll");
                }
                else
                {
                    $("#dialog-form").height(initialHeight);
                }

                if(<%= (!IsReadOnly).ToString().ToLower() %> && (isVertical || (!isVertical && tbody[0].childNodes.length < 3))){
                    $("#btn_add").show();
                }else{
                    $("#btn_add").hide();
                }

            }
        }

        // Changes the view from label to select on Modal PopUp
        function changeToSelectVertical(labelx, id, idx, currentModelTier){
            var selectedModel = 0;
            var newSelectedModel = 0;
            var newSelectedModeltxt = 0;

            var label = $(labelx);
            var td = label.parent();
            var input = $("#"+idx+"_");
                
            var jsonModels = JSON.parse($('#<%=jsonModels.ClientID%>').val());
            var jsonsVmodels = JSON.parse($('#input_vertical_models_' + id).val());
            
            var select = $("<select>").attr("id","currentSelect");
           
            var modelVm = input.val().length == 0 ? undefined : JSON.parse(input.val());
            var priority = $('#model_verticalmatrix_tbody tr').length;

            if(modelVm != undefined)
            {
                selectedModel = JSON.parse(input.val()).ModelID;


            }else{
                selectedModel = undefined;
            }

            if(selectedModel == undefined){selectedModel = 0;}
            
            //Sort by tier of current model
            for(var i=0; i<jsonModels.length; i++) {
                if (jsonModels[i].Tier == currentModelTier)
                    jsonModels[i].SortByTier = -1;
                else
                    jsonModels[i].SortByTier = jsonModels[i].Tier;
            }


            //Sort Replacements
            jsonModels.sort(function(a, b) {
                var o1 = a.SortByTier;
                var o2 = b.SortByTier;

                var p1 = a.ModelName;
                var p2 = b.ModelName;

                if (o1 != o2) 
                {
                    if (o1 < o2) return -1;
                    if (o1 > o2) return 1;
                    return 0;
                }
                if (p1 < p2) return -1;
                if (p1 > p2) return 1;
                return 0;
            });

            
            var option = $("<option>");
            option.attr("value", 0);
            select.append(option);

            for(i=0;i<jsonModels.length;i++){
                var model = jsonModels[i];
                option = $("<option>");
                option.attr("value",model.ModelID).html(model.ModelName + "<%= Resources.ModelMatrixManagement.LabelNRPText %>" + parseFloat(Math.round( model.RetailPriceNew * 100) / 100).toFixed(2) + "<%= Resources.ModelMatrixManagement.LabelNewCostText %>" + parseFloat(Math.round( model.NewCost * 100) / 100).toFixed(2) );

                if(model.ModelID == selectedModel){
                    option.attr("selected",true);
                }
                select.append(option);
            }
            select.attr("data-placeholder", " ");
            td.append(select);
            var element = null;

            //Use different plugin if IE7
            if(isIE7 == true){
                element = select.combobox({ 
                    select: function(event, ui){ 
                        select.trigger('change');
                    }
                });
            }
            else{
                if(select.hasClass("chosenSelect") == false){
                    select.addClass("chosenSelect");
                }
                element = select.chosen().bind(
                {
                    "chosen:blur" : function(){ 
                        select.trigger('change'); 
                    }
                });

                //Focus on plugin so we can use blur
                $("#currentSelect_chosen .chosen-search input", select.parent()).focus();
            }
            
            element.on('change', function(evt, params) {
                newSelectedModel = $(this).val();
                newSelectedModeltxt = $(this).find('option:selected').text();
                    
                label.html(newSelectedModeltxt);
                if(modelVm != undefined){
                    for(i=0;i<jsonsVmodels.length;i++){
                        var model = jsonsVmodels[i];
                        if(model.ModelID == modelVm.ModelID){
                            jsonsVmodels.splice(i,1);
                            priority = i;
                        }
                    }
                }

                for(i=0;i<jsonModels.length;i++){
                    var model = jsonModels[i];
                    if(model.ModelID == newSelectedModel){
                        
                        model.Priority = priority;
                        model.StatusId = $("#vertical_currentSelect_"+idx+"_").val();
                        $('#'+idx+'_').val(JSON.stringify(model));
                        var _newcost = parseFloat(Math.round( model.RetailPriceNew * 100) / 100).toFixed(2);//parseFloat(model.RetailPriceNew);//
                        var _newprice = parseFloat($('#input_retailprice_'+id).val()); 
                        model.TierEx = IsTierException(_newprice,_newcost);
                        if(model.TierEx) {
                            var tierLevel = TierLevelException(_newprice, _newcost);
                            if(tierLevel==1)
                                label.addClass('tier_exeption');
                            if(tierLevel==2)
                                label.addClass('tier_exeption_lower');
                        }else{
                            label.removeClass('tier_exeption');
                            label.removeClass('tier_exeption_lower');
                        }
                    }
                }

                label.show();
                $(".chosen-container", select.parent()).remove();
                $(this).remove();
            });
            
            select.focus();
            label.hide();
            
        }

        // Returs Select with the conditions
        function selectConditions(conditionID, ida){
            var select = $("<select>").attr("id","vertical_currentSelect_"+ ida+"_");
            var jsonconditions = JSON.parse($('#inputConditions').val());
            for (var i = 0; i < jsonconditions.length; i++) {
                var json = jsonconditions[i];
                var option = $("<option>").attr("value",json.Value).html(json.Text);
                if(json.Value == conditionID){
                    option.attr("selected",true);
                }
                select.append(option);
            }
            return select;
        }

        // Adds a new Row on Modal PopUp
        function AddRow(sender){
            //alert('here1');
            <%= IsReadOnly ? "return;" : "" %>
            var tbody = $('#model_verticalmatrix_tbody');
            var rowID = $('#current_rowid_popup').val();
            //alert('here2');
            var defaultModel = $("#td_model_id_"+rowID).val();
            var jsonModels = JSON.parse($('#<%=jsonModels.ClientID%>').val());
            var json;
            var currentTier;
            //alert('here3');
            for (var a = 0; a < jsonModels.length; a++) {
                if(jsonModels[a].ModelID == defaultModel){
                    json = jsonModels[a];
                    currentTier = jsonModels[a].Tier;
                }
            }
            //alert('here4');
            var randomId = Math.floor((Math.random()*1000)+1); 
            json.ModelID = randomId;

            //Check is vertical
            var isVertical = false;
            //alert('here');
        <% if (GetIsVerticalCMMR())
           {%>
            isVertical = true;    
        <% } %>

            var newRow = $("<tr>").attr({"id":("_"+randomId+"_")}).append($("<td>").append($("<input >").attr({"id":(randomId+"_"), "style":"display:none", "value":""}))
                        .append($('<label>').prop('class', 'labelPopUp-align').append($('#model_verticalmatrix_tbody tr').length + 1)).append('<a class="up">&#8593;</a><a class="down">&#8595;</a>'))//json.Priority
                        .append($("<td>").append($("<label>").bind('click',{json:randomId},function(e){changeToSelectVertical(this,rowID,e.data.json,currentTier);}).prop("id", "labelToSelect")))
                        .append((isVertical) ? $("<td>").append(selectConditions(0,randomId)).addClass("center_all") : '') 
                        .append($("<td>").addClass("center_all").append($("<label>").addClass("label_pointer").bind("click",{id:randomId},
                        function(e){
                            removeRow(e.data.id);
                            if(isVertical || (!isVertical && tbody[0].childNodes.length < 3))
                            {
                                $(sender).show();
                            }

                         }).html('X')));

            tbody.append(newRow);

            if(!$("#dialog-form").hasClass("ui-dialog-content-NoScroll"))
                $("#dialog-form").addClass("ui-dialog-content-NoScroll");

            if($("tr", tbody).length > 7 && $("tr", tbody).length < 12)
            {
                $("#dialog-form").height($("#dialog-form").height() + newRow.height());
            }
            else if($("tr", tbody).length >= 12)
            {
                $("#dialog-form").height(initialHeight);
                $("#dialog-form").removeClass("ui-dialog-content-NoScroll");
            }

            if(!isVertical && tbody[0].childNodes.length >= 3)
            {
                $(sender).hide();
            }

            UpDownTrigger();
            $('#labelToSelect:last', $('tr:last', tbody)).click();
        }

        // updates the Tier exception on vertical clients
        function UpdateVerticalModelTierEx(){
        
            var totalRecords = <%=totalrecords%>;
            var replacements = Array();
            var masterModels = JSON.parse($('#<%=masterModels.ClientID%>').val());

        for (var i = 0; i < totalRecords; i++) {
            var mmodelId = $("#td_model_id_"+i).val();
            for (var b = 0; b < masterModels.length; b++) {
                if(mmodelId == masterModels[b].ModelID){
                    replacements = masterModels[b].Replacements;
                    $("#td_model_id_"+i).parent("td").find('label').removeClass("tier_exeption");
                    if(masterModels[b].TierEx){
                        if(masterModels[b].TierLevel==1)
                            $("#td_model_id_"+i).parent("td").find('label').addClass("tier_exeption");
                        if(masterModels[b].TierLevel==2)
                            $("#td_model_id_"+i).parent("td").find('label').addClass("tier_exeption_lower");
                    }
                }
            }
           
            for (var a = 0; a < replacements.length; a++) {
                var model = replacements[a];
                if(model.ModelID != undefined){
                    switch (model.Priority) {
                        case 1:
                            $("#input_primary_current_"+i).val(JSON.stringify(model));
                            $("#primary_"+i).find('label').removeClass('tier_exeption');
                            if(model.TierEx){
                                if(model.TierLevel==1)
                                    $("#primary_"+i).find('label').addClass('tier_exeption');
                                if(model.TierLevel==2)
                                    $("#primary_"+i).find('label').addClass('tier_exeption_lower');
                            }
                            break;
                        case 2:
                            $("#input_secondary_current_"+i).val(JSON.stringify(model));
                            $("#secondary_"+i).find('label').removeClass('tier_exeption');
                            if(model.TierEx){
                                if(model.TierLevel==1)
                                    $("#secondary_"+i).find('label').addClass('tier_exeption');
                                if(model.TierLevel==2)
                                    $("#secondary_"+i).find('label').addClass('tier_exeption_lower');
                            }
                            break;
                        case 3:
                            $("#input_tertiary_current_"+i).val(JSON.stringify(model));
                            $("#tertiary_"+i).find('label').removeClass('tier_exeption');
                            if(model.TierEx){
                                if(model.TierLevel==1)
                                    $("#tertiary_"+i).find('label').addClass('tier_exeption');
                                if(model.TierLevel==2)
                                    $("#tertiary_"+i).find('label').addClass('tier_exeption_lower');
                            }
                            break;
                    }
                }
            }
        }
            // Update tooltips
            for (var i = 1; i <= <%=totalrecords%>; i++) {
                setTimeout(function(){
                    ToolTipModels(i);
                }, 1);
            }
        }

        // checks if the exist an exception based on tier bounds
        function CheckTierException(id){
            //console.log("CheckTierException");
            //console.log("-> " + id);
            var totalRecords = <%=totalrecords%>;
            var modelObj;
            var newRetailPriceNewInput = $('#input_retailprice_'+id);
            var modelInput = $('#td_model_id_'+id);//ID
            var jsonModels = JSON.parse($('#<%=jsonModels.ClientID%>').val());
            for (var a = 0; a < jsonModels.length; a++) {
                if(jsonModels[a].ModelID == modelInput.val()){
                    jsonModels[a].RetailPriceNew = newRetailPriceNewInput.val();
                    modelObj = jsonModels[a];
                }
            }
            $('#<%=jsonModels.ClientID%>').val(JSON.stringify(jsonModels));

            for (var i = 1; i <= totalRecords; i++) {
                try {
                    var modelJson = JSON.parse($('#input_primary_current_'+i).val());
                    if(parseInt(modelJson.ModelID) == parseInt(modelInput.val())){
                        $('#input_primary_current_'+i).val(JSON.stringify(modelObj));
                        modelJson = modelObj;
                        try {
                            var _newprice = parseFloat($('#input_retailprice_'+i).val()); 

                            var _newcost = parseFloat(modelObj.RetailPriceNew);

                            if(IsTierException(_newprice,_newcost)){
                                $('#primary_'+i).find('label').addClass('tier_exeption');
                            }else{
                                $('#primary_'+i).find('label').removeClass('tier_exeption');
                            }
                        } catch (e) {
                            console.log(e);
                        }
                    }
                } catch (e) {
                    console.log(e);
                }
            }

            for (var i = 1; i <= totalRecords; i++) {
                try {
                    var modelJson = JSON.parse($('#input_secondary_current_'+i).val());
                    if(parseInt(modelJson.ModelID) == parseInt(modelInput.val())){
                        $('#input_secondary_current_'+i).val(JSON.stringify(modelObj));
                        modelJson = modelObj;
                        try {
                            var _newprice = parseFloat($('#input_retailprice_'+i).val()); 
                            var _newcost = parseFloat(modelObj.RetailPriceNew);
                            if(IsTierException(_newprice,_newcost)){
                                $('#secondary_'+i).find('label').addClass('tier_exeption');
                            }else{
                                $('#secondary_'+i).find('label').removeClass('tier_exeption');
                            }
                        } catch (e) {
                            console.log(e);
                        }
                    }
                } catch (e) {
                    console.log(e);
                }
            }

            for (var i = 1; i <= totalRecords; i++) {
                try {
                    var modelJson = JSON.parse($('#input_tertiary_current_'+i).val());
                    if(parseInt(modelJson.ModelID) == parseInt(modelInput.val())){
                        $('#input_tertiary_current_'+i).val(JSON.stringify(modelObj));
                        modelJson = modelObj;
                        try {
                            var _newprice = parseFloat($('#input_retailprice_'+i).val()); 
                            var _newcost = parseFloat(modelObj.RetailPriceNew);
                            if(IsTierException(_newprice,_newcost)){
                                $('#tertiary_'+i).find('label').addClass('tier_exeption');
                            }else{
                                $('#tertiary_'+i).find('label').removeClass('tier_exeption');
                            }
                        } catch (e) {
                            console.log(e);
                        }
                    }
                } catch (e) {
                    console.log(e);
                }
            }
        }

        // validates the tier based on the bounds
        function IsTierExceptionAjax(newcost, orgcost){
            if(newcost == undefined || orgcost == undefined){
                console.log("Warning NULL values GetTier.");
                return 0; 
            }
            $.ajax({
                type: "POST",
                url: "Default.aspx/GetTierForModel",
                data: JSON.stringify({"cost":newcost,"cost2":orgcost}),
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                async:false,
                success: function (msg) {
                    return Boolean(msg.d);
                },
                error: function () {
                    console.log("An unknown error occured trying\nto load the matrix status.\nPlease ty again later.");
                    return 0;
                }
            });
        }

        function GetTierBasedOnCost(newcost){
            var tiers =JSON.parse($('#jsonTier').val());
            var tier1 = tiers[tiers.length-1].Tier;
            for (var i = 0; i < tiers.length; i++) {
                var t = tiers[i];
                if(parseFloat(newcost) < parseFloat(t.Upper) && parseFloat(newcost) > parseFloat(t.Lower)){
                    tier1 = parseInt(t.Tier);
                    break;
                }
            }
            return tier1;
        }

        function IsTierException(newcost, orgcost){
            if(newcost == undefined || orgcost == undefined){
                console.log("Warning NULL values GetTier.");
                return false; 
            }
            
            var tiers =JSON.parse($('#jsonTier').val());
            var tier1, tier2 = 0;
            //console.log("Tiers: " + JSON.stringify(tiers));
            //console.log("1st: " + newcost + " 2st: " + orgcost);
            for (var i = 0; i < tiers.length; i++) {
                var t = tiers[i];
                if(parseFloat(newcost) < parseFloat(t.Upper) && parseFloat(newcost) > parseFloat(t.Lower)){
                    tier1 = parseInt(t.Tier);
                }
                if(parseFloat(orgcost) < parseFloat(t.Upper) && parseFloat(orgcost) > parseFloat(t.Lower)){
                    tier2 = parseInt(t.Tier);
                }
            }
            return (tier1 != tier2);
        }

        function TierLevelException(newcost, orgcost){

            if(newcost == undefined || orgcost == undefined){
                console.log("Warning NULL values GetTier.");
                return 0; 
            }
            
            var tiers =JSON.parse($('#jsonTier').val());
            var tier1, tier2 = 0;

            for (var i = 0; i < tiers.length; i++) {
                var t = tiers[i];
                if(parseFloat(newcost) < parseFloat(t.Upper) && parseFloat(newcost) > parseFloat(t.Lower)){
                    tier1 = parseInt(t.Tier);
                }
                if(parseFloat(orgcost) < parseFloat(t.Upper) && parseFloat(orgcost) > parseFloat(t.Lower)){
                    tier2 = parseInt(t.Tier);
                }
            }

            if (tier1 > tier2) //lower
                return 2;

            if (tier1 < tier2) //bigger
                return 1;

            return 0; //same
        }


        // Gets the new calclated % to C# code using ajax
        function RecalculateNonNewCostRatioAjax(inputId){
            var masterModels = JSON.parse($('#<%=masterModels.ClientID%>').val());
            var masterModelID = $("#td_model_id_"+inputId).val();
            var mmodel;
            for (var i = 0; i < masterModels.length; i++) {
                if(masterModelID == masterModels[i].ModelID){
                    model = masterModels[i];
                }
            }

            var newCost =parseFloat(model.NewCost);//parseFloat( $("#input_newCost_" + inputId).val());
            var nonNewCost =parseFloat(model.RefurbCost);//parseFloat($("#input_refurbcost_" + inputId).val());

            $.ajax({
                type: "POST",
                url: "Default.aspx/RecalculateNonNewCostRatio",
                data: JSON.stringify({"newCost":newCost, "nonNewCost":nonNewCost}),
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (msg) {
                    $('#'+inputId).removeClass('errortd');
                    var json = JSON.parse(msg.d);
                    $('#td_costratio_'+inputId).html(parseInt(json.CostRatio) + '%');
                    if(json.CostRatioEx){ $('#'+inputId).addClass('errortd');}
                    UpdateMasterModelCosts(inputId);
                },
                error: function (e) {
                    ErrorHandler(e, "Default.aspx/RecalculateNonNewCostRatio");// alert("An error occured trying to recalculate\nthe non new cost ratio.\nPlease ty again later.");
                }
            });
        }

        // Changes the view from label to input
        function changeToInput(label, isNewCost){
            var inputActive = $('#inputActive');
            if(parseInt(inputActive.val())==0){ 
                inputActive.val(1);

                var label = $(label);
                var myTd = label.parent('td');
                var myTr = myTd.parent('tr');
                var input = myTd.find('input');
                var originalValue = parseFloat(input.val());

                var valueOrg = input.val();
                var newCostInput = $("#input_newCost_" + myTr.attr('id'));
                var refurbInput = $("#input_refurbcost_" + myTr.attr('id'));
                
                label.html(valueOrg);
                label.hide();

                input.show();
                input.focus();
                input.select();

                input.focusout(function(){
                    if($.isNumeric($(this)[0].value) == false)
                    {
                        $(this)[0].value = '';
                    }

                    $(this).removeClass('error_input');
                    $.validity.start();
                    if($(this).attr('id').indexOf("_other_") != -1){
                        $(this).require("<%= Resources.ModelMatrixManagement.LabelOtherPriceIsRequired %>").greaterThanOrEqualTo(0, "<%= Resources.ModelMatrixManagement.LabelOtherPriceCantBeNegative %>");
                }else if($(this).attr('id').indexOf("_newCost__") != -1){
                    $(this).require("<%= Resources.ModelMatrixManagement.LabelNewCostIsRequired %>").greaterThan(0,"<%= Resources.ModelMatrixManagement.LabelNewCostCanrBeZeroNegative %>");
                }else if($(this).attr('id').indexOf("_retailprice_") != -1){
                    $(this).require("<%= Resources.ModelMatrixManagement.LabelNewRetailPriceIsRequired %>").greaterThanOrEqualTo(parseFloat(newCostInput.val()), "<%= Resources.ModelMatrixManagement.LabelNewRetailPriceCantBeZeroNegative %>");
                }else if($(this).attr('id').indexOf("_retailpricenonnew_") != -1){
                    $(this).require("<%= Resources.ModelMatrixManagement.LabelNonNewRetailPriceRequired %>").greaterThanOrEqualTo(parseFloat(refurbInput.val()), "<%= Resources.ModelMatrixManagement.LabelNonNewRetailPriceCantBeZeroNegative %>");
                    }else{
                        $(this).require("<%= Resources.ModelMatrixManagement.LabelDefaultInputRequired %>").greaterThan(0, "<%= Resources.ModelMatrixManagement.LabelDefaultCantBeZeroNegative %>");
                }

                    var result = $.validity.end();

                if(result.valid) {
                    if(originalValue != parseFloat($(this).val())) {
                        if($(this).attr('id').indexOf("_newCost_") != -1) { 
                            GetNewCosts($(this).val(), myTr.attr('id')); 
                        } else {
                            UpdateMasterModelCosts(myTr.attr('id'));
                        }
                        
                        UpdateVerticalModelTierEx();

                        if($(this).attr('id').indexOf("input_refurbcost_") != -1) { 
                            RecalculateNonNewCostRatioAjax( myTr.attr('id')); 
                        }

                        //color td to blue if the value is changed and not updated
                        myTd.attr("style", "background-color: #bde5f8 !important").addClass("unsavedChanges");
                        DisableButtons();
                    }
                    label.html(formatCurrency(parseFloat(Math.round( $(this).val() * 100) / 100).toFixed(2)));
                    label.show();
                    $(this).hide();
                    $(this).unbind('focusout');
                    inputActive.val(0);

                }else{
                    $(this).addClass('error_input');
                }
            });  

    input.bind('keydown', function (e) {
        var keyNum = e.keyCode || e.which;
        
        if (keyNum == 9) { 
            e.preventDefault();
            $(this).focusout();
            var nextCell = $(this).parents('td').next('td');
            //get next row
            if (nextCell[0].id == "") {
                if ($(this).parent('td').parent('tr').next('tr').css('display') != 'none') {
                    nextCell = $(this).parent('td').parent('tr').next('tr').find('td:first');
                } else {
                    return false;
                }        
            }
            nextEditableCellTabClick(nextCell);
            return false;
        }
        if (keyNum == 13) { //if this is enter key
            e.preventDefault();
            $(this).focusout();
            return false;
        }
        return true;
    });
}
}

        function nextEditableCellTabClick(currentCell) {
            if (currentCell.length > 0) 
            {
                if (currentCell.css('display') != 'none') 
                {
                    var currentLable = currentCell.find('label.label-pointer');
                    if (currentLable.length > 0) {
                        changeToInput(currentLable);
                        return;
                    } else 
                    {
                        nextEditableCellTabClick(currentCell.next('td'));
                    }

                } else {
                    nextEditableCellTabClick(currentCell.next('td'));
                }
            }
        }

//
function MakeTableSorteable(tableID){
    tableID.tablesorter({
        theme: 'default',
        widthFixed: false,
        showProcessing: false,
        headerTemplate: '{content}',
        onRenderTemplate: null, // function(index, template){ return template; },
        onRenderHeader: function (index) {
            $(this).find('div.tablesorter-header-inner').addClass('roundedCorners');
        },
        cancelSelection: true,
        sortMultiSortKey: "shiftKey",
        sortResetKey: 'ctrlKey',
        delayInit: false,
        serverSideSorting: false,
        ignoreCase: true,
        sortForce: null,
        sortAppend: null,
        sortInitialOrder: "asc",
        sortLocaleCompare: false,
        sortReset: false,
        sortRestart: false,
        emptyTo: "bottom",
        stringTo: "max",
        textExtraction: {
            0: function (node) {
                return $(node).text();
            },
            1: function (node) {
                return $(node).text();
            }
        },
        textSorter: null,
        initWidgets: true,
        widgets: ['zebra'],//, 'columns'
        widgetOptions: {
            zebra: [
                "ui-widget-content even",
                "ui-state-default odd"],
            uitheme: 'jui',
            //columns: [
            //    "primary",
            //    "secondary",
            //    "tertiary"],
            columns_thead: true,
            filter_childRows: false,
            filter_cssFilter: "tablesorter-filter",
            filter_functions: null,
            filter_hideFilters: false,
            filter_ignoreCase: true,
            filter_reset: null,
            filter_searchDelay: 300,
            filter_serversideFiltering: false,
            filter_startsWith: false,
            filter_useParsedData: false,
            resizable: true,
            saveSort: true,
            stickyHeaders: "tablesorter-stickyHeader"

        },
        initialized: function (table) {},
        tableClass: 'tablesorter',
        cssAsc: "tablesorter-headerSortUp",
        cssDesc: "tablesorter-headerSortDown",
        cssHeader: "tablesorter-header",
        cssHeaderRow: "tablesorter-headerRow",
        cssIcon: "tablesorter-icon",
        cssChildRow: "tablesorter-childRow",
        cssInfoBlock: "tablesorter-infoOnly",
        cssProcessing: "tablesorter-processing",
        selectorHeaders: '> thead th, > thead td',
        selectorSort: "th, td",
        selectorRemove: "tr.remove-me",
        debug: false

    }).tablesorterPager({
        container: $(".pager"),
        ajaxUrl: null,
        ajaxProcessing: function(ajax) {
            if (ajax && ajax.hasOwnProperty('data')) {
                return [ajax.data, ajax.total_rows];
            }
        },

        output: '{startRow} to {endRow} ({totalRows})',
        updateArrows: true,
        page: 0,
        size: 40,
        fixedHeight: true,
        removeRows: false,
        cssNext: '.next',
        cssPrev: '.prev',
        cssFirst: '.first',
        cssLast: '.last',
        cssGoto: '.gotoPage',
        cssPageDisplay: '.pagedisplay',
        cssPageSize: '.pagesize',
        cssDisabled: 'disabled'

    });
}

//Disables buttons before user click update 
function DisableButtons() {
    $('#' + '<%= btnSendback.ClientID %>').attr('disabled', 'disabled');
    $('#' + '<%= btnPushprod.ClientID %>').attr('disabled', 'disabled');
    $('#' + '<%= btnSubmit.ClientID %>').attr('disabled', 'disabled');
    $('#' + '<%= btnSendback.ClientID %>').css( 'cursor', 'not-allowed' );
    $('#' + '<%= btnPushprod.ClientID %>').css( 'cursor', 'not-allowed' );
    $('#' + '<%= btnSubmit.ClientID %>').css( 'cursor', 'not-allowed' );
    $('#' + '<%= btnPushprod.ClientID %>').css('color', 'gray');
    $('#' + '<%= btnSendback.ClientID %>').css('color', 'gray');  
    $('#' + '<%= btnSubmit.ClientID %>').css('color', 'gray'); 

}
// uncomment one below for more details...
// $("#loading_dialog").loading("loadStart");
// $("#loading_dialog").loading("loadStart","Updating");
// $("#loading_dialog").loading("loadStop");
    </script>
</asp:Content>

