var CInterface = Class.create();

CInterface.prototype = Object.extend( (new CCnfDialog('logout-container')), {

	initialize: function()
	{
		this.body = null;
		this.options = {
			'minimaizerSelector': 'body table[id="gui-main-block"] img[class="minimize-ico"]',
			'closedClassName': 'closed-col',
			'navigatorID':'questionnaires',
			'navigatorCallback':null
		};
		this.requestOptions = null;
		this.navigators = new Hash();
	},

    setupAdditionalOptions: function(config)
	{
		this.options = Object.extend(this.options, config);
	},

	initUserBar: function()
	{
		var logoutBtn = $$('div.user-name a[rel="confirm"]');
		if ( logoutBtn && logoutBtn[0] )
		{
			logoutBtn[0].onclick = function() { return false }
		    logoutBtn[0].observe('click',this.logoutWindowDisplay.bindAsEventListener(this));
		}
		var showInfoBtn = $$('div.user-name a[class="show_groups"]');
        if ( showInfoBtn && showInfoBtn[0] )
        {
            showInfoBtn[0].onclick = function() { return false }
            showInfoBtn[0].observe('click',this.showInfo.bindAsEventListener(this));
        }
	},

    showInfo: function(evt)
	{
		var el = Event.findElement(evt,'a');
        var X = (Utils.getLeftPos(el)-290);
        var Y = (Utils.getTopPos(el)+30);
        this.displayDialog ( el, X, Y, {'title':$('user_groups_container').innerHTML,'ok':this.hideInfo.bind(this)} );
		return false;
	},

	hideInfo: function()
	{
		this.hideCnf();
	},

	logoutWindowDisplay: function(evt)
	{
		var el = Event.findElement(evt,'a');
        var X = (Utils.getLeftPos(el)-270);
		var Y = (Utils.getTopPos(el)+30);
		this.displayDialog ( el, X, Y );
		return false;
	},

	OkCnf: function()
	{
		var logoutForm = this.cnfElement.up('form#unauth');
		if ( logoutForm )
		{
			logoutForm.submit();
		}
		return false;
	},

	createResizeEl: function()
	{
		var parentContainer = $$('body table[id="gui-main-block"] div[class="padding"]');
		if ( parentContainer && parentContainer[0] )
		{
			var rEl = new Element('div', {'class': 'resizer'});
			new Insertion.Top(parentContainer[0], rEl);
		}
	},

	showConfirmation: function(evt)
	{
		var el = Event.findElement(evt, 'a');
		var f = Event.findElement(evt, 'form');
		this.requestOptions = {
            'title':el.title,
            'rel':'confirm',
            'ok':this.cnfOkConfirmation.bind(this),
            'form':f,
			'el':el
        };

        var XY = this._calcCenterViewportPosition();
        this.displayDialog ( el, XY[0]-120, XY[1]-30, this.requestOptions );
		return false;
	},

	_calcCenterViewportPosition: function()
    {
        var W = Utils.getViewportWidth();
        var H = (Utils.getViewportHeight()/2) + Utils.docScrollTop();
        return [W/2,H];
    },

	cnfOkConfirmation: function()
	{
		if (this.requestOptions && this.requestOptions.form)
		{
			Utils.evalGlobally($(this.requestOptions.el).readAttribute("target"));
			this.requestOptions.form.submit();
			this.hideCnf();
		}
		return false;
	},

	submitSearchForm:function( objEvent )
	{
		var objEl =  Event.findElement(objEvent,'a');
		if( !objEl )
			return false;

		var objElForm = objEl.up('form');
		if(!objElForm )
			return false;

		this.sendSearchFormRequest(objElForm);
		
		return false;
	},
	
	sendSearchFormRequest: function(objElForm)
	{
		if( !Object.isElement(objElForm) )
		{
			objElForm = Event.findElement(objElForm,'form');
		}
		
		if( objElForm.elements['_ia'] )
        {
            objElForm.elements['_ia'].value='search';
        }
        var nav = $(objElForm).up('div[class="nav-white-block"]');
        if (nav)
        {
            var formParams = $(objElForm).serialize();
            var jsNavObj = this.getNavigator(nav.id);
            jsNavObj.setLoadingEffect();

            if( objElForm.method == 'post' )
            {
                new Ajax.Request ( $(objElForm).action,
                    { 'onSuccess': jsNavObj.successLoading.bind(jsNavObj),
                      'postBody':formParams }
                );
            }
            else if( objElForm.method == 'get')
            {
                objElForm.request({
                'onComplete':jsNavObj.successLoading.bind(jsNavObj)
                });
            }
        }
		return false;
	},

    initMinimizeSelector: function () 
	{
		$$(this.options['minimaizerSelector']).each(function(el) { el.onclick = function() { return false }; }.bind(this) )
        $$(this.options['minimaizerSelector']).invoke('observe', 'click', this.layoutMinimizer.bindAsEventListener(this) );
	},

	initLayout: function()
	{
		
        $$('form a[rel="delete"]').each(function(el)
		{
		  var str = $(el).readAttribute("onclick").replace("return false","");
		  $(el).writeAttribute("target", str);
		  el.onclick = function() { return false }; }
		)
        $$('form a[rel="delete"]').invoke('observe', 'click', this.showConfirmation.bindAsEventListener(this) );

		if ( this.options['navigatorID'] && typeof CNavigator != 'undefined' && !this.isNavigatorExists(this.options['navigatorID']) )
		{
			if (Object.isArray(this.options['navigatorID']))
			{
				this.options['navigatorID'].each (function(navigatorID) {
					
					this.navigatorSet(navigatorID, new CNavigator(
	                    {
	                        'id':navigatorID,
	                        'paginationSelector': 'div[class="top-navigation"] a',
	                        'callback':this.options['navigatorCallback']?this.options['navigatorCallback']:null
	                    }
	                ));
					this.getNavigator(navigatorID).init();
				}.bind(this));
			}
			else
			{

				var NavigatorObj = new CNavigator(
                    {
                        'id': this.options['navigatorID'],
                        'paginationSelector': 'div[class="top-navigation"] a',
						'callback':this.options['navigatorCallback']?this.options['navigatorCallback']:null
                    }
                );

				NavigatorObj.init();
				this.navigatorSet(this.options['navigatorID'],NavigatorObj);
			}
		}

        $$('form a[rel="search"]').each(function(el) { 
          el.onclick = function() { return false }; 
          var f = el.up('form');
		  f.onsubmit = function() {return false;}
		  Event.stopObserving(f, 'submit');
		  Event.observe(f, 'submit', this.sendSearchFormRequest.bindAsEventListener(this));
          return false;
        }.bind(this) );
        $$('form a[rel="search"]').invoke('observe', 'click', this.submitSearchForm.bindAsEventListener(this) );
		
		this.initUserBar();
		
        this.resizeOperation();
		
		return false;
	},
	
	resizeOperation: function()
	{
		this.resetHeight();
        this.resizeLayout();
	},
	
	isNavigatorExists: function(idNav)
	{
		if (Object.isArray(idNav)) 
		{
			var ret = false;
			idNav.each(function(id){
				if ( this.navigators.get(id) )
				{
					ret = true;
				}
			}.bind(this))
			return ret;
		}
		else
		{
			return this.navigators.get(idNav);
		}
	},

	navigatorSet: function(objNavID, objNav)
	{
		this.navigators.set(objNavID, objNav);
	},

	getNavigator: function(id)
	{
		var obj = null;
		this.navigators.each(function(p){ if (p.key == id ) obj = p.value})
		return obj;
	},

	resetHeight: function()
	{
		var trs = $$('table[id="gui-main-block"]>tbody>tr');
        if (trs.length == 3)
		{
			var boxInner = trs[1].getElementsBySelector('div[class="box-inner"]');
            if ( boxInner )
            {
                for ( var i = 0; i < boxInner.length; i++ )
                {
                    boxInner[i].setStyle({
                        'height':'auto'
                    });
                }
            }
		}
	},

	resizeLayout: function()
	{
		var trs = $$('table[id="gui-main-block"]>tbody>tr');
        if ( trs.length == 3 )
        {
            var top = (trs[0].getHeight());
            var bottom = (trs[2].getHeight());
            var height = Utils.getViewportHeight()-top-bottom;
            trs[1].setStyle({
                'height':height+'px'
            });

			var boxInner = trs[1].getElementsBySelector('div[class="box-inner"]');
			
			if ( boxInner )
			{
				for ( var i = 0; i < boxInner.length; i++ )
				{
					if ( ( height - boxInner[i].getHeight() ) > 10 )
                    {
                        boxInner[i].setStyle({
                            'height':(height-10)+'px'
                        });
                    }
				}
			}
        }
	},

	layoutMinimizer: function( evt )
	{
		var elTable = Event.element(evt).up('tr');
		if (elTable)
		{
			if (elTable.hasClassName(this.options['closedClassName']))
            {
				if ( Prototype.Browser.IE )
				{
					var td = elTable.down('td');
                    if ( td.hasClassName('management-col') )
                    {
                        td.getElementsBySelector('div[class="nav-white-block"] *').invoke('show');
                    }
				}
                elTable.removeClassName(this.options['closedClassName']);
				Utils.deleteCookie('layout_closed');
            }
            else
            {
				this.elTable = elTable;
				this.hideManagementArea(elTable,null);
            }
		}
		this.resizeLayout();
		return false;
	},

	hideManagementArea: function()
	{
		var elTable = this.elTable;
		var innerDiv = this.innerDiv;
		elTable.addClassName(this.options['closedClassName']);
        if ( Prototype.Browser.IE )
        {
            var td = elTable.down('td');
            if ( td.hasClassName('management-col') )
            {
                td.getElementsBySelector('div[class="nav-white-block"] *').invoke('hide');
            }
        }
		if ( innerDiv )
		{
			innerDiv.setStyle({'width':'','position':'static'});
		}
        Utils.setCookie('layout_closed','1',null,null,null,false);
	}
});

var interfaceObj = new CInterface();

Event.observe(document, 'dom:loaded', interfaceObj.initLayout.bindAsEventListener(interfaceObj) );
Event.observe(document, 'dom:loaded', interfaceObj.initMinimizeSelector.bindAsEventListener(interfaceObj) );
Event.observe(window,'resize', interfaceObj.resizeLayout.bindAsEventListener(interfaceObj) );
