﻿//Author - Korochkin Vadim (2009) qstream@ngs.ru


//notation: 
//пространства имен - с большой буквы
//объекты, методы - с маленькой
//приватные методы и объекты  - с подчеркивания и с маленькой


var QSystem =
{

    //------ objects ------------
    Page: {},
    Control: {},
    Validation: {},
    Thread: {},
    Events: {},



    //------ methods ------------       


    create: function() {
        $(function() {
            setTimeout("QSystem.initialize()", 100);
        }
        );
    },

    _readyFn: [],
    isReady: false,

    onReady: function(fn) {
        if (!QSystem.isReady) {
            QSystem._readyFn.push(fn);
        }
        else {
            fn();
        }
    },

    _onReady: function() {


        for (var i = 0; i < QSystem._readyFn.length; i++) {
            QSystem._readyFn[i]();
        }
        _readyFn = null;

    },

    requestManager: null,

    initialize: function() {


        QSystem.requestManager = Sys.WebForms.PageRequestManager.getInstance();


        for (var key in QSystem) {

            if ((typeof QSystem[key] == 'object') && ((typeof QSystem[key]._init) == 'function')) {
                QSystem[key]._init();
            }
        }

        QSystem.isReady = true;
        QSystem._onReady();
    }
};






QSystem.Events =
{
    CreateEvent: function(eventName, owner) {
        /// <summary>
        /// 1111
        /// </summmary>
        /// <param name="eventName" type="String">Human event name</param>


        if (!eventName) {
            alert("Must init eventName!");
            return;
        }

        var event = {
            _stateOn: true,

            on: function() {
                _stateOn = true;
            },
            off: function() {
                _stateOn = false;
            },
            _subscribers: [],
            eventName: eventName,

            push: function(obj) {
                if (typeof (obj.fn) == 'function')
                    this._subscribers.push(obj);
                else
                    Audit.exception('"fn" from selectedNodeChanged is not a function!');
            },

            run: function(args) {

                if (this._subscribers) {

                    var needEvery = (!owner._stateOn || !this._stateOn);
                    this._run(args, needEvery);
                }
            },

            _run: function(args, needEvery) {
                for (var i = this._subscribers.length - 1; i >= 0; i--) {

                    var obj = this._subscribers[i]
                    var fn = obj.fn;

                    if (needEvery && !obj.every) continue;

                    if (fn && typeof (fn) == 'function') {
                        try {
                            var result = fn(owner, [args]); // если возвращено false - прерываем цепочку
                            if (result != undefined && result == false) return;
                        }
                        catch (e) {
                            Audit.exception('Event_subscribers_Run-ERROR in ' + fn + ' \nException:' + e.message);
                        }
                    }
                    else
                        Audit.exception('fn(' + fn.toString() + ') is not a function in ' + this.eventName + ' event!');
                }
            }
        };

        owner[eventName] = function(fn, every) { event.push({ fn: fn, every: every }); return this; };
        return event;
    }
};

QSystem.Page =
    {

        onLoad: function(updatepanelId, fn) {
            $(function() {
                SQSystem.requestManager.add_beginRequest(//add_pageLoading(
                      function(sender, e) {
                          var updated = e.get_panelsUpdating(); //!!!??
                          var i = 0;
                          for (i = 0; i < updated.length; i++) {
                              var currentPanel = $(updated[i]);
                              if (updatepanelId == currentPanel.attr('id')) {

                                  fn(currentPanel, sender, e);
                              }
                          }
                      }
              );
            }
               );
        },

        onLoaded: function(updatepanelId, fn) {
            $(function() {

                QSystem.requestManager.add_pageLoaded(function(sender, e) {
                    var updated = e.get_panelsUpdated();
                    var i = 0;
                    for (i = 0; i < updated.length; i++) {
                        var currentPanel = $(updated[i]);
                        if (updatepanelId == currentPanel.attr('id')) {
                            fn(currentPanel, sender, e);
                        }
                    }

                });
            }
             );
        },

        everyLoad: function(fn) {
            $(function() {
                QSystem.requestManager.add_endRequest(fn);
                fn();
            }
                );
        },

        everyPreLoad: function(fn) {
            $(function() {
                QSystem.requestManager.add_beginRequest(fn);
                fn();
            }
                );
        }
    };


QSystem.Control =
    {
        _init: function() {
            QSystem.requestManager.add_beginRequest(QSystem.Control._onRequest);
        },

        _list: new Array(),

        everyPostBack: function(controlId, fn) {
            var onPB = function() {
                QSystem.Control.onPostBack(controlId, fn);
            }

            QSystem.Page.everyLoad(onPB);
        },

        _onRequest: function(sender, e) {

            var initiator = e.get_postBackElement();
            var initiatorId = $(initiator).attr('id');

            for (var i = 0; i < QSystem.Control._list.length; i++) {

                var c = QSystem.Control._list[i];

                if (c.controlId == initiatorId) {
                    c.fn($(c.controlId), sender, e);
                }
            }
        },

        onPostBack: function(id, fn) {

            var obj = { controlId: id, fn: fn };

            if (Array.indexOf(QSystem.Control._list, obj) == -1)
                QSystem.Control._list.push(obj);


        },

        remove_onPostBack: function(jcontrol, fn) {
            Array.Delete(QSystem.Control._list, { control: jcontrol, fn: fn })
        },


        validate: function(jObj) {
            jObj.each(function() {
                if (this.Validators) {
                    $(this.Validators).each(function() { ValidatorValidate(this); });
                }
            });
        },

        enableValidation: function(jObj, enable) {
            jObj.each(function() {
                if (this.Validators) {
                    $(this.Validators).each(function() { ValidatorEnable(this, enable); });
                }
            });
        }
    };


QSystem.Validation =
    {
        _init: function() {
            //QSystem.Page.everyLoad(QSystem.Validation.CheckPageValidators);
        },

        CheckPageValidators: function() {
            $(Page_Validators).each(
            function() {
                var notExists = !document.getElementById(this.id);
                // console.assert(notExists, false);
                if (notExists) {
                    Array.remove(Page_Validators, this);
                };
            });
        }
    };


QSystem.Thread =
    {
        _init: function()
        { },

        /// имеются ограничения на контекст
        start: function(fn, ms) {
            if (!ms) ms = 1;

            var code = 'QSystem.Thread._tempCode = ' + fn;
            eval(code);
            setTimeout('QSystem.Thread._tempCode();', ms);
        }
    };

window.isNull = function(obj, value) {
    //if (obj) return obj;
    //return value ? value : '';

    return (typeof (obj) == "boolean") ? obj : (obj ? obj : (value != undefined ? value : ''))
}

window.isnull = window.isNull;


// this.QSystem.UpdateProgress:
//    {
//        ShowProgress: function(updatePanel)
//       {        
//            var wraper =  $('#' + updatePanel).parent();
//            wraper.addClass('InProgress');    
//        },
//        
//        HideProgress: function(updatePanel)
//       {        
//            var wraper =  $('#' + updatePanel).parent();
//            wraper.removeClass('InProgress');    
//        },
//        
//        attachProgress: function(updatePanel) 
//        {
//              $(function() { });
//               QSystem.Page.onLoaded(updatePanel, QSystem.updateProgress.ShowProgress);

//                
//                var wraper =$('<div role="progress">...</div>');//создаем wraper
//                $('#' + updatePanel).wrap(wraper);
//                
//                QSystem.Page.onLoaded(updatePanel, function(updatePanel, sender, e) {
//                    //убрать прогресс
//                   // wraper.removeClass('InProgress');
//                    }
//                });
//        }
//    }





//QSystem.updateProgress.attachProgress().
//this.manager = new Manager();
//var a = new Array();


//QSystem.updateProgress.





// очень нужная статья http://msdn.microsoft.com/ru-ru/magazine/cc163413.aspx
//http://www.sql.ru/forum/actualthread.aspx?tid=640076
//cool color:#edf5fb
//http://ymik.habrahabr.ru/blog/61750/
//http://www.feng-gui.com/default.aspx
//http://ymik.habrahabr.ru/blog/57685/
//http://ymik.habrahabr.ru/blog/60426/
//http://ymik.habrahabr.ru/blog/57685/
//http://ymik.habrahabr.ru/blog/57684/
//http://ymik.habrahabr.ru/blog/57683/




jQuery.fn.onPostBack = function(fn) {

    $(this).each(function() {
        QSystem.Control.onPostBack($(this).attr('id'), fn);
    });

    return this;
};

jQuery.fn.validate = function() {
    QSystem.Control.validate(this);
    return this;
}
jQuery.fn.enableValidation = function(enable) {
    QSystem.Control.enableValidation(this, enable);
    return this;
}

jQuery.fn.visible = function(value) {
    if (value != undefined) {
        if (value) this.show()
        else this.hide();

        return this;
    }

    return this.css('display') != 'none';
};

$(QSystem.create);


function vsSize() {
    console.log($('#__VIEWSTATE').attr('value').length / 1024 + ' kb');
}

//$(

//function() {

//    setTimeout("alert(10); Sys.Application.add_load(    function() {       QSystem.Page.onLoaded('ctl00_ContentPlaceHolder1_upMessage',                function() {                    $('#ctl00_ContentPlaceHolder1_lblMessage').fadeOut(5000);                }             );        }      );", 1000)
//});


///QSystem.onReady(function() { QSystem.Page.onLoaded('ctl00_ContentPlaceHolder1_upMessage'); alert('111'); });