
var popupWindowPos = null;
var WINDOW_CONTAINER_WIDTH = Utils.getViewportWidth(); //in px

var WindowModalPos = function ( ctrl )
{
	if ( ctrl )
	{
		this.ctrl			= ctrl;
		this.content 		= ctrl.href;
		ctrl.onclick    	= function () { return false }
		ctrl.onclick 		= this.activate.bind(this);
		popupWindowPos			= this;
		this.popupCont  	= null;
		this.objResizeEvent = null;
		this.objScrollEvent = null;
		
		this.correctedWidth = 0;
		this.popupAjaxRequestProperties = {
            "popupLoadingTimeout": 20000, //set to 10000 on production server
            "popupAjaxRequest": null,
            "popupLoadingTimeoutID": false,
            "popupLoadingRequestAborted": false,
            "popupLoadingProgressShown": false
        }
        this.ajaxLoadingEffect = null;
        
	}
	
};

WindowModalPos.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],cssLoadingEffect: 'winLoadingEffectTopMenu'});
			}
			this.ajaxLoadingEffect.setLoadingEffect();
		}
		this.popupAjaxRequestProperties['popupAjaxRequest'] = new Ajax.Request ( this.ctrl.href, {
		  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']);

        popupWindowPos.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(0);
            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(0);
	        popupCont.style.visibility = 'hidden';
	        winObj.className = "done";
			this.updatePosition(popupCont);
		}
		
		
		this.popupCont = popupCont;
		popupCont.style.visibility = 'visible';
		

		
        var scripts = (response.responseText.extractScripts());
        
        
        scripts.each(function(v){
	       	if( v.indexOf('gfieldsCheck')==-1 )
        	{
            	Utils.evalGlobally(v);
        	}
        });
         
			
		this.actions();
		
		if(this.ajaxLoadingEffect != null){
			this.ajaxLoadingEffect.removeLoadingEffect();
		}
	},
	
	updatePosition: function(popupCont)
	{
		var pageSize = getPageSize();
		$('window').style.height = '0px';
		var W = pageSize[2];
		var H = pageSize[3];

        var w_center = parseInt(W/2);
        var h_center = parseInt(H/2);
        
/*
		$('message_content').style.height = '100px';
		$('message_content').style.overflowX = 'auto';
*/
		
		var visibilityHeight = pageSize[3];


		if($('message_content'))
		{
			if($(popupCont).down('div.popUp1') ){
				$(popupCont).down('div.popUp1').style.margin = 0;
			} else if($(popupCont).down('div.popUp2')){
				$(popupCont).down('div.popUp2').style.margin = 0;
			}
			
			$('message_content').style.height = 'auto';

			//$('message_content').style.overflowX = 'none';
			// 
			// $('message_content').style.overflow = 'auto';
						
			if (($(popupCont).getHeight() + 30) >= visibilityHeight)
			{
				//$(popupCont).down('div.popUp1').style.margin = 0;
				
				var inContentHeight = $(popupCont).down('div.in-cont').getHeight();
				var calcHeight = visibilityHeight - (inContentHeight - $('message_content').getHeight()) - 60;

				$('message_content').style.height = calcHeight + 'px';
				$('message_content').style.overflowY = 'scroll';
				
				if (Prototype.Browser.IE)
				{
					$('message_content').style.position = 'relative';
				}
			}
			else
			{
				//$(popupCont).down('div.popUp1').style.marginTop = '100px';
			}
		}


	//var realWindowHeigth = $(popupCont).down('div.inner').getHeight();
		if( pageSize[2] - $(popupCont).getWidth() > 0){
			popupCont.style.left  = (pageSize[2] - $(popupCont).getWidth() )/2 + document.viewport.getScrollOffsets()[0] +'px';
		} else {
			popupCont.style.left  = '5px';
		}
				
		if( (pageSize[3]-$(popupCont).getHeight())/2 > 0)
		{
        	popupCont.style.top  = (pageSize[3]-$(popupCont).getHeight())/2 + document.viewport.getScrollOffsets()[1] +'px';
		}
		else
		{
			popupCont.style.top  = '5px';
		}
		
		var pageSizeAfterRepos = getPageSize();
		$('window').style.height = pageSizeAfterRepos[1] + 'px';//popupCont.getHeight() + 50 +'px';
		
        //popupCont.style.top  = '120px';
	},

	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;
		if( display =='block')
		{
			$('overlay').style.height = getPageSize()[1]+ 'px';
			$('overlay').style.width = getPageSize()[0] + this.correctedWidth + 'px';
			var IE6 = Prototype.Browser.IE && parseInt(navigator.userAgent.substring(navigator.userAgent.indexOf("MSIE")+5)) == 6;
			var IE7 = Prototype.Browser.IE && parseInt(navigator.userAgent.substring(navigator.userAgent.indexOf("MSIE")+5)) == 7;
			var IE8 = Prototype.Browser.IE && !IE6 && !IE7;
			if((Prototype.Browser.IE && !IE8) || Prototype.Browser.Opera)
			{
				document.body.style.overflow='';
			}
			else
			{
				document.body.style.overflowX='hidden';
			}
			this.objResizeEvent = this.repositionedCoordinates.bindAsEventListener(this,true);
			Event.observe(window,'resize',this.objResizeEvent );
			
			/*
			this.objScrollEvent = this.repositionedCoordinates.bind(this,false);
			Event.observe(document.getElementsByTagName('body')[0],'scroll',this.objScrollEvent );
			*/ 	
			
		}
		$('window').style.display 	= display;
		$('window').innerHTML 		= '';
		if ( display != 'none' )
		{
			this.getPage();
		}
	},
	
	repositionedCoordinates:function(objEvent, reposOverlay)
	{
		if ($('overlay').style.display == 'block')
		{
			$('overlay').hide();
			this.updatePosition( this.popupCont );
			if($('overlay') && reposOverlay)
			{
				var wH = getPageSize()[1];
				var wW = getPageSize()[0];
	
				if(Prototype.Browser.IE)
				{
					/*
					wH = wH + document.viewport.getScrollOffsets()[1];
					wW = wW + document.viewport.getScrollOffsets()[0];
					*/ 
				}
	
				$('overlay').style.height = wH + 'px';
				$('overlay').style.width = wW + this.correctedWidth + 'px';
				var IE6 = Prototype.Browser.IE && parseInt(navigator.userAgent.substring(navigator.userAgent.indexOf("MSIE")+5)) == 6;
				var IE7 = Prototype.Browser.IE && parseInt(navigator.userAgent.substring(navigator.userAgent.indexOf("MSIE")+5)) == 7;
				var IE8 = Prototype.Browser.IE && !IE6 && !IE7;
				if((Prototype.Browser.IE && !IE8) || Prototype.Browser.Opera)
				{
					document.body.style.overflow='';
				}
				else
				{
					document.body.style.overflowX='hidden';
				}
			}
			$('overlay').style.display = 'block';
		}
		
	},

	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");
		if( this.objResizeEvent!=null)
		{
			Event.stopObserving(window, 'resize', this.objResizeEvent )
		}
		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 WindowModalPos(w[i]);
                }
            }
		}
		return;
	}
	else
	{
		var w = $$('a[rel="showWindow"]');
	}
	
	for ( i = 0; i < w.length; i++ ) 
    {
		new WindowModalPos(w[i]);
    }
}

function addWindowModalPos()
{
	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);
		//bod.down('div.all').appendChild(win);
	}
}

Event.observe(document, 'dom:loaded', addWindowModalPos );

function wheel(event)
{
	return false;
	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	
	}
}




	function getPageSize()
	{
	var xScroll, yScroll;

	if (window.innerHeight && window.scrollMaxY) {
		xScroll = window.innerWidth + window.scrollMaxX;
		yScroll = window.innerHeight + window.scrollMaxY;
	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;
	} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		xScroll = document.body.offsetWidth;
		yScroll = document.body.offsetHeight;
	}

	var windowWidth, windowHeight;

	if (self.innerHeight) {	// all except Explorer
		if(document.documentElement.clientWidth){
			windowWidth = document.documentElement.clientWidth;
		} else {
			windowWidth = self.innerWidth;
		}
		windowHeight = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	} else if (document.body) { // other Explorers
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	}

	// for small pages with total height less then height of the viewport
	if(yScroll < windowHeight){
		pageHeight = windowHeight;
	} else {
		pageHeight = yScroll;
	}

	//console.log("xScroll " + xScroll)
	//console.log("windowWidth " + windowWidth)

	// for small pages with total width less then width of the viewport
	if(xScroll < windowWidth){
		pageWidth = windowWidth;
	} else {
		pageWidth = xScroll;
	}
	//console.log("pageWidth " + pageWidth)

	arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight)
	return arrayPageSize;
}

