
var popupWindow = null;
var WINDOW_CONTAINER_WIDTH = Utils.getViewportWidth(); //in px

var WindowModal = function ( ctrl )
{
	if ( ctrl )
	{
		this.ctrl		= ctrl;
		this.content 	= ctrl.href;
		ctrl.onclick    = function () { return false }
		ctrl.onclick 	= this.activate.bind(this);
		popupWindow		= this;
		
		this.popupAjaxRequestProperties = {
            "popupLoadingTimeout": 20000, //set to 10000 on production server
            "popupAjaxRequest": null,
            "popupLoadingTimeoutID": false,
            "popupLoadingRequestAborted": false,
            "popupLoadingProgressShown": false
        }
        this.ajaxLoadingEffect = null;
	}
};

WindowModal.prototype = Object.extend( (new CCnfDialog('cnf-container')), {

	getPage: function ()
	{
		if ( document.getElementsByTagName('body')[0] )
		{
			if(this.ajaxLoadingEffect == null)
			{
				this.ajaxLoadingEffect = new AjaxLoadingEffect({'containerId':document.getElementsByTagName('body')[0]});
			}
			this.ajaxLoadingEffect.setLoadingEffect();
		}
		var realHref = this.content;
		if( this.ctrl.rel =="showSeko" ){
			realHref = this.content +getUrlParamsForSekoSynergy();  
		} 
		//alert( this.content );
		this.popupAjaxRequestProperties['popupAjaxRequest'] = new Ajax.Request ( realHref, { 
		  onCreate: this.onCreateTabLoading.bind(this),
          onFailure: this.onFailureTabLoading.bind(this),
		  onSuccess: this.successLoading.bind(this) 
		  } 
		);
	},

    onTabLoadingTimeout: function()
    {
         var request = this.popupAjaxRequestProperties['popupAjaxRequest'];
         if ( Utils.callInProgress(request.transport) ) 
         {
            this._abortTabAjaxRequest(request);
           
            if (request.options['onFailure']) 
            {
              request.options['onFailure'](request.transport, request.json);
            }
         }
    },
    
    onFailureTabLoading: function()
    {
        //var el = this.getSelectedTab();
        var W = Utils.getViewportWidth();
        var H = Utils.getViewportHeight();
        
        var w_center = parseInt(W/2);
        var h_center = parseInt(H/2);
		
		var X = w_center-120;
        var Y = h_center-50;
        this.okAlertButtonTitle = 'Close';
        this.displayDialog ( $('window'), X, Y, 
            {
            'title':LOC_CNF_AJAX_TIMEOUT, 
            'rel':'alert',
            'ok':this.onFailureokCnf.bind(this)
            } 
        );
        window.clearTimeout(this.popupAjaxRequestProperties['popupLoadingTimeoutID']);
        //$('popupLoadingEffect').removeClassName('loadingProgress');
        //$('overlay').addClassName('errLoadingProgress');
        popupWindow.deactivate();
    },
    
    onFailureokCnf: function()
    {
		$('overlay').removeClassName('errLoadingProgress');
        this.deactivate();
        this.hideCnf();
        return false;
    },
    
    _abortTabAjaxRequest: function ( request )
    {
        this.popupAjaxRequestProperties['popupLoadingRequestAborted'] = true;
        request.transport.abort();
    },
    
    onCreateTabLoading: function()
    {
       this.popupAjaxRequestProperties['popupLoadingTimeoutID'] = window.setTimeout(this.onTabLoadingTimeout.bind(this), this.popupAjaxRequestProperties['popupLoadingTimeout']);
    },
	
	_onTabLoadingSuccess: function()
    {
        if ( this.popupAjaxRequestProperties['popupLoadingRequestAborted'] )
        {
            this.popupAjaxRequestProperties['popupLoadingRequestAborted'] = false;
            return false;
        }
        //clear timeout on success
        if (this.popupAjaxRequestProperties['popupLoadingTimeoutID'])
        {
            window.clearTimeout(this.popupAjaxRequestProperties['popupLoadingTimeoutID']);          
        }
        
        return true;
    },
	
	successLoading: function ( response )
	{
		var W = Utils.getViewportWidth();
		var H = Utils.getViewportHeight();

		var w_center = parseInt(W/2);
		var h_center = parseInt(H/2);

		var winObj = $('window');

		//if ( !this._onTabLoadingSuccess() ) return;
	    
		if ( arguments.length > 2 )
		{

			new Insertion.Bottom($('lbContent'),response.responseText.stripScripts());
			var popupCont = $('lbContent').down(2);
            popupCont.style.visibility = 'hidden';
			popupCont.setStyle({
				'visibility':'hidden',
				'left':arguments[1],
				'top':arguments[2]
			});
		}  
		else
		{
			winObj.update("<div id='lbContent'>" + response.responseText.stripScripts() + "</div>");
	        var popupCont = $('lbContent').down(2);
	        popupCont.style.visibility = 'hidden';
	        winObj.className = "done";
			this.updatePosition(popupCont);
		}
		popupCont.style.visibility = 'visible';
		
		
        var scripts = (response.responseText.extractScripts());
        scripts.each(function(v){
            Utils.evalGlobally(v);
        });
			
		this.actions();
		
		if(this.ajaxLoadingEffect != null){
			this.ajaxLoadingEffect.removeLoadingEffect();
		}
	},
	
	updatePosition : function(popupCont) {
		popupCont.style.height = 'auto';
		popupCont.style.overflow = 'auto';
	
		var W = Utils.getViewportWidth();
		var H = Utils.getViewportHeight();

		var w_center = parseInt(W / 2);
		var h_center = parseInt(H / 2);

		popupCont.style.left = (w_center - $(popupCont).getWidth() / 2) + 'px';
		if ((h_center - $(popupCont).getHeight() / 2) > 0) {							
			popupCont.style.top = (h_center - $(popupCont).getHeight() / 2) + 'px';
		} else {						
			popupCont.style.top = '0px';
		}

		if (parseInt(H) < $(popupCont).getHeight()) {
			popupCont.style.height = parseInt(H) - 5 + 'px';
			popupCont.style.overflow = 'scroll';
		}
		
		var popup = this
		window.onresize = function() {
			popup.updatePosition(popupCont);
		};

	},

	activate: function()
	{
		if ( Prototype.Browser.IE )
		{
			this.prepareIE();
			this.hideSelects('hidden');
		}
	
		if (window.addEventListener)
		{
			/** DOMMouseScroll is for mozilla. */
			window.addEventListener('DOMMouseScroll', wheel, false);
		}
		/** IE/Opera. */
		window.onmousewheel = document.onmousewheel = wheel;

		window.scrollTo(0,0);
		/*this.hideShowBodyScroll('hidden');*/
		this.displayWindow("block");
		
		return false;
	},

	/*hideShowBodyScroll: function( display )
	{
		document.body.style.overflow=display;
	},*/

	prepareIE: function ()
	{
		bod = document.getElementsByTagName('body')[0];
		$('overlay').style.height = bod.scrollHeight+'px';
	},

	hideSelects: function ( visibility )
	{
		selects = document.getElementsByTagName('select');
		for(i = 0; i < selects.length; i++) {
			selects[i].style.visibility = visibility;
		}
	},

	displayWindow: function(display)
	{
		$('overlay').style.display 	= display;
		$('window').style.display 	= display;
		$('window').innerHTML 		= '';
		if ( display != 'none' )
		{
			this.getPage();
		}
	},

	actions: function()
	{
		var closeActions = document.getElementsByTagName('A');
		for(i = 0; i < closeActions.length; i++)
		{
			if ( closeActions[i].rel == 'deactivate' )
			{
				closeActions[i].onclick = this.deactivate.bind(this);
			}
		}
	},

	deactivate: function()
	{
		if ( Prototype.Browser.IE )
		{
			this.prepareIE();
			this.hideSelects("visible");
		}
		
		// enable mouse scroll
		if (window.removeEventListener)
				/** DOMMouseScroll is for mozilla. */
				window.removeEventListener('DOMMouseScroll', wheel, false);
		/** IE/Opera. */
		window.onmousewheel = document.onmousewheel = null;
		// document.body.scroll = 'yes';
		
		/*this.hideShowBodyScroll('');*/
		this.displayWindow("none");
		return false;
	}
});

function initializeWindow()
{
	if ( arguments.length > 0)
	{
		if ($(arguments[0]))
		{
			var w = $(arguments[0]).getElementsByTagName('a');
            for ( i = 0; i < w.length; i++ ) 
            {
                if ( w[i].rel == "showWindow")
                {
                    new WindowModal(w[i]);
                }
            }
            
			var wS = $(arguments[0]).getElementsByTagName('a');
			alert(2);
            for ( i = 0; i < wS.length; i++ ) 
            {
                if ( wS[i].rel == "showSeko")
                {
                    new WindowModal(wS[i]);
                }
            }
            
		}
		return;
	}
	else
	{
		var w = $$('a[rel="showWindow"]');
		var wS = $$('a[rel="showSeko"]');
	}
	
	for ( i = 0; i < w.length; i++ ) 
    {
		new WindowModal(w[i]);
    }

	for ( i = 0; i < wS.length; i++ ) 
    {
		new WindowModal(wS[i]);
    }
    
    
}

function addWindowModal()
{
	bod 				= document.getElementsByTagName('body')[0];
	if ( !$('overlay') )
	{
		overlay 			= document.createElement('div');
		overlay.id			= 'overlay';
		var win				= document.createElement('div');
		win.id				= 'window';
		win.className 		= 'loading';
		bod.appendChild(overlay);
		bod.appendChild(win);
	}
}

Event.observe(document, 'dom:loaded', addWindowModal );

function wheel(event)
{
	var delta = 0;
	if (!event) /* For IE. */
			event = window.event;
	if (event.wheelDelta) { /* IE/Opera. */
			delta = event.wheelDelta/120;
			/** In Opera 9, delta differs in sign as compared to IE.
			 */
			if (window.opera)
					delta = -delta;
	} else if (event.detail) { /** Mozilla case. */
			/** In Mozilla, sign of delta is different than in IE.
			 * Also, delta is multiple of 3.
			 */
			delta = -event.detail/3;
	}
	/** If delta is nonzero, handle it.
	 * Basically, delta is now positive if wheel was scrolled up,
	 * and negative, if wheel was scrolled down.
	 */
	if (delta)
	handle(delta);
	/** Prevent default actions caused by mouse wheel.
	 * That might be ugly, but we handle scrolls somehow
	 * anyway, so don't bother here..
	 */
	if (event.preventDefault)
			event.preventDefault();
	event.returnValue = false;
}

function handle(delta)
{
	if (delta < 0)
	{
		// no action	
	}
	else
	{
		// no action	
	}
}
