// управление виджетами
var widgetAPI = {
    widgets: {},
    createWidget: function(id, path, state, params, rendered, contentrendered, tic)
    {
		if(typeof tic == 'undefined')
			tic = '';
        this.widgets[id] = new widgetObject(id, path, state, params, rendered, contentrendered, tic);
        return this.widgets[id];
    },

    removeWidget: function(id)
    {
        delete this.widgets[id];
    },

    closeAll: function()
    {
        for(i in this.widgets)
        {
            if(typeof this.widgets[i] != 'undefined')
                this.widgets[i].show(false);
        }
    },

    openAll: function()
    {
        for(i in this.widgets)
        {
            if(typeof this.widgets[i] != 'undefined')
                this.widgets[i].show(true);
        }
    }
}

//обьект виджета
function widgetObject(id, path, state, params, rendered, contentrendered, tic)
{
    this.id = id;
    this.rendered = rendered;
    this.path = path;
    this.state = state;
    this.params = params;
	this.tic = tic;

    if(rendered == true || contentrendered == true)
    {
        this.configure = $('#container_'+this.id+' .widgetConfigure');
        this.container = $('#container_'+this.id+' .widgetContainer');
        this.content = $('#container_'+this.id+' .widgetContent');
        this.initialized = true;

        $('#container_'+this.id+' .widgetButtonClose').unbind('click');
        $('#container_'+this.id+' .widgetButtonReload').unbind('click');
        $('#container_'+this.id+' .widgetButtonConfigure').unbind('click');

        $('#container_'+this.id+' .widgetButtonClose').bind('click', {obj:this}, function(e){e.data.obj.toggleVisible();});
        $('#container_'+this.id+' .widgetButtonReload').bind('click', {obj:this}, function(e){e.data.obj.reload();});
        $('#container_'+this.id+' .widgetButtonConfigure').bind('click', {obj:this}, function(e){e.data.obj.toggleConfigure();});
    }

    if(rendered == false && contentrendered == false)
        this.loadContainer();

    if(contentrendered == true && rendered == false)
    {
        this.showed = false;
        this.content.css('display', 'none');
    }
}

widgetObject.prototype = {
    id: null,                   // уникальный идентификатор в пределах загруженной страницы
    configure: undefined,       // блок конфигурации
    container: undefined,       // блок контейнера
    content: undefined,         // блок содержимого
    beforeLoad: null,           //
    rendered: false,            // отрендерен блок содержимого?
    initialized: false,         // отрендерен контейнер?
    showed: true,               // показан блок содержимого?
    configureshowed: false,     // показана конфигурация?
    configurerendered: false,   // отрендерена конфигурация?
    path: '',                   // имя виджета
    state: '',                  // текущее состояние
    params: {},                 // дополнительные параметры
	tic: '',

    beforeReload: undefined,
    beforeConfigureApply: undefined,
    beforeConfigureSave: undefined,
    afterConfigureApply: undefined,
    beforeConfigureShow: undefined,
    afterConfigureShow: undefined,
    beforeContainerLoad: undefined,
    beforeContentShow: undefined,
    afterContentShow: undefined,
    beforeHandle: undefined,
    beforeContainerLoaded: undefined,
    afterContainerLoaded: undefined,
    beforeConfigureLoaded: undefined,
    afterConfigureLoaded: undefined,
    beforeLoaded: undefined,
    afterLoaded: undefined,

    addHandler: function(selector, evt, func)
    {
        var obj = $('#container_'+this.id+' '+selector);
        obj.unbind(evt);
        obj.bind(evt, {obj:this}, function(e){func.apply(e.data.obj);});
    },

    // сохранить настройки
    configureApply: function()
    {
        if(jQuery.isFunction(this.beforeConfigureApply))
            this.beforeConfigureApply.apply(this);

        // сбор всех значений из полей контейнера конфигурации имеющих класс widgetFieldToSave
        // формируется строка GET запроса
        var fields = $('#container_'+this.id+' .widgetConfigure .widgetFieldToSave');
        var result = '';
        fields.each(function(i){
            if(this.type == 'checkbox')
            {
                if(this.checked == true)
                {
                    if(result.length > 0) result += '&';
                    result += escape(this.name) + '=' + this.value;
                }
            }
            else if(this.type == 'radio')
            {
                if(this.selected == true)
                {
                    if(result.length > 0) result += '&';
                    result += escape(this.name) + '=' + this.value;
                }
            }
            else
            {
                if(result.length > 0) result += '&';
                result += escape(this.name) + '=' + escape(this.value);
            }
        });

        if(jQuery.isFunction(this.beforeConfigureSave))
            this.beforeConfigureSave.apply(this);

        var __obj = this;

        this.save('configureapply', {params: result}, function(data){__obj.reload();});
        if(jQuery.isFunction(this.afterConfigureApply))
            this.afterConfigureApply.apply(this);

        this.showConfigure(false);
    },

    // скрыть / показать блок настроек
    toggleConfigure: function()
    {
        this.showConfigure(!this.configureshowed);
    },

    // показать блок настроек (true - показать false - скрыть)
    showConfigure: function(show)
    {
        if(jQuery.isFunction(this.beforeConfigureShow))
            show = this.beforeConfigureShow.apply(this, [show]);

        if(show == true && this.configurerendered == false)
        {
            var __obj=this;
            params = this.params;
            params.widgetContainerInit = false;
			params.tic = this.tic;
            this.handleAjax(
                'configure',
                null,
                params,
                function(data){__obj.successConfigureLoad(data);},
                this.failedLoad);
            return;
        }

        if(show == true)
            this.configure.slideDown('normal');
        else
            this.configure.slideUp('normal');

        this.configureshowed = show;

        if(jQuery.isFunction(this.afterConfigureShow))
            this.afterConfigureShow.apply(this, [show]);
    },

    toggleVisible: function()
    {
        this.show(!this.showed);
    },

    reload: function()
    {
        if(jQuery.isFunction(this.beforeReload))
            this.beforeReload.apply(this);

        if(this.showed == false)
        {
            this.rendered = false;
        }
        else
        {
            this.handle(this.state, this.params);
        }
    },

    loadContainer: function()
    {
        if(jQuery.isFunction(this.beforeContainerLoad))
            this.beforeContainerLoad.apply(this);

        if(this.rendered == false)
        {
            var __obj=this;
            params = this.params;
            params.widgetContainerInit = !this.initialized;
            this.handleTo(
                this.state,
                null,
                params,
                function(data){__obj.successContainerLoad(data);});
            return;
        }
    },

    show: function(show)
    {
        if(show) show = true; else show = false;

        if(jQuery.isFunction(this.beforeContentShow))
            show = this.beforeContentShow.apply(this, [show]);

        if(show == true && this.rendered == false)
        {
            var __obj=this;
            params = this.params;
            params.widgetContainerInit = !this.initialized;
            params.widgetContainerShowed = true;
            this.handleTo(
                this.state,
                null,
                params,
                function(data){__obj.successLoad(__obj.content, data);});
            return;
        }

        if(show == true)
        {
            this.content.slideDown('normal');
            $('#container_'+this.id+' .widgetButtonCloseObj').removeClass('widgetButtonCloseClosedImg');
            $('#container_'+this.id+' .widgetButtonCloseObj').addClass('widgetButtonCloseOpenedImg');
        }
        else
        {
            this.content.slideUp('normal');
            $('#container_'+this.id+' .widgetButtonCloseObj').addClass('widgetButtonCloseClosedImg');
            $('#container_'+this.id+' .widgetButtonCloseObj').removeClass('widgetButtonCloseOpenedImg');
        }

        if(this.showed != show)
            this.save('togglevisible', {widgetContainerShowed: show});
        this.showed = show;

        if(jQuery.isFunction(this.afterContentShow))
            this.afterContentShow.apply(this, [show]);
    },

    remove: function()
    {
        widgetAPI.removeWidget(this.id);
    },

    load: function(state, params, success, failed)
    {
        if(typeof(success) == 'undefined')
            return;
        if(typeof(failed) == 'undefined')
            failed = null;
        this.handleAjax(state, null, params, success, failed);
    },

    save: function(state, params, success, failed)
    {
        if(typeof(success) == 'undefined')
            success = null;
        if(typeof(failed) == 'undefined')
            failed = null;
        this.handleAjax(state, null, params, success, failed);
    },

    handle: function(state, params, success, failed)
    {
        this.handleTo(state, this.content, params, success, failed);
    },

    handleTo: function(state, obj, params, success, failed)
    {
        this.state = state;

        var __obj = this;
        if(typeof(success) == 'undefined')
            success = function(data){__obj.successLoad(obj, data);};
        if(typeof(failed) == 'undefined')
            failed = function(){__obj.failedLoad(obj);};

        this.handleAjax(state, this.content, params, success, failed);
    },

    handleAjax: function(state, obj, params, success, failed)
    {
        if(jQuery.isFunction(this.beforeHandle))
            state = this.beforeHandle.apply(this, [state, obj, params, success, failed]);

        params.widgetContainerId = this.id;
		params.tic = this.tic;
		params = $.extend({}, this.params, params);
		
		var _params = new Array();
		for(v in params) {

			if ('object' == typeof params[v]) {
				for(v1 in params[v]) {
					_params.push(v+'['+v1+']='+encodeURIComponent(params[v][v1]));
				}
			} else
				_params.push(v+'='+encodeURIComponent(params[v]));
		}
		
        $.ajax({
			url: '/service/widget/'+this.path+'/'+state+'.php',
			beforeload: this.beforeLoad,
			cache: false,
			dataType: 'json',
			data: _params.join('&').replace(/%20/g, "+"),
			success: success,
			error: failed,
			type: 'GET'});
    },

    successContainerLoad: function(data)
    {
        if(jQuery.isFunction(this.beforeContainerLoaded))
            this.beforeContainerLoaded.apply(this, [data]);

        if(data.type == 'html')
        {
            container = $('#container_'+this.id);
            container.html(data.content);
            container.slideDown('normal');
            this.configure = $('#container_'+this.id+' .widgetConfigure');
            this.container = $('#container_'+this.id+' .widgetContainer');
            this.content = $('#container_'+this.id+' .widgetContent');

            this.initialized = true;

            this.rendered = data.showed;
            this.showed = data.showed;
            this.params.widgetContainerInit = false;

            if(data.showed == false)
            {
                this.content.hide();
                $('#container_'+this.id+' .widgetButtonCloseObj').addClass('widgetButtonCloseClosedImg');
                $('#container_'+this.id+' .widgetButtonCloseObj').removeClass('widgetButtonCloseOpenedImg');
            }
            else
            {
                $('#container_'+this.id+' .widgetButtonCloseObj').removeClass('widgetButtonCloseClosedImg');
                $('#container_'+this.id+' .widgetButtonCloseObj').addClass('widgetButtonCloseOpenedImg');
            }

            $('#container_'+this.id+' .widgetButtonClose').unbind('click');
            $('#container_'+this.id+' .widgetButtonReload').unbind('click');
            $('#container_'+this.id+' .widgetButtonConfigure').unbind('click');

            $('#container_'+this.id+' .widgetButtonClose').bind('click', {obj:this}, function(e){e.data.obj.toggleVisible();});
            $('#container_'+this.id+' .widgetButtonReload').bind('click', {obj:this}, function(e){e.data.obj.reload();});
            $('#container_'+this.id+' .widgetButtonConfigure').bind('click', {obj:this}, function(e){e.data.obj.toggleConfigure();});
        }

        if(jQuery.isFunction(this.afterContainerLoaded))
            this.afterContainerLoaded.apply(this, [data]);
    },

    successConfigureLoad: function(data)
    {
        if(jQuery.isFunction(this.beforeConfigureLoaded))
            this.beforeConfigureLoaded.apply(this, [data]);

        if(data.type == 'html')
        {
            this.configure.html(data.content);
            this.configure.slideDown('normal');
            //this.configure.css('display', '');

            this.configurerendered = true;
            this.configureshowed = true;

            $('#container_'+this.id+' .widgetButtonConfigureApply').unbind('click');
            $('#container_'+this.id+' .widgetButtonConfigureApply').bind('click', {obj:this}, function(e){e.data.obj.configureApply();});
        }
        if(jQuery.isFunction(this.afterConfigureLoaded))
            this.afterConfigureLoaded.apply(this, [data]);
    },

    successLoad: function(obj, data, notsetrendered)
    {
        if(jQuery.isFunction(this.beforeLoaded))
            this.beforeLoaded.apply(this, [obj, data]);

        if(data.type == 'html')
        {
            obj.html(data.content);
            if(this.showed != true)
                this.save('togglevisible', {widgetContainerShowed: true});
            this.showed = true;
            this.rendered = true;
            this.content.slideDown('normal');
            $('#container_'+this.id+' .widgetButtonCloseObj').removeClass('widgetButtonCloseClosedImg');
            $('#container_'+this.id+' .widgetButtonCloseObj').addClass('widgetButtonCloseOpenedImg');

            $('#container_'+this.id+' .widgetButtonClose').unbind('click');
            $('#container_'+this.id+' .widgetButtonReload').unbind('click');
            $('#container_'+this.id+' .widgetButtonConfigure').unbind('click');

            $('#container_'+this.id+' .widgetButtonClose').bind('click', {obj:this}, function(e){e.data.obj.toggleVisible();});
            $('#container_'+this.id+' .widgetButtonReload').bind('click', {obj:this}, function(e){e.data.obj.reload();});
            $('#container_'+this.id+' .widgetButtonConfigure').bind('click', {obj:this}, function(e){e.data.obj.toggleConfigure();});
        }
        if(jQuery.isFunction(this.afterLoaded))
            this.afterLoaded.apply(this, [obj, data]);
    },

    failedLoad: function()
    {

    }
};