﻿/// <reference path="../ws/CommonServices.asmx" />
/// <reference path="jquery/jquery-1.4.1-vsdoc.js"/>
/// <reference path="main_panel.js" />
/// <reference path="resources.js" />

var d = document;
d.ce = d.createElement;

// ===================== Blank Objects ==========================
var bTbl = d.ce('table');
function getBTbl() { return bTbl.cloneNode(false); }

var bThead = d.ce('thead');
function getBThead() { return bThead.cloneNode(false); }

var bTR = d.ce('tr');
bTR.cn = bTR.cloneNode;
function getBTR() { return bTR.cloneNode(false); }

var bTH = d.ce('th');
function getBTH() { return bTH.cloneNode(false); }

var bTD = d.ce('td');
function getBTD() { return bTD.cloneNode(false); }

var bTbody = d.ce('tbody');
function getBTbody() { return bTbody.cloneNode(false); }

var bDiv = d.ce('div');
function getBDiv() { return bDiv.cloneNode(false); }

var bSpan = d.ce('span');
function getBSpan(t) {
    var v = bSpan.cloneNode(false);
    if (t) $(v).text(t);
    return v;
}

var bUl = d.ce('ul');
function getBUl() { return bUl.cloneNode(false); }

var bLi = d.ce('li');
function getBLi() { return bLi.cloneNode(false); }

var bA = d.ce('a');
function getBA() { return bA.cloneNode(false); }

var bImg = d.ce('img');
function getBImg() { return bImg.cloneNode(false); }

var bLbl = d.ce('label');
function getBLbl() { return bLbl.cloneNode(false); }

var bHr = d.ce('hr');
function getBHr() { return bHr.cloneNode(false); }

var bInput = d.ce('input');
function getBInput(tp) {
    var i = bInput.cloneNode(false);
    if (tp) $(i).attr("type", tp);
    return i;
}

// =============================================================

var $sRes = {
    load_ma: {
        1033: 'loading microsoft ajax module',
        1049: 'загрузка модуля microsoft ajax',
        1065: ' microsoft ajax بار گیری مودول ',
        1067: 'microsoft ajax մոդուլի բեռնում'
    },
    load_common: {
        1033: 'loading common classes module',
        1049: 'загрузка модуля основных классов',
        1065: 'بارگیری کلاسسهای اصلی ',
        1067: 'Հիմնական կլասսերի մոդուլի բեռնում։'
    },
    load_main_panel: {
        1033: 'loading main panel module',
        1049: 'загрузка модуля основной панели',
        1065: 'بارگیری مودول پانل اصلی',
        1067: 'Հիմնական պանելի մոդուլի բեռնում։'
    },
    load_jquery_plugins: {
        1033: 'loading jquery plugins',
        1049: 'загрузка плагинов jquery',
        1065: '',
        1067: ''
    },
    load_common_controls: {
        1033: 'loading ui common controls',
        1049: 'بارگیری رابط مدیریت  ایندترفیس',
        1065: 'loading ui common controls',
        1067: 'Ինտերֆեյսի ղեկավարման գործիքների բեռնում։'
    },
    load_error: {
        1033: 'an error accured during module load',
        1049: 'в процессе загрузки модулей произошла ошибка',
        1065: 'جطا در طی بار گیری مودول',
        1067: 'Մոդուլի բեռնման ընթացքում տեղի է ունեցել սխալ։'
    },
    load_restart: {
        1033: 'restarting modules load process in 5 sec.',
        1049: 'процес загрузки модулей будет перезапущен через 5 сек.',
        1065: 'مودول را دو باره بارگیری خواند شد بعد از 5 ثانیه',
        1067: 'Մոդուլի բեռնման ընթացքը կվերսկսվի 5 վայրկյանից։'
    },
    session_reques: {
        1033: 'session request',
        1049: 'запрос сессии',
        1065: 'استعلام سیسسی',
        1067: 'Սեսսիայի հարցում'
    },
    session_reques_error: {
        1033: 'an error accured during request',
        1049: 'ошибка запроса сессии',
        1065: 'خطای استعلام سیسسی',
        1067: 'Սեսսիայի հարցման սխալ'
    },
    session_reques_restart: {
        1033: 're requesting session in 10 second',
        1049: 'повторный запрос сессии через 10 секунд',
        1065: 'استعلام مکرر سیسسی بعد از 10 ثانیه',
        1067: 'Սեսսիայի կրկնակի հարցում 10 վայրկյանից'
    },
    session_request_login: {
        1033: 'user access verification',
        1049: 'проверка авторизации пользователя',
        1065: 'تحقیق مجوز کاربر ',
        1067: 'Օգտագործողի մուտքի թույլտվության ստուգում'
    },
    session_request_login_eror: {
        1033: 'user access verification error',
        1049: 'ошибка проверки авторизации пользователя',
        1065: 'خطای بررسی محوز کاربر ',
        1067: 'Օգտագործողի մուտքի թույլտվության  ստուգման սխալ'
    },
    session_request_login_retry: {
        1033: 're requesting user access verification in 10 second',
        1049: 'повторный запрос проверки авторизации пользователя через 10 секунд',
        1065: 'استعلام مکرر برای بررسی مجوز کاربر بعد از 10 ثانیه',
        1067: 'Օգտագործողի մոտքի թույտվության կրկնակի ստուգում 10 վայրկյանից'
    }
}




// =========================== Management objects ===================================

var $C = {
    BGUID: '00000000-0000-0000-0000-000000000000'
}

var $S = new function () {      // Current session management object
    this.h = new function () {
        this.sid = $C.BGUID;
        this.lcid = 1049;
    }
    this.getH = function () {
        var h = new Unify.v3.Common.WCFService.UnifyWCFRequestHeader();

        h.LCID = this.h.lcid;
        h.SID = this.h.sid;

        return h;
    }
}

var $A = new function () {      // Application management objects
    this.modules = {
        ma: { loading: false, loaded: false, data: null, arg: null, source: 'js/ajax/ma.js',
            open: function () { return null; }
        }, // microsoft ajax
        mainPanel: { loading: false, loaded: false, data: null, arg: null, source: 'js/main_panel.js',
            open: function () { return null; }, template: 'templates/main_panel.xml'
        }, // main panel of the UI
        common: { loading: false, loaded: false, data: null, arg: null, source: 'js/ajax/common.js',
            open: function () { return null; }
        }, // common classes and definitions
        ajax_common_controls: { loading: false, loaded: false, data: null, arg: null, source: ['js/ajax/common_controls.js', 'js/ajax/eventLists.js', 'js/ajax/betGroups.js'],
            open: function () { }, template: 'templates/common_controls.xml'
        }, // common controls classes
        common_controls: { loading: false, loaded: false, data: null, arg: null, source: 'js/controls_cache.js',
            open: function () { }
        }, // common controls classes
        jqueryPlugins: { loading: false, loaded: false, data: null, arg: null, source: ['js/jquery/jquery.numberformatter-1.2.1.min.js', 'js/jquery/jquery-ui-1.8.9.custom.min.js', 'js/jquery/jquery.backgroundPosition.js'],
            open: function () { }
        },
        homepage: { loading: false, loaded: false, data: null, arg: null, source: 'js/modules/toto_home_page.js',
            open: function (e) {
                var p = new Unify.v3.UI.Pages.TotoHomePage(e);
                p.initialize();
                return p;
            }
        },
        eventspage: { loading: false, loaded: false, data: null, arg: null, source: 'js/modules/toto_events_page.js',
            open: function (e) {
                var p = new Unify.v3.UI.Pages.TotoEventsPage(e);
                p.initialize();
                return p;
            }
        },
        aboutuspage: { loading: false, loaded: false, data: null, arg: null, source: 'js/modules/about_us_page.js',
            open: function (e) {
                var p = new Unify.v3.UI.Pages.TotoAboutUsPage(e);
                p.initialize();
                return p;
            }
        },
        helppage: { loading: false, loaded: false, data: null, arg: null, source: 'js/modules/help_page.js',
            open: function (e) {
                var p = new Unify.v3.UI.Pages.TotoHelpPage(e);
                p.initialize();
                return p;
            }
        },
        totolivepage: { loading: false, loaded: false, data: null, arg: null, source: 'js/modules/toto_live_events_page.js',
            open: function (e) {
                var p = new Unify.v3.UI.Pages.TotoLiveEventsPage(e);
                p.initialize();
                return p;
            }
        },
        totoresultspage: { loading: false, loaded: false, data: null, arg: null, source: 'js/modules/toto_results_page.js',
            open: function (e) {
                var p = new Unify.v3.UI.Pages.TotoResultsPage(e);
                p.initialize();
                return p;
            }
        },
        totosearchpage: { loading: false, loaded: false, data: null, arg: null, source: 'js/modules/toto_search_page.js',
            open: function (e) {
                var p = new Unify.v3.UI.Pages.TotoSearchPage(e);
                p.initialize();
                return p;
            }
        },
        contactpage: { loading: false, loaded: false, data: null, arg: null, source: 'js/modules/contact_page.js',
            open: function (e) {
                var p = new Unify.v3.UI.Pages.TotoContactPage(e);
                p.initialize();
                return p;
            }
        },
        forgotpasswordpage: { loading: false, loaded: false, data: null, arg: null, source: 'js/modules/forgot_password_page.js',
            template: 'templates/forgot_password_page.xml',
            open: function (e) {
                var p = new Unify.v3.UI.Pages.TotoForgotPasswordPage(e);
                p.initialize();
                return p;
            }
        },
        registrationpage: { loading: false, loaded: false, data: null, arg: null, source: 'js/modules/toto_registration_page.js',
            template: 'templates/toto_registration_page.xml',
            open: function (e) {
                var p = new Unify.v3.UI.Pages.TotoRegistrationPage(e);
                p.initialize();
                return p;
            }
        },
        registrationcompletecheckemail: { loading: false, loaded: false, data: null, arg: null, source: 'js/modules/reagistration_succeeded_check_email_page.js',
            open: function (e) {
                var p = new Unify.v3.UI.Pages.RegistrationCompleteCheckEmail(e);
                p.initialize();
                return p;
            }
        },
        confirmemail: { loading: false, loaded: false, data: null, arg: null, source: 'js/modules/email_confirmation_page.js',
            open: function (e) {
                var p = new Unify.v3.UI.Pages.EmailConfirmationPage(e);
                p.initialize();
                return p;
            }
        },
        eventsSchedule: { loading: false, loaded: false, data: null, arg: null, source: 'js/modules/eventsSchedule.js',
            template: 'templates/eventsSchedule.xml',
            open: function (e) {
                var p = new Unify.v3.UI.Pages.EventsSchedulePage(e);
                p.initialize();
                return p;
            }
        },
        myAccount: { loading: false, loaded: false, data: null, arg: null, source: 'js/modules/myAccount_page.js',
            template: 'templates/myAccount_page.xml',
            open: function (e) {
                var p = new Unify.v3.UI.Pages.MyAccountPage(e);
                p.initialize();
                return p;
            }
        },
        myAccount_betsTab: { loading: false, loaded: false, data: null, arg: null, source: 'js/modules/myAccount_Bets_page.js',
            template: 'templates/myAccount_Bets_page.xml',
            open: function (e) {
                var p = new Unify.v3.UI.Pages.MyAccountPage.BetsTab(e);
                p.initialize();
                return p;
            }
        },
        myAccount_operationsTab: { loading: false, loaded: false, data: null, arg: null, source: 'js/modules/myAccount_Operations_page.js',
            template: 'templates/myAccount_Operations_page.xml',
            open: function (e) {
                var p = new Unify.v3.UI.Pages.MyAccountPage.OperationsTab(e);
                p.initialize();
                return p;
            }
        },
        myAccount_paymentsTab: { loading: false, loaded: false, data: null, arg: null, source: 'js/modules/myAccount_Payments_page.js',
            template: 'templates/myAccount_Payments_page.xml',
            open: function (e) {
                var p = new Unify.v3.UI.Pages.MyAccountPage.PaymentsTab(e);
                p.initialize();
                return p;
            }
        },
        myAccount_payoutsTab: { loading: false, loaded: false, data: null, arg: null, source: 'js/modules/myAccount_Payouts_page.js',
            template: 'templates/myAccount_Payouts_page.xml',
            open: function (e) {
                var p = new Unify.v3.UI.Pages.MyAccountPage.PayoutsTab(e);
                p.initialize();
                return p;
            }
        },
        myAccount_privateDataTab: { loading: false, loaded: false, data: null, arg: null, source: 'js/modules/myAccount_PrivateData_page.js',
            template: 'templates/myAccount_PrivateData_page.xml',
            open: function (e) {
                var p = new Unify.v3.UI.Pages.MyAccountPage.PrivateDataTab(e);
                p.initialize();
                return p;
            }
        },
        myAccount_changePasswordTab: { loading: false, loaded: false, data: null, arg: null, source: 'js/modules/myAccount_ChangePassword_page.js',
            template: 'templates/myAccount_ChangePassword_page.xml',
            open: function (e) {
                var p = new Unify.v3.UI.Pages.MyAccountPage.ChangePasswordTab(e);
                p.initialize();
                return p;
            }
        },
        calculator: { loading: false, loaded: false, data: null, arg: null, source: ['js/modules/ticket_system.js', 'js/modules/calculator_page.js'],
            template: 'templates/calculator_page.xml',
            open: function (e) {
                var p = new Unify.TOTO.UI.Controls.Calculator(e);
                p.initialize();
                return p;
            }
        },
        notifications: { loading: false, loaded: false, data: null, arg: null, source: 'js/modules/notifications.js',
            template: 'templates/notifications.xml',
            open: function (e) {
                var p = new Unify.v3.UI.Pages.NotificationsPage(e);
                p.initialize();
                return p;
            }
        },
        liveEvents: { loading: false, loaded: false, data: null, arg: null, source: ['js/ajax/live_events.js', 'js/modules/live_bets.js'],
            template: 'templates/liveEvents.xml'
        },
        ticket: { loading: false, loaded: false, data: null, arg: null, source: ['js/modules/ticket_system.js', 'js/modules/ticket.js'],
            template: 'templates/ticket.xml',
            open: function (e) {
                var p = new Unify.TOTO.UI.Controls.Ticket(e);
                p.initialize();
                return p;
            }
        },
        liveResults: { loading: false, loaded: false, data: null, arg: null, source: 'js/modules/results_page.js',
            template: 'templates/results.xml',
            open: function (e) {
                var p = new Unify.v3.UI.Pages.ResultsPage(e);
                p.initialize();
                return p;
            }
        }
    }
    this.startup_modules = {
        0: {
            n: 'ma',
            m: $sRes.load_ma[$S.h.lcid]
        },
        1: {
            n: 'common',
            m: $sRes.load_common[$S.h.lcid]
        },
        2: {
            n: 'common_controls',
            m: $sRes.load_common_controls[$S.h.lcid]
        },
        3: {
            n: 'ajax_common_controls',
            m: $sRes.load_common_controls[$S.h.lcid]
        },
        4: {
            n: 'mainPanel',
            m: $sRes.load_main_panel[$S.h.lcid]
        },
        5: {
            n: 'jqueryPlugins',
            m: $sRes.load_jquery_plugins[$S.h.lcid]
        }
    }
    this.load = function (module, onSuccess, onFailure) {
        var m = this.modules[module];
        var jsIndex = 0;
        if (!m.loading && !m.loaded) {
            m.loading = true;
            var jsLoader = function () {
                if (typeof (m.source) == 'string') {
                    $.getScript(m.source, function (data, textStatus) {
                        m.data = data;
                        m.loaded = true;
                        m.loading = false;
                        onSuccess(m.data, textStatus, XMLHttpRequest);
                    });
                }
                else {
                    $.getScript(m.source[jsIndex], function (data, textStatus) {
                        if (jsIndex < m.source.length - 1) {
                            jsIndex++;
                            jsLoader();
                        }
                        else {
                            m.data = data;
                            m.loaded = true;
                            m.loading = false;
                            onSuccess(m.data, textStatus, XMLHttpRequest);
                        }
                    });
                }
            }
            var cache = $A.debug ? false : true;
            if (m.template) {
                $.ajax({
                    async: true,
                    cache: cache,
                    dataType: 'xml',
                    ifModified: true,
                    url: 'themes/' + this.theme + '/' + m.template,
                    timeout: 40000,
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        m.loading = false;
                        onFailure(XMLHttpRequest, textStatus, errorThrown);
                    },
                    success: function (data, textStatus, XMLHttpRequest) {
                        m.template = data;
                        //m.loaded = true;
                        //m.loading = false;
                        jsLoader();
                    }
                });
            }
            else {
                jsLoader();
            }



        }

        if (m.loaded) onSuccess(m.data);
    }
    this.theme = 'toto.v3';
}


var $W = new function () {      // web services requests object
    var t = this;

    t.svc = {                // services of the system
        Common: { path: 'ws/CommonServices.asmx' },
        Registration: { path: 'ws/RegistrationServices.asmx' },
        Session: { path: 'ws/SessionServices.asmx' },
        Data: { path: 'ws/DataServices.asmx' }
    }

    t._res = {
        add_req: {
            1033: 'Adding request to web requests stack: ',
            1049: 'Добавление запроса в общий стек запросов: ',
            1065: 'اضافه کردن استعلام در تسم استعلام وب',
            1067: 'Հարցման ավելացում հարցումներ ընդհանուր սթեյկ։ '
        },
        find_req: {
            1033: 'looking for request to invoke',
            1049: 'поиск очередного запроса для запуска',
            1065: 'جستجو اتعلام برای پرتاب',
            1067: 'поиск очередного запроса для запуска'
        },
        inv_req: {
            1033: 'invoke request: ',
            1049: 'запуск запроса: ',
            1065: 'پرتاب استعلام: ',
            1067: 'запуск запроса: '
        },
        del_req: {
            1033: 'remove request from web requests stack: ',
            1049: 'удаление запроса из стека веб запросов: ',
            1065: 'برداشت استعلام ار ستک استعلام وب',
            1067: 'Վեբ հարցումների ստեյկից հարցման հեռացում։ '
        },
        cnt_req: {
            1033: 'requests in stack: ',
            1049: 'количество запросов в стеке: ',
            1065: 'تعداد استعلام در ستک ',
            1067: 'Ստեյկում հարցումների քանակը։'
        }

    }


    t.MTC = 3; // maximum threads count
    t._tc = 0; // current threads count
    t._c = 0;  // counter of the requests
    t.PRIORITY = {BG_PROCESS:0, BG_UI_PROCESS:1, SIMPLE_WEB_REQUEST:2, PRIORITY_WEB_REQUEST:3, HIGHPRIORITY_UIWEB_REQUEST:4};
    t._r = {
        0: {}, // background processes
        1: {}, // background UI processes
        2: {}, // simple web requests
        3: {}, // priority web requests
        4: {}  // hight priority UI web requests
    }; // requests

    t.WebServiceProxy = null;

    t.initTimer = function () {
        $T1.add_onTickEvent(t.start);
    }

    this.requestComplete = function (uc) {
        t._tc--;
        var th = uc.split(',');

        $dbg.add(t._res.del_req[$S.h.lcid] + uc);
        $dbg.add(t._res.cnt_req[$S.h.lcid] + t._tc);
        try {
            delete (t._r[th[0]][th[1]]);
        } catch (e) {

        }

        // if (th[0] > 1) t.start();

        t.start();
    }

    this.start = function () {
        if (this._tc >= this.MTC) return;

        var br = false;

        $dbg.add(t._res.find_req[$S.h.lcid]);

        for (var i = 4; i >= 0; i--) {
            for (var tr in t._r[i]) {
                var ti = t._r[i][tr];
                if (ti.n) {
                    t._tc++;
                    $dbg.add(t._res.inv_req[$S.h.lcid] + tr + ' ' + ti.s + ' ' + ti.m + ' ' + i);
                    $dbg.add(t._res.cnt_req[$S.h.lcid] + t._tc);
                    ti.n = false;
                    t.WebServiceProxy.makeRequest(ti.s, ti.m, ti.p,
                function (data, userContext, methodName) {
                    t.requestComplete(userContext.thd);
                    if (ti.onS) ti.onS(data, userContext.context, methodName);
                },
                function (error, userContext, methodName) {
                    t.requestComplete(userContext.thd);
                    if (ti.onF) ti.onF(error, userContext.context, methodName);
                }, ti.uc);
                    if (i > 1) { setTimeout(function () { t.start(); }, 50); }
                    br = true;
                    break;
                }
            }
            if (br) break;
        }
    }

    this.request = function (service, method, params, onSuccess, onFailure, priority, userContext) {
        if (!params) params = {};
        if (typeof (priority) === 'undefined') priority = 2;

        var c = t._c++;

        $dbg.add(t._res.add_req[$S.h.lcid] + c + ' ' + service + ' ' + method + ' ' + priority);

        t._r[priority][c] = { s: t.svc[service].path, m: method, p: params, onS: onSuccess, onF: onFailure, uc: { thd: priority + ',' + c, context: userContext }, n: true };

        if (priority > 1) t.start();
    }
}

var $L = new function () {
    this.li = false; // is logged in
    this.st = null;  // user status control
    this.un = ''; // user name
}

var $D = new function () {      // Application Data cache store
    this.ev = {};       // events cache
    this.lev = {};      // live events cache
    this._locations = {};

    this.getLocations = function (postback) {
        var t = this;

        if (t._locations[$S.h.lcid]) {
            postback(t._locations[$S.h.lcid]);
            return;
        }

        $W.request('Data', 'GetLocations', { opt: 222 },
    function (res) {
        t._locations[$S.h.lcid] = res;
        postback(res);
    },
    function (ex) {
        setTimeout(function () { t.getLocations(postback) }, 5000);
    });
    }

}

var $dbg = new function () {
    this.e = false;
    this.m = [];
    this.c = 25;
    this.p = null;
    this.add = function (m) {
        if (!this.e) return;
        this.m[this.m.length] = m;
        for (var i = this.c, j = this.m.length; i < j; i++) {
            Array.removeAt(this.m, 0);
        }
        if (this.p) $(this.p).html(this.m.join('<br />'));
    }
    this.hide = function () {
        if (this.p) $(this.p).hide()
    }
    this.show = function () {
        if (this.p) $(this.p).show()
    }

}


// ====================================================================

// ===== startup function. starts after default.aspx is loaded ========

var afterRootInit = null;

function WebStartUp(postback) {

    $dbg.p = document.getElementById('dbg');
    $dbg.e = true;
    afterRootInit = postback;
    LoadAllStartUpModules(0, RequestGuestSession);
}

function RequestGuestSession() {

    if ($S.h.sid == $C.BGUID) {
        $dbg.add($sRes.session_reques[$S.h.lcid]);
        $W.request('Session', 'CreateGuestSession', null,
            function (s) {
                $S.h.sid = s;
                GetUserName();
            },
            function (ex) {
                $dbg.add($sRes.session_reques_error[$S.h.lcid]);
                $dbg.add(ex._message);
                $dbg.add($sRes.session_reques_restart[$S.h.lcid]);
                setTimeout(RequestGuestSession, 10000);
            });
    }
    else {
        GetUserName();
    }
}

function GetUserName() {
    $dbg.add($sRes.session_request_login[$S.h.lcid]);
    $W.request('Session', 'GetUserLogin', null,
    function (un) {
        $L.un = un;
        $L.li = (un !== '');
        InitRootPanel();
    },
    function (ex) {
        $dbg.add($sRes.session_request_login_eror[$S.h.lcid]);
        $dbg.add($sRes.session_request_login_retry[$S.h.lcid]);
        setTimeout(GetUserName, 10000);
    });
}

function InitRootPanel() {
    $R.initialize();
    $(document.body).html($R.get_element());
    $R.reload();
    if (afterRootInit) afterRootInit();
}

function LoadAllStartUpModules(i, postback) {
    if (typeof ($A.startup_modules[i]) === 'undefined') {
        postback();
        return;
    }

    $dbg.add($A.startup_modules[i].m);
    $A.load($A.startup_modules[i].n,
    function () { // on success
        LoadAllStartUpModules(i + 1, postback)
    },
    function () { // on failure
        RetryLoadAllStartUpModules(postback)
    });
}

function RetryLoadAllStartUpModules(postback) {
    $dbg.add($sRes.load_error[$S.h.lcid]);
    $dbg.add($sRes.load_restart[$S.h.lcid]);
    setTimeout(function () { LoadAllStartUpModules(0, postback) }, 5000);
}
// ====================================================================

function debug_obj(o, o1, o2, o3, o4, o5) {
    var aaa = o;
}

