Type.registerNamespace('Devy.UI');

Devy.UI.Buscador = function () {
    Devy.UI.Buscador.initializeBase(this);

    //Miembros
    this._Parent = null;
    this._Container = null;

    this._Nombre = null;

    this._ServicePortal = null;

    this._FormFieldDescriptors = null;
    this._FormContainer = null;
    this._Form = null;

    this._ListContainer = null;
    this._PagesIndexContainer = null;

    this._events = null;

    this._PAGES = new Array();
    this._criteria = null;
    this._ObjectsType = "articulos;eventos";
    this._RecordsPerPage = 24;
    this._HtmlViewTemplateName = "reducido-busquedas";

    this._PagesCount = 0;

    this._CurrentPos = 0;
    this._TotalCount = 0;
    this._PagesIndex = null;


    this._Lista = null;

    this._NoRecords = false;
    this._NoRecordsLabel = null;

    this._LoadRecordsOnStart = false;

    this._FormFieldDescriptors = null;
}

Devy.UI.Buscador.prototype = {
    //*********************************************************************
    //Publicos
    set_Container: function (value) { this._Container = value; },
    get_Container: function () { return this._Container; },
    set_Parent: function (value) { this._Parent = value; },
    get_Parent: function () { return this._Parent; },

    set_Nombre: function (value) { this._Nombre = value; },
    get_Nombre: function () { return this._Nombre; },

    set_ServicePortal: function (value) { this._ServicePortal = value; },
    get_ServicePortal: function () { return this._ServicePortal; },

    set_ObjectsType: function (value) { this._ObjectsType = value; },
    get_ObjectsType: function () { return this._ObjectsType; },

    set_HtmlViewTemplateName: function (value) { this._HtmlViewTemplateName = value; },
    get_HtmlViewTemplateName: function () { return this._HtmlViewTemplateName; },

    set_RecordsPerPage: function (value) { this._RecordsPerPage = value; },
    get_RecordsPerPage: function () { return this._RecordsPerPage; },

    set_FormFieldDescriptors: function (value) {
        this._FormFieldDescriptors = value;

        if (this._Form) {
            this._Form.set_FieldDescriptors(this.getSafeFormFieldDescriptors());
            this._Form.set_BusinessObject(this.get_FilterCriteria());
        }
    },
    get_FormFieldDescriptors: function () { return this._FormFieldDescriptors; },

    set_FilterCriteria: function (value) {
        this._criteria = value;

        if (this._Form) {
            this._Form.set_BusinessObject(value);
        }
    },
    get_FilterCriteria: function () {
        if (!this._criteria) {
            if (this._CreateNewFilterCriteriaCallBack) {
                this._criteria = this._CreateNewFilterCriteriaCallBack();
            }
            else {
                this._criteria = {};
            }
        }
        return this._criteria;
    },


    set_CSSClass: function (value) { this._CSSClass = value; },
    get_CSSClass: function () { return this._CSSClass; },


    get_NoRecords: function () { return this._NoRecords },

    get_Lista: function () { return this._Lista },

    initialize: function () {
        Devy.UI.Buscador.callBaseMethod(this, 'initialize');

        this._ServicePortal = Devy.UI.BuscadorService;

        this._FormContainer = $('<div class="FormContainer"></div>')[0];
        this._Container.appendChild(this._FormContainer);
        this._initForm(this._FormContainer);

        this._PageIndexContainer = $('<div class="PageIndexContainer"></div>')[0];
        this._Container.appendChild(this._PageIndexContainer);

        this._initPagesIndex(this._PageIndexContainer);
        $(this._PageIndexContainer).append('<div class="clear" />');
        this._initPagesIndex(this._PageIndexContainer);

        this._NoRecordsLabel = $('<p class="NoRecords">No hay resultados para el filtro ingresado...</p>')[0];
        $(this._NoRecordsLabel).hide();
        this._Container.appendChild(this._NoRecordsLabel);

        this._ListContainer = $('<div class="ListContainer"></div>')[0];
        $(this._ListContainer).hide();
        this._Container.appendChild(this._ListContainer);


        this._initLista();

        this._atachEvents();

        if (this._LoadRecordsOnStart)
            this._BeginPageChange(1);
    },

    dispose: function () {
        this._detachEvents();
        Devy.UI.Buscador.callBaseMethod(this, 'dispose');
    },

    _atachEvents: function () {
        var contexto = this;

    },

    _detachEvents: function () {


    },

    //*********************************************************************
    //Event Handlers

    _pagesPageClick: function (s, e) {
        s.get_Parent()._BeginPageChange(e);
    },

    _refreshList: function (newPageNumber) {
        if (!newPageNumber) newPageNumber = this._CurrentPos;
        if (newPageNumber <= 0) newPageNumber = 1;
        this.get_FilterCriteria().RecordsPerPage = this._RecordsPerPage;
        this._PAGES = new Array();
        this._BeginPageChange(newPageNumber);
    },

    _refreshCurrentPage: function () {
        this._EndPageChange(this._CurrentPos);
    },


    //*********************************************************************
    //Mis eventos
    add_rowClick: function (handler) {
        this.get_events().addHandler('rowClick', handler);
    },
    remove_rowClick: function (handler) {
        this.get_events().removeHandler('rowClick', handler);
    },

    add_pageChange: function (handler) {
        this.get_events().addHandler('pageChange', handler);
    },
    remove_pageChange: function (handler) {
        this.get_events().removeHandler('pageChange', handler);
    },

    get_events: function () {
        if (!this._events) {
            this._events = new Sys.EventHandlerList();
        }
        return this._events;
    },

    _raiseEvent: function (eventName, eventArgs) {
        var handler = this.get_events().getHandler(eventName);

        var theEventArgs = null;
        if (handler) {
            if (!eventArgs) {
                theEventArgs = Sys.EventArgs.Empty;
            }
            else {
                theEventArgs = eventArgs;
            }

            handler(this, theEventArgs);
        }
    },

    //Manejo de Paginas
    _BeginPageChange: function (NewPage) {
        if (this._PAGES[NewPage]) {
            this._EndPageChange(NewPage);
        }
        else {
            Devy.Notifications.ShowLoading("Obteniendo resultados...");

            //Invocamos el servicio
            var ServiceData = new Array();
            ServiceData.Requester = this;

            ServiceData.RequestedPage = NewPage;
            ServiceData.Criteria = Devy.Util.ObjectAsFieldArray(this.get_FilterCriteria());
            ServiceData.ObjectsType = this._ObjectsType;
            ServiceData.RecordsPerPage = this._RecordsPerPage;
            ServiceData.HtmlViewTemplateName = this._HtmlViewTemplateName;

            this._ServicePortal.GetResultados(
            this._ObjectsType,
            ServiceData.Criteria,
            this._RecordsPerPage,
            NewPage,
            this._HtmlViewTemplateName,
            this._onGetResultadosServerSuccess, this._onGetResultadosServerError,
            ServiceData);
        }
    },

    _EndPageChange: function (NewPage) {
        this._CurrentPos = NewPage;

        if (this._PAGES[this._CurrentPos]) {

            if (this._PAGES[this._CurrentPos].length >> 0) {
                this._NoRecords = false;
                $(this._NoRecordsLabel).hide();
            }
            else {
                this._NoRecords = true;
                $(this._NoRecordsLabel).show();
            }

            this._PagesIndex.SetUpPages(this._CurrentPos, this._PagesCount, this._RecordsPerPage, this._TotalCount);

            this._Lista.set_DataSource(this._PAGES[this._CurrentPos]);
            $(this._ListContainer).show();
        }
        else {
            $(this._ListContainer).hide();
        }

        //Mandamos pageChange
        var eventDataArgs = {};

        this._raiseEvent('pageChange', eventDataArgs);

        Devy.Notifications.HideLoading();
    },


    _onGetResultadosServerSuccess: function (result, context, methodName) {
        context.Requester._PAGES[context.RequestedPage] = result.Items;
        context.Requester._PagesCount = result.PagesCount;
        context.Requester._TotalCount = result.TotalCount;

        context.Requester._EndPageChange(context.RequestedPage)
    },
    _onGetResultadosServerError: function (error, context, methodName) {
        Devy.Notifications.HideLoading();
        Devy.Notifications.ShowError("GetResultados Error", error.get_message());
    },

    _CreateListViewItemCallBack: function (obj) {
        return obj.HtmlView;
    },

    _initLista: function () {
        var editDelegate = Function.createDelegate(this, function (obj) {
            this._ObjectEdit.BeginEditObject(obj);
        });

        var deleteDelegate = Function.createDelegate(this, function (obj) {
            this._ObjectEdit.BeginDeleteObject(obj);
        });

        this._Lista = $create(Devy.UI.ListView,
        {
            "Parent": this,
            "Container": this._ListContainer,
            "Selectable": false,
            "MultiSelectable": false,
            "CreateListViewItemCallBack": this._CreateListViewItemCallBack
        },
        {},
        {});
    },

    // Init interface helpers
    _initPagesIndex: function (container) {
        this._PagesIndex = $create(Devy.UI.PagesIndex,
        {
            "Parent": this,
            "Container": container,
            "PagesCount": 1,
            "CurrentPage": 1,
            "EntityNamePlural": "resultados"
        },
        { "pageClick": this._pagesPageClick },
        {});
    },

    _initForm: function (container) {
        this._Form = $create(Devy.UI.Forms.Form,
        {
            "Parent": this,
            "Container": container,
            "CSSClass": "BuscadorForm",
            "CommandOKText": "Buscar",
            "ShowCommandCancel": false,
            "BusinessObject": this.get_FilterCriteria(),
            "FieldDescriptors": this.getSafeFormFieldDescriptors()
        },
            { "OKClick": this._formOKClick
            },
            {});
    },

    getSafeFormFieldDescriptors: function () {
        if (this._FormFieldDescriptors)
            return this._FormFieldDescriptors;
        else {
            //Default
            return [
                    {
                        "PropertyName": "ContieneTexto"
                    , "FieldType": "MultilineText",
                        "HeaderText": "Ingrese texto a buscar"
                    }
             ];
        }
    },

    _formOKClick: function (s, e) {
        s.get_Parent()._refreshList(1);
    }
}

Devy.UI.Buscador.registerClass('Devy.UI.Buscador', Sys.Component);
