﻿var browser = new BrowserDetect().browser;
var version = new BrowserDetect().version;
var isBrowserCorrect = true;

if (browser == "Opera") { }
else if (browser == "Explorer") { if (version >= 6) { } }
else {
    isBrowserCorrect = false ;
}

jQuery(document).ready(InitPage);
var json = GetSessionParam();

var UserData = new UserData();
UserData.Load();

function UserData() {
    this.Id = null;
    this.Name = null;
    this.FilialId = null;
    this.KitPages = null;
    this.Menu = null;

    this.Load = UserData_LoadFromCookies;
    this.Save = UserData_SaveToCookies;
    this.IsAuthorized = UserData_IsAuthorized;

    function UserData_LoadFromCookies() {
        this.Id = jQuery.cookie("premiaUserId");
        this.Name = jQuery.cookie("premiaUserName");
        this.FilialId = jQuery.cookie("premiaUserFilialId");
        this.KitPages = jQuery.cookie("premiaUserKitPages");
        this.Menu = jQuery.cookie("premiaUserMenu");
    }

    function UserData_SaveToCookies(_userId, _userName, _userFilialId, _userKitPages, _userMenu) {
        this.Id = _userId;
        this.Name = _userName;
        this.FilialId = _userFilialId;
        this.KitPages = _userKitPages;
        this.Menu = _userMenu;

        jQuery.cookie("premiaUserId", _userId, { expires: 2, secure: true });
        jQuery.cookie("premiaUserName", _userName);
        jQuery.cookie("premiaUserFilialId", _userFilialId);
        jQuery.cookie("premiaUserRoleId", _userKitPages);
        jQuery.cookie("premiaUserRoleName", _userMenu);
    }

    function UserData_IsAuthorized() { return (this.Id != "0" && this.Id != null && this.Id != ""); }

}


//  показываем waitscreen
function WaitScreenShow() { jQuery("#divWaitScreen").css("display", "block"); }
//  скрываем waitscreen
function WaitScreenHide() { jQuery("#divWaitScreen").css("display", "none"); }

function InitPage() {
    if (jQuery.cookie("premiaUserCheck")) {
        jQuery("#check_Button").attr("src", "img/new/check_.png");
    }
    RememberMe();
    WaitScreenHide();

    documentResize();
    jQuery(window).bind("resize", {}, function () { documentResize(); });

    InitConnectionTest();

    function getKey(evt) {
        evt = (evt) ? evt : (window.event) ? event : null;
        if (evt) {
            var cCode = (evt.charCode) ? evt.charCode : ((evt.keyCode) ? evt.keyCode : ((evt.which) ? evt.which : 0));
            return cCode;
        }
    }

    if (isBrowserCorrect) {
        jQuery("#InputInformationBox input").focus(function () { jQuery(jQuery(this).parent()[0]).css("background-image", "url(img/LoginPageNew/inputgreen.png)"); });
        jQuery("#InputInformationBox input").blur(function () { jQuery(jQuery(this).parent()[0]).css("background-image", "url(img/LoginPageNew/inputgrey.png)"); });
        jQuery("#inptPassword").keyup(function (evt) { if (getKey(evt) == 13) { jQuery("#btnLoginOk").triggerHandler("click"); } });
        jQuery("#inptLogin").keyup(function (evt) { if (getKey(evt) == 13) { jQuery("#btnLoginOk").triggerHandler("click"); } });
        jQuery("#btnLoginCancel").click(function () { LoginQtyDialogHide(); });
        jQuery("#btnLoginOk").click(function () { LoginUser(); });
        jQuery("#btnLoginOk").mousedown(function () { jQuery("#btnLoginOk").attr("src", "img/LoginPageNew/enter2.png") });
        jQuery("#btnLoginOk").mouseup(function () { jQuery("#btnLoginOk").attr("src", "img/LoginPageNew/enter1.png") });
        jQuery("#SpanLogoff").click(function () { if (SetSessionParam("logoff") != null) { LogOff(); } });
    }
    else {
        jQuery("#btnLoginOk").attr("src", "img/LoginPageNew/enterGrey.png");
        jQuery("#ErrorMessage").css("display", "block");
    }
    GetUserName(json, "LoginText");
}

function LoginUser() {

    checkForRemember();
    var login = jQuery.trim(jQuery("#inptLogin").val());
    var password = jQuery.trim(jQuery("#inptPassword").val());
    if (login != "") {
        WaitScreenShow();

        jQuery.ajax({
            data: { "action": "login", "login": login, "password": password },
            type: "get",
            url: "./requests/AndersenWebDataGrid.ashx",
            dataType: "json",
            success: function (json) {
                WaitScreenHide();
                if ((json.length == 0 || json[0]["userid"] == "0") && json[0]["error"] == "0") {
                    jQuery.cookie("premiaUserMemo", null);
                    jQuery("#inptPassword").val('');
                    alert('Не правильное имя пользователя или пароль!');
                }
                else if (json[0]["error"] != "0") { 
		status = json[0].status.toLowerCase();
		if (status != 'success') {
	          if (status == 'timeout')
	            alert('Превышено время ожидания ответа от сервера. Возможно, в данный момент у вас отсутствует интернет подключение, или оно очень медленное.');
	          else
	            alert('Премия. Ошибка подключения к базе данных.');
	        }
//			alert('В процессе произошла ошибка:\n' + json[0]["error"]); 
		}
                else {
                    UserData.Save(json[0]["userid"], json[0]["username"], json[0]["userfilialid"], json[0]["kitpages"], json[0]["menu"], password);
                    SetSessionParam("login");
                    var firstPage = json[0]["menu"].split('|')[0].split(';')[1];
                    if (firstPage) { document.location.assign(firstPage); }
                    else { alert("Вам не доступны страницы"); document.location.assign('News.htm'); }
                    LoginText.innerText = "Привет, " + json[0]["username"] + "!";
                }
            },
            error: function (obj) { WaitScreenHide(); alert('Премия. Ошибка подключения к базе данных. Превышен интервал ожидания. Проверьте подключение к интернету.'); }
        });
    }
    else {
        alert("Заполните все поля!");
    }
}

function documentResize() {
    if (document.body.clientWidth > 300) {
        jQuery("#divForm").css("width", document.body.clientWidth);
        jQuery("#divMirror").css("width", document.body.clientWidth);
    }
    if (document.body.clientHeight > 400) {
        jQuery("#divForm").css("height", (document.body.clientHeight * (3 / 5)));
        jQuery("#divMirror").css("height", (document.body.clientHeight * (2 / 5)));
    }
}


