$(document).ready(function () {
    $("#UserName").focus();


    $('#versionoverlay').hide();
    $(document).ready(function () {
        var vcookie = localStorage.getItem('VersionCookie');

        if (vcookie == null || vcookie == "" || vcookie == undefined) {
            localStorage.setItem('VersionCookie', $('#CurrVersion').text())
        }
        else {

            if (vcookie != $('#CurrVersion').text()) {
                $('#versionoverlay').show();
            }
            else {
                $('#UserName').focus();
                $('#versionoverlay').hide();
            }
        }

    });

    var data = {};
    data.DeptId = 0;
    $.ajax({
        type: "POST",
        url: "../Master/DepartmentGetandGets",
        data: data,
        success: function (result) {
            DepartmentLoad(result.oList);


        }
    });
    $.ajax({
        type: "POST",
        url: "../Login/CompanyDetailGet",
        data: data,
        success: function (result) {
            GetComanyDetails(result.QList);
        }
    });
    $('#UserName').keydown(function (e) {
        var key = e.charCode ? e.charCode : e.keyCode ? e.keyCode : 0;
        if (key == 13) {
            e.preventDefault();
            $('#Password').focus();
        }
        
    });
    $('#Password').keydown(function (e) {
        var key = e.charCode ? e.charCode : e.keyCode ? e.keyCode : 0;
        if (key == 13) {
            e.preventDefault();
            $('#deptselect').focus();
        }

    });
    $('#deptselect').keydown(function (e) {
        var key = e.charCode ? e.charCode : e.keyCode ? e.keyCode : 0;
        if (key == 13) {
            e.preventDefault();
            $('#btnlogin').focus();
        }

    });
    $("#btnlogin").click(function (e) {
        UserLogin();
    });

});


function DepartmentLoad(result) {
    $("#deptselect").empty();
    for (var i = 0; i < result.length; i++) {
        $("#deptselect").append("<option value='" + result[i].DepartmentId + "'>" + result[i].DepartmentName + "</option>");
    }
}


function login() {
    window.location = '../master/';
}



function UserLogin() { 
    var cat = (localStorage.getItem('nanana'));
    if (cat != null) {

        clearSession();
    }
        
        var data = {};   //array
        data.UserLoginId = $('#UserLoginId').val();
        data.UserName = $('#UserName').val();
        data.Password = $('#Password').val();
        data.DeptID = $('#deptselect').val();

        $.ajax({
            type: "POST",
            url: "../Login/UserLoginCheck",
            data: data,
            success: function (result) {
                if (result.oList.length != '') {
                    $('#Loading').show();
                    GetUserDetails(result.oList);
                }
                else {
                    $('#Loading').hide();
                    toastr.error('Incorrect UserName/Password');
                    $('#UserName').focus();
                }

            }
        });
    //}
    //else {
    //    $('#Loading').hide();
    //    var res = cat.split(":");
    //    toastr.error('Please Logout or Clear Current Session',"'" + res[3] + "' is LoggedIn");       
    //}
}


function GetUserDetails(result) {
    var DivArray = [];
    //var UserDetails = [];
    for (var i = 0; i < result.length; i++) {
        DivArray.push(result[i].DivId);
    }
    localStorage.setItem('tttt', DivArray);
     var UserDetails = '' + result[0].UserId + ':' + result[0].DeptId + ':' + result[0].LocationID + ':' + result[0].UserName + ':' + result[0].DepartmentName + ':' + result[0].UserMenu + '';

     localStorage.setItem('nanana', UserDetails);


     var DCompanyName = result[0].DCompanyName;
     var DAddress = result[0].DAddress;
     var DPhoneNo = result[0].DPhoneNo;
     var DEmail = result[0].DEmail;
     var DFax = result[0].DFax;
     var DTRNNo = result[0].DTRNNo;


     var D_SalesPrintId = result[0].D_SalesPrintId;
     var D_SalesReturnPrintId = result[0].D_SalesReturnPrintId;
     var D_VoucherPrintId = result[0].D_VoucherPrintId;
     var D_QuotationPrintId = result[0].D_QuotationPrintId;
     var D_PrintColor = result[0].D_PrintColor;

     var MainComapnyDetails = (localStorage.getItem('cacaca')).split('%');

     if (localStorage.getItem('cacaca') != null &&  (DCompanyName!='')) {      

         var DepartmentAddress = '' + MainComapnyDetails[0] + '%' + MainComapnyDetails[1] + '%' + DCompanyName + '%' + DAddress + '%' + DPhoneNo + '%' +
             DEmail + '%' + DFax + '%' + MainComapnyDetails[7] + '%' + MainComapnyDetails[8] + '%' + MainComapnyDetails[9] + '%' + MainComapnyDetails[10] + '%' +
             MainComapnyDetails[11] + '%' + DTRNNo + '%' + MainComapnyDetails[13] + '%' + MainComapnyDetails[14] + '%' + MainComapnyDetails[15] + '%' +
             MainComapnyDetails[16] + '%' + D_SalesPrintId + '%' + D_SalesReturnPrintId + '%' + D_VoucherPrintId + '%' + D_QuotationPrintId + '%' + D_PrintColor + '';

         localStorage.setItem('cacaca', DepartmentAddress);
     }
     else {
         var DepartmentAddress = '' + MainComapnyDetails[0] + '%' + MainComapnyDetails[1] + '%' + MainComapnyDetails[2] + '%' + MainComapnyDetails[3] + '%' + MainComapnyDetails[4] + '%' +
             MainComapnyDetails[5] + '%' + MainComapnyDetails[6] + '%' + MainComapnyDetails[7] + '%' + MainComapnyDetails[8] + '%' + MainComapnyDetails[9] + '%' + MainComapnyDetails[10] + '%' +
             MainComapnyDetails[11] + '%' + MainComapnyDetails[12] + '%' + MainComapnyDetails[13] + '%' + MainComapnyDetails[14] + '%' + MainComapnyDetails[15] + '%' +
             MainComapnyDetails[16] + '%' + D_SalesPrintId + '%' + D_SalesReturnPrintId + '%' + D_VoucherPrintId + '%' + D_QuotationPrintId + '%' + D_PrintColor + '';
         localStorage.setItem('cacaca', DepartmentAddress);
     }


    var flo = (localStorage.getItem('cacaca'));
    if (flo == null) {
        $('#Loading').hide();
        toastr.error('License Expired');
        $('#Activatelink').show();
        localStorage.removeItem('nanana');
        localStorage.removeItem('tttt');

       
    } else {
        var dashboard = result[0].UserMenu.split(",");
        localStorage.setItem('LoginMe', '1');
        if (dashboard.indexOf("M163") != -1) {

            window.location = '../Master/';
            localStorage.setItem('defaultdashboard', '../Master/');

        }
        else if (dashboard.indexOf("M171") != -1) {

            window.location = '../Master/SalesManDashboard';
            localStorage.setItem('defaultdashboard', '../Master/SalesManDashboard');

        }
        else if (dashboard.indexOf("M164") != -1) {
            window.location = '../Master/UsedcarsDashBoard';
            localStorage.setItem('defaultdashboard', '../Master/UsedcarsDashBoard');
        }
        else if (dashboard.indexOf("M215") != -1) {
            window.location = '../Dashboard/DashBoardElectro';
            localStorage.setItem('defaultdashboard', '../Dashboard/DashBoardElectro');
        }
        else if (dashboard.indexOf("M216") != -1) {
            window.location = '../Dashboard/DashBoardScrap';
            localStorage.setItem('defaultdashboard', '../Dashboard/DashBoardScrap');
        }
        else if (dashboard.indexOf("M217") != -1) {
            window.location = '../Dashboard/DeliveryDashBoard';
            localStorage.setItem('defaultdashboard', '../Dashboard/DeliveryDashBoard');
        }
        else if (dashboard.indexOf("M222") != -1) {
            window.location = '../Master/EmployeeDashBoard';
            localStorage.setItem('defaultdashboard', '../Master/EmployeeDashBoard');
        }
        else if (dashboard.indexOf("M226") != -1) {
            window.location = '../Master/UserDashBoard';
            localStorage.setItem('defaultdashboard', '../Master/UserDashBoard');
        }
        else if (dashboard.indexOf("M261") != -1) {
            window.location = '../Dashboard/ItemwiseDashBoard';
            localStorage.setItem('defaultdashboard', '../Dashboard/ItemwiseDashBoard');
        }
        else if (dashboard.indexOf("M311") != -1) {
            window.location = '../Dashboard/RCDashBoard';
            localStorage.setItem('defaultdashboard', '../Dashboard/RCDashBoard');
        }
        else if (dashboard.indexOf("M321") != -1) {
            window.location = '../Dashboard/MyDashBoard';
            localStorage.setItem('defaultdashboard', '../Dashboard/MyDashBoard');
        }
        else {
            //$('#Loading').hide();
            //toastr.info('Current User Has No DashBoard Rights');
            //localStorage.removeItem('nanana');
            //localStorage.removeItem('tttt');
            window.location = '../DashBoard/DashBoard';
            localStorage.setItem('defaultdashboard', '../DashBoard/DashBoard');

        }
        
    }
    
}

function GetComanyDetails(result) {

    var ComanyDetail = '' + result[0].CompanyId + '%' + result[0].CompanyCode + '%' + result[0].CompanyName + '%' + result[0].Address + '%' + result[0].PhoneNo + '%' + result[0].Email + '%' +
        result[0].Fax + '%' + result[0].PeriodFrom + '%' + result[0].PeriodTo + '%' + result[0].ProtectionDate + '%' + result[0].CurrencyId + '%' + result[0].Decimals + '%' + result[0].TRNNo + '%' +
        result[0].DelFlag + '%' + result[0].Area + '%' + result[0].BusinessType + '%' + result[0].CurDate + '%' + result[0].SalesPrint + '%' + result[0].SalesReturnPrint + '%' + result[0].VoucherPrint + '%' +
        result[0].QuotationPrint + '%' + result[0].PrintColor + '';
    localStorage.setItem('cacaca', ComanyDetail); 
    $('#CompanyN').text(result[0].CompanyName); 
}

function clearSession() {
    $('#Loading').hide();
    var catte = (localStorage.getItem('nanana'));
    var resee = catte.split(":");
    if (catte != null)
    {
        var data = {};   //array                   
        data.UserId = resee[0];

        $.ajax({
            type: "POST",
            url: "../Login/UserLogoutCheck",
            data: data,
            success: function (result) {
                localStorage.removeItem('nanana');
                localStorage.removeItem('tttt');
                //toastr.success("Session Cleared");
            }
        });
    }
    else {
        localStorage.removeItem('nanana');
        localStorage.removeItem('tttt');
        //toastr.success("Session Cleared");
    }
    
    
    
}
function Newuser() {
    $('#Loading').hide();
    toastr.warning("Please Contact your Admin");
}


function activate() {
    var data = {};
    $.ajax({
        type: "POST",
        url: "../Login/GetCompanyCode",
        data: data,
        success: function (result) {
            var CC = result.QList[0].CompanyCode;
            var DD = result.QList[0].ValidationKey;
            if (parseInt(result.QList[0].Days) > 0) {
                DD = DD +'-'+ result.QList[0].Days+'M'
            }
            else {
                DD = DD +'-'+ result.QList[0].Days + 'E'
            }
            $('#Comapnycode').text(CC + '-' + DD)
        }
    });

    $('#ExpiryDiv').show();
    $('#expirycode').val('');
    $('#expirycode').focus();
}

function CheckExpiry() {

    if ($('#expirycode').val() == '') {
        $('#Loading').hide();
        toastr.warning("Please Enter The Activation Code");
        $('#expirycode').focus();
    } else {        
        var data = {};
        data.ActivationCode = $('#expirycode').val();
        $.ajax({
            type: "POST",
            url: "../Login/ComapnyExpiryUpdate",
            data: data,
            success: function (result) {                
                var status = result.QList[0].Status;
                if (status == 1) {
                    $.ajax({
                        type: "POST",
                        url: "../Login/CompanyDetailGet",
                        data: data,
                        success: function (result) {
                            GetComanyDetails(result.QList);
                        }
                    });
                    $('#ExpiryDiv').hide();
                    $('#Activatelink').hide();
                    $('#Loading').hide();
                    toastr.success("License Activated");
                } else {
                    $('#expirycode').val('');
                    $('#expirycode').focus();
                    $('#Loading').hide();
                    toastr.error('Invalid Activation Code');
                }

            }
        });
    }

}

//conge Lower Case letter to upper CODE and NAME
function changetoupper(Id) {
    $('#' + Id).val($('#' + Id).val().toUpperCase())
}

function Checklength(evt) {
    
    var charCode = (evt.which) ? evt.which : event.keyCode
    if (charCode != 8 && charCode != 13) {
        if (($('#expirycode').val()).length == 4 || ($('#expirycode').val()).length == 9 || ($('#expirycode').val()).length == 14) {
            $('#expirycode').val($('#expirycode').val() + '-')
        }
    }
}