/*global DARTY, window , document , setTimeout,frames, alert */ 
DARTY = DARTY || {};
DARTY.util = DARTY.util || {};
// <dependencies checking>
(function(){// Depends on Init.js, Dom.js
    var from = "DARTY.util.PopUp";
    var libs = ["DARTY.util.Init","DARTY.util.Dom","DARTY.util.Array","DARTY.util.Number"];    
	if (DARTY && DARTY.util && DARTY.util.required) {    
        DARTY.util.required(libs, from);
    }
    else {  
       if(DARTY && DARTY.DEBUG) {	   
           var msg = "Missing library : DARTY.util.Init in " + from;  
           alert(msg); 
         }     
    }
})();
// </dependencies checking>
DARTY.util.PopUp = function(){// popup manager 
	// ----------------------- Private variable declaration ---------------------------------------
    var dom = DARTY.util.Dom; // alias
    var $get = dom.id; // alias
    var mixin = DARTY.util.Mixin;	
    var logger = DARTY.util.Log;	
	/* <constants declaration>  */
    var CONST = {
		DEFAULT_OVERLAY_OPACITY : 50,
		FRAME_OVERLAY_OPACITY : 70,
        TYPE: {
            DIV: 'div',
            IFRAME: 'iframe',
            ALERT: 'alert'
        },
        STYLE: {
            ERROR: 'error',
            WARNING: 'warning',
            INFO: 'info'
        },
		LABELS : {
			CLOSE: 'Fermer'
		},
		INNER_HTML : {
			POPUP_CONTAINER: '<table id="popup_header"><tr><td id="popup_title"></td><td id="popup_close"><a href="#" id="popup_close_link"></a></td></tr></table><div id="popup_content"></div>'
		},
		POPUPID_EXTENSION : '_popup',
		HEIGHT_THRESHOLD_FOR_BORDER_DETECTION: 250 /* unit: pixel */
    };
	/* </constant declaration> */
    var overlay; 
	var iframe_overlay;	// on ie6 and below, we can't cover any windowed object like
						// select box, flash object , activeX etc....
						// even with absolute position and z-index	
						// to correct the issue, two solution :
						//   * hiding all these objects before covering
						//       - disavantage : treat each new case individualy
						//       - advantage : simpler
						//   * adding an intermediate transparente iframe with the same 
						//     size and positionning of the covering object
						//     - advantage : work without intervention when new windowed object added
						//       in the page
						//     - inconvenient : slightly more sophisticated to implement
						// we have choosen the iframe solution

	 // ---- structure of the popup container -----
	 // <div id="popup_container"
     //   <table id="popup_header">
	 //    <tr>
	 //       <td id="popup_title"></td>
	 //       <td id="popup_close">
	 //           <a href="#" id="popup_close_link"></a>
	 //        </td>
	 //    </tr>
	 //  </table>
	 //  <div id="popup_content"></div>
	 // </div>						
	 var popup_container;
     var popup_content;
     var popup_title;
	 var popup_close;	
	 var popup_close_link;
	 var popup_header;
	 
	 // -- events on popup
	 // -- ondisplay
	 var externalCommonPopOnDisplay; 
	 var innerOnDisplay;
	 var addInnerOnDisplay;
	 var setOnDisplay; // public
	 var setExternalCommonPopOnDisplay; // private
	 var launchExternalCommonPopOnDisplay; // common for all popup
	 var launchInnerOnDisplay;
	 var launchIndividualPopExternalOnDisplay; // only for an instance of popup
	 var launchAllOnDisplay;
	 //-- onclose
	 var externalCommonPopOnClose; 
	 var innerOnClose;
	 var addInnerOnClose;
	 var setOnClose; // public
	 var setExternalCommonPopOnClose; // private
	 var launchExternalCommonPopOnClose; // common for all popup
	 var launchInnerOnClose;
	 var launchIndividualPopExternalOnClose; // only for an instance of popup
	 var launchAllOnClose;
	 // -- end events on popup
	 
     var displayPopUp;	
	 var displayWaitOverlay;
	 var displayAlertError;
	 var displayAlertWarning;
	 var displayAlertInfo;
	 var close;
	 var refresh;
	 var resize;
     var showOverlay;
	 var overlayOpacity;
     var hideOverlay;
     var resizeOverlay;
     var getOverlay;
     var checkOverlay;
	 var showContent;
     var showContentDiv;
	 var showAlert;
	 var showContentIframe;
     var getPopUpContainer;
     var checkPopUpContainer;
     var isLowerThanIE7;
	 var isLowerOrEqualIE6;
	 var paramPop;	
	 var resizePopUp;	
	 var adjust;
	 var validateParam;
	 var showWaitOverlay;
	 var init;
	 //--
	 var viewport;
	 var oVoile;
	 //--
	 var PopUp;
	 // ----------------------- End of private variable declaration ---------------------------------------
	 dom.onload(function() {
	 document.body.overflowX$ = document.body.style.overflowX;
	 //--
	 viewport = (function(){
        var _width, _height, _windowHeight, _windowWidth, _scrollY;
        var refresh, getWidth, getHeight , getWindowHeight, getWindowWidth;
        var o; 
        refresh = function(){
            var scx = dom.scrollX();
            var scy = dom.scrollY();
            var wh = dom.windowHeight();
            var ww = dom.windowWidth();
            var pw = dom.pageWidth();
            var ph = dom.pageHeight();
            var width = Math.max(ww, pw);
            var height = Math.max(wh, ph);
            _width = width;
            _height = height;
            _windowHeight = wh;
            _windowWidth  = ww; 
            _scrollY = scy;      
            return {
                width: _width,
                height: _height,
                windowHeight: _windowHeight,
                windowWidth: _windowWidth,
                scrollY: _scrollY
            };
        };
        
        getWidth = function(){
            return _width || refresh().width;
        };
        
        getHeight = function(){
            return _height || refresh().height;
        };
        
        getWindowHeight = function() {
            return _windowHeight || refresh().windowHeight;
        };
        
        getWindowWidth = function() {
           return _windowWidth || refresh().windowWidth;
        };
        
        getScrollY = function() {
          return _scrollY || refresh().scrollY;
        };
        
        o = {
            refresh: refresh,
            getWidth: getWidth,
            getHeight: getHeight,
            getWindowHeight: getWindowHeight,
            getWindowWidth: getWindowWidth,
            getScrollY: getScrollY
        };
        
        return o;
     })();
	 //--
	 oVoile = (function(){
        var o = {};
        o.displayed = false;
        o.init = function(){
            var existing_popup_wait_content;
            var topImg = viewport.getWindowHeight()/2 - 100 + 'px';
            var leftImg = viewport.getWindowWidth()/2 - 100 + 'px';
            
            var voile = $get('voile') || document.createElement('div');
            voile.id = 'voile';
            voile.innerHTML = '&nbsp;';
            //--            
            (function() {
	                var cssTextArr = [];  
		            cssTextArr.push('top:0px');
		            cssTextArr.push('left:0px');
		            cssTextArr.push('right:0px');
		            cssTextArr.push('bottom:0px');
		            cssTextArr.push('width:' + viewport.getWidth() + 'px');
		            cssTextArr.push('height:' + viewport.getHeight() + 'px');
		            cssTextArr.push('margin:0px');
		            cssTextArr.push('padding:0px');
		            cssTextArr.push('position:absolute');
		            cssTextArr.push('background-color:black');
		            cssTextArr.push('z-index:2000');
		            cssTextArr.push('display:none');
		            cssTextArr.push('background-repeat:no-repeat');
		            cssTextArr.push('background-position:' + leftImg + ' ' + topImg );		            
		            voile.style.cssText = cssTextArr.join(';') + ';';
	        })();	        

            dom.setOpacity(voile, window.frameElement?CONST.FRAME_OVERLAY_OPACITY:CONST.DEFAULT_OVERLAY_OPACITY);
            o.voile = voile;
            dom.addEvent(window,'resize',o.refresh);
            //--
            return this;
        };
        o.refresh = function(){
            if(o.displayed) {
	            var topImg,leftImg;	              
	            viewport.refresh();
	            topImg = viewport.getWindowHeight()/2 - 100 + viewport.getScrollY() + 'px';
	            leftImg = viewport.getWindowWidth()/2 - 100 + 'px';	
	            //--
	            o.voile.style.height = viewport.getHeight() + 'px';
	            o.voile.style.width = viewport.getWidth() + 'px';
	            o.voile.style.backgroundPosition = leftImg + ' ' + topImg;
	            //--
				o.display();
			}
            return o;
        };
        o.display = function(){
            var iframe_voile; 
            var iframe_voile_style;
            var body = document.body;
            body.style.overflow = 'hidden';
            document.documentElement.style.overflow = 'hidden';
            body.scroll = 'no';
            if(isLowerThanIE7()) { // hack not necessary since IE7
				iframe_voile = $get('iframe_voile') || document.createElement('iframe');
				iframe_voile.id = 'iframe_voile';
				iframe_voile.src="javascript:document.write('&lt;html&gt;&lt;/html&gt;');"; // work with https
				iframe_voile_style = iframe_voile.style;
				iframe_voile_style.filter='progid:DXImageTransform.Microsoft.Alpha(style=0,opacity=0)'; // transparent iframe
				iframe_voile_style.display = 'block';
				iframe_voile_style.position = 'absolute';
				iframe_voile_style.top = '0px';
				iframe_voile_style.left = '0px';
				iframe_voile_style.width = o.voile.style.width;
				iframe_voile_style.height = o.voile.style.height;
				iframe_voile_style.border = 'none';
				iframe_voile_style.zIndex = '1999';
				iframe_voile.scrolling = 'no';
				iframe_voile.frameborder='0';
				document.body.appendChild(iframe_voile); // we have to insert the iframe before the covering object
			}
            body.appendChild(this.voile); 
            /*
            if(!isLowerThanIE7()) { 
              body.scrollIntoView(); 
            }   
            */
            o.voile.style.display = 'block';
            if(! o.displayed) {
             (function() {
              	var topImg,leftImg;
	            viewport.refresh();
	            topImg = viewport.getWindowHeight()/2 - 100 + viewport.getScrollY() + 'px';
	            leftImg = viewport.getWindowWidth()/2 - 100 + 'px';
	            o.voile.style.height = viewport.getHeight() + 'px';
	            o.voile.style.width = viewport.getWidth() + 'px';
	            o.voile.style.backgroundPosition = leftImg + ' ' + topImg;
	            if(isLowerThanIE7()) {
	               iframe_voile_style.width = o.voile.style.width;
				   iframe_voile_style.height = o.voile.style.height;
	            }
             })();
            }
            o.displayed = true;			
			return o;
        };
        return o.init();
     })();
     //--
     });
     //--
     PopUp = function (pURL, pName, pFeatures){ /* extracted from old v2_comm => TODO: to refactor */
		    var hauteur = 0;
		    var largeur = 0;
		    var wParam = pFeatures.toLowerCase().split(",");
		    pFeatures = "";
		    
		    for (var i = 0; i < wParam.length; i++) {
		        var wCouple = wParam[i].split("=");
		        if (wCouple.length == 2) {
		            if (wCouple[0] == "height") {
		                hauteur = wCouple[1];
		                pFeatures += wParam[i] + ", ";
		            }
		            else 
		                if (wCouple[0] == "width") {
		                    largeur = wCouple[1];
		                    pFeatures += wParam[i] + ", ";
		                }
		                else 
		                    if (wCouple[0] != "top" && wCouple[0] != "left") {
		                        pFeatures += wParam[i] + ", ";
		                    }
		        }
		    }
		    
		    var top = (screen.height - hauteur) / 2;
		    var left = (screen.width - largeur) / 2;
		    pFeatures = "top=" + top + ",left=" + left + "," + pFeatures;
		    pWin = window.open(pURL, pName, pFeatures);
		    pWin.focus();
	  };
     //--
	 init = function() {
	   //--	   
	   return this;   
	 };
	 
     isLowerThanIE7 = function(){
        var bd = dom.BrowserDetect;
        return bd.browser === 'Explorer' && bd.version < 7;
    };
	
	isLowerOrEqualIE6 = function(){
        var bd = dom.BrowserDetect;
        return bd.browser === 'Explorer' && bd.version <= 6;
    };
	
	adjust = function() {
        // Locate the popup container
        var obj = getPopUpContainer();
        // Make sure that the popup container exists
        if (!obj) {
			return;
		}
        // Find its current height and width
        var w = dom.getWidth(obj);
        var h = dom.getHeight(obj);
        // Position the box, vertically, in the middle of the window
        var t = dom.scrollY() + (dom.windowHeight()/2) - (h/2);
        // But no heigher than the top of the page		
        if (t < 0) {
			t = 0;
		}
        // Position the box, horizontally, in the middle of the window			
        var l = dom.scrollX() + (dom.windowWidth() / 2) - (w / 2);
        // But no less than the left of the page
        if (l < 0) {
			l = 0;
		}
        
        // Set the adjusted position of the element
        dom.setY(obj, t);
        dom.setX(obj, l);
		
		launchAllOnDisplay();
	};
	
    checkPopUpContainer = function(){
        var id = dom.id;
        if (!popup_container) {
            popup_container = document.createElement('div');
            popup_container.id = 'popup_container';
            popup_container.className = '';
            popup_container.innerHTML = CONST.INNER_HTML.POPUP_CONTAINER;
            document.body.appendChild(popup_container);
            popup_header = id('popup_header');
            popup_content = id('popup_content');
            popup_title = id('popup_title');
            if (paramPop && paramPop.title) {
                popup_title.innerHTML = paramPop.title;
            }
            popup_close_link = id('popup_close_link');
            popup_close_link.innerHTML = CONST.LABELS.CLOSE + "<span></span>";
            popup_close_link.onclick = function(e){
                hideOverlay();
                document.body.style.overflowX = document.body.overflowX$;
                return dom.stopDefault(e);
            };
            popup_close = id('popup_close');
            
            addInnerOnDisplay(function(){
                var popup_iframe = dom.id('popup_iframe');
                if (paramPop && paramPop.className && popup_container.className.indexOf(paramPop.className) === -1) {
                    popup_container.className = paramPop.className;
                }                
                
                if (popup_iframe && paramPop && paramPop.iFrameContentClassName) {
                    popup_iframe.onready = function(){                       
                        dom.addClassName({
                            className: paramPop.iFrameContentClassName,
                            element: popup_iframe.contentWindow.document.body
                        });
                    };
                }
            });
            addInnerOnDisplay(function(){
                //-- onKeyPressed Event handler activation
                if (paramPop && paramPop.onKeypress) {
                    dom.addEvent(document, 'keypress', paramPop.onKeypress);
                }
            });	
			addInnerOnDisplay(function(){
                //-- close button desactivation
                if (paramPop && paramPop.hasOwnProperty('active_close_button') && !paramPop.active_close_button) {
                   popup_close_link.style.display = 'none';
                }
            });	
            addInnerOnClose(function(){
                if (paramPop && paramPop.className && popup_container.className.indexOf(paramPop.className) >= 0) {
                    popup_container.className = popup_container.className.replace(paramPop.className, '');
                }
            });
            addInnerOnClose(function(){
				//-- onKeyPressed Event handler de-activation
				if (paramPop && paramPop.onKeypress) {
                    dom.removeEvent(document, 'keypress', paramPop.onKeypress);
                }
            });
        }
        
        return popup_container;
    };
	getPopUpContainer = function() {
		return checkPopUpContainer();
	};
	
	resizePopUp = function() {  
		var id = dom.id;
		var popup_container_padding = parseInt(dom.getStyle(id('popup_container'),'padding'),10);
        if (paramPop) {
            if (paramPop.width) {
                paramPop.width = (function(){
				    if (dom.isIE()) {
				        return Math.min(paramPop.width,dom.windowWidth());  
				    }
				    else {
				        return Math.min(paramPop.width,dom.windowWidth() - 50);  
				    }
				})();
                popup_container.style.width = paramPop.width + "px";
                popup_content.style.width = paramPop.width + "px";
            } else {
				popup_container.style.width = "auto";
				popup_content.style.width = "auto";
			}
            
            if (paramPop.height) { // Gestion de la hauteur minimal d'une popup en fonction du viewPort
                //-- on la popup ne doit pas être à moins de HEIGHT_ADJUST 
                //-- du bors de la fenetre contenant la popup
                
                //--               
                paramPop.height = (function() { 
                    if(paramPop.height && (paramPop.height <= CONST.HEIGHT_THRESHOLD_FOR_BORDER_DETECTION) ) {
                      paramPop.detectBorderCollision = false;
                    }
                    var HEIGHT_ADJUST = (paramPop.detectBorderCollision === false)?0:150;
                    if(dom.windowHeight() - HEIGHT_ADJUST > 0) {
                       return Math.min(paramPop.height,dom.windowHeight() - HEIGHT_ADJUST);
                    } else {
                      return Math.min(paramPop.height,dom.windowHeight());
                    }   
                })();     
                //--                     
                popup_container.style.height = (+paramPop.height + 2*popup_container_padding) + "px";
                popup_content.style.height = paramPop.height + "px";
            } else {
				popup_container.style.height = "auto";
				popup_content.style.height = "auto";
			}
        }
	};
	
	showWaitOverlay = function() {
		if(popup_header) {
			popup_header.style.display = 'none';
		}
		if(popup_container) {
			popup_container.className = 'wait'; 			
			if ( popup_content.firstChild ) {
                popup_content.removeChild(popup_content.firstChild);               
            }
			dom.show(popup_container);
		}		
	};
	
    showContent = function(cloned){
        var id = dom.id;
        
        if ( cloned && cloned.nodeType === document.ELEMENT_NODE ) { 
            // Remove the content, if there's one already there
            // thus, we avoid creating a 'hideContentDiv' method
            if ( popup_content.firstChild ) {
                popup_content.removeChild(popup_content.firstChild);               
            }
            // And add our new content in, instead
            popup_content.appendChild(cloned);
            // PATCH Internet explorer
            // les iframe crees avec createElement dans IE ne se comporte pas normalement
            // => on recree donc la iframe avec innerHTML sous IE
            if(dom.isIE() && cloned && cloned.tagName === 'IFRAME' ) {	            
	               var iframe_html;
	               var popup_iframe;
	               iframe_html = popup_content.innerHTML;	
	               iframe_html = iframe_html.replace("id=popup_iframe","id=popup_iframe name=popup_iframe");	
	               if ( popup_content.firstChild ) {
	                   popup_content.removeChild(popup_content.firstChild);               
	               }
	               popup_content.innerHTML = iframe_html;  
            }
            // FIN PATCH Internet explorer
            popup_content.visible = true;
			// make cloned visible
			cloned.style.display = 'block';
            popup_title.innerHTML = paramPop.title || cloned.title || '';     
			
            // size
            resizePopUp();
            
            
            // Then fade it in smoothly
            if (!popup_container.visible && !dom.isIE()) {
                dom.fadeIn(popup_container, 0, 100);
                setTimeout(function(){
                    popup_container.style.filter = 'none';
                }, 1000);
            }
            else {
                dom.show(popup_container);
            }   
        }
    };
	
    showContentDiv = function(elt){
        var id = dom.id;
        
        if (elt && elt.nodeType === document.ELEMENT_NODE) {
            var cloned = elt.cloneNode(true);
            if (cloned) {
                cloned.id += CONST.POPUPID_EXTENSION;
                
                // we have to postfix all the id elements in the cloned content popup				               
                dom.walkTheDom(cloned, function(node){
                    var attrFor;
                    if (node && node.nodeType === document.ELEMENT_NODE && node.id) {
                        node.id += CONST.POPUPID_EXTENSION;
                    }
                    
                    if (node.tagName === 'LABEL' && (node.getAttribute('for') || node.htmlFor)) {
                        attrFor = node.getAttribute('for') || node.htmlFor;
                        if (node.getAttribute('for')) {
                            node.setAttribute('for', attrFor + CONST.POPUPID_EXTENSION);
                        }
                        else 
                            if (node.htmlFor) {
                                node.htmlFor += CONST.POPUPID_EXTENSION;
                            }
                    }
                });
            }
            showContent(cloned);
            if (popup_content) {
                popup_content.style.overflow = 'auto';
            }
        }
    };
	
	showAlert = function() {
	    var popup_alert_content = document.getElementById('popup_alert_content') || document.createElement('div');		
		popup_alert_content.id = 'popup_alert_content'; 	
		popup_alert_content.style.display = 'none';
		popup_alert_content.className = paramPop.style;
		document.body.appendChild(popup_alert_content);
		
		if(popup_alert_content) {
			popup_alert_content.innerHTML = '<h1>' + paramPop.message + '</h1>';
		}
		showContentDiv(popup_alert_content);
	};
	
    showContentIframe = function(){
        var id = dom.id;
        function waitIframe(){
            if (!frames.popup_iframe) {
                setTimeout(waitIframe, 10);
            }
        }
        
        if (popup_content && !popup_content.visible) {// to avoid iframe reload when it's already visible
            var iframe = document.createElement('iframe');
			var io;
			var ifram_named;
            if (iframe) {
                iframe.id = 'popup_iframe';
				iframe.name = 'popup_iframe';
                iframe.src = paramPop.url;
                iframe.scrolling = paramPop.scrolling || 'no';                
                iframe.frameBorder = '0';// warning: 'frameBorder' and not 'frameborder'
                iframe.hspace = '0';                		
                showContent(iframe);
                if (popup_content) {
                    popup_content.style.overflow = 'hidden';
                }
				
				/* processing iframe  */	
				waitIframe();
				ifram_named = frames.popup_iframe;
				if(ifram_named) {
                    try {
                        io = ifram_named.onload;
                        ifram_named.onload = function(){
                            if (io && typeof io === 'function') {
                                io();
                            }
                            ifram_named.document.body.style.border = 'none';
                            if (iframe) {
                                iframe.style.backgroundImage = 'none';
                            }
                        };
                    } 
                    catch (e) {
                       // nothing
                    }
				}	
				//--
				if(isLowerThanIE7()) {
				    // don't forget to make a background color on the popup content , otherwise the 'waiting' picture will appear
					//iframe.style.backgroundImage = 'none';					
				}
				/* end processing iframe */	
            }
        }
    };
	
    checkOverlay = function(){
        if (!overlay) { // creates overlay if it doesn't exist
            // don't forget to define the initial 
            // style property : #overlay {display:none} 
            overlay = document.createElement('div');
            overlay.id = 'overlay';				           
            if (window.frameElement) {
				overlayOpacity = CONST.FRAME_OVERLAY_OPACITY;
            }
            
			if(isLowerThanIE7()) { // hack not necessary since IE7
				iframe_overlay = document.createElement('iframe');
				iframe_overlay.id = 'iframe_overlay';
				iframe_overlay.src="javascript:document.write('&lt;html&gt;&lt;/html&gt;');"; // work with https
				iframe_overlay.style.filter='progid:DXImageTransform.Microsoft.Alpha(style=0,opacity=0)'; // transparent iframe
				iframe_overlay.scrolling = 'no';
				iframe_overlay.frameborder='0';
				document.body.appendChild(iframe_overlay); // we have to insert the iframe before the covering object
			}
			
            // Add the overlay div into the DOM
            if (overlay) {				
				document.body.appendChild(overlay);				
            }
        }
		checkPopUpContainer();
		return overlay;
    };
	
    getOverlay = function(){// lazy creation of overlay		
        return checkOverlay();
    };
	
    resizeOverlay = function(){ 
	    var scx = dom.scrollX();
		var scy = dom.scrollY(); 
	    var wh = dom.windowHeight();
		var ww = dom.windowWidth();  
		var pw = dom.pageWidth();
		var ph = dom.pageHeight(); 
		var width = Math.max(ww,pw); 
		if(!dom.isIE()) {
		   width += scx;
		}
		var height = Math.max(wh,ph); 
		var o;        
        if (!window.frameElement) {
            o = {
                width: width,
                height: height
            };
        }
        else {
            o = (function(){				
				var iframe_width;
				
				/*
				if(dom.isIE()) {
				 iframe_width = window.width; 
				} 
				*/
				iframe_width = frameElement.clientWidth;
					
                return {
                    width: iframe_width,
                    height: height
                };
            })();
        }
		
        if (getOverlay()) {
			if (isLowerThanIE7()) {				
				iframe_overlay.style.height = o.height + "px";
				iframe_overlay.style.width = o.width + "px";
			}			
            overlay.style.height = o.height + "px";
            overlay.style.width = o.width + "px";
        }		
    };
	
    hideOverlay = function(){
		if(getPopUpContainer()) {
			dom.hide(getPopUpContainer());
			popup_container.visible = false;
			popup_content.visible = false;
		}
        if (getOverlay()) {
			if (isLowerThanIE7()) {
				dom.hide(iframe_overlay);
				iframe_overlay.visible = false;
			}
            dom.hide(overlay); 
            overlay.visible = false;			
        }
		
		launchAllOnClose();
    };
	close = hideOverlay;
	
	refresh = function() {
        if (getOverlay().visible) {
            showOverlay();
        }
	};
	
	resize = function(o) { // dynamically resizing the Pop
		if(o) {
			if(o.height && DARTY.util.Number.isNumber(o.height)) {
				paramPop.height = o.height;
			}
			
			if(o.width && DARTY.util.Number.isNumber(o.width)) {
				paramPop.width = o.width;
			}
			
			if(o.hasOwnProperty('detectBorderCollision')) {
			  paramPop.detectBorderCollision = o.detectBorderCollision;
			}
		}
		resizePopUp();		
		refresh();
		return this; // for chaining purpose
	};
	
    showOverlay = function(){ 
		var id = dom.id;
		if (getOverlay()) {
			resizeOverlay(); // adapting overlay with the viewport	
			if (isLowerThanIE7()) {
				dom.show(iframe_overlay);
			}
            
            if (overlay.visible) {
                dom.show(overlay);
                dom.setOpacity(overlay, (overlayOpacity > 0) && overlayOpacity || CONST.DEFAULT_OVERLAY_OPACITY);
            }
            else {
                if (dom.isIE()) {
                    dom.show(overlay);
                    dom.setOpacity(overlay, (overlayOpacity > 0) && overlayOpacity || CONST.DEFAULT_OVERLAY_OPACITY);
                }
                else {
                    dom.fadeIn(overlay, 0, (overlayOpacity > 0) && overlayOpacity || CONST.DEFAULT_OVERLAY_OPACITY); // TODO: activation/desactivation de fadeIn 
                }
            }
            
            document.body.style.overflowX = 'hidden';
            overlay.visible = true;
            window.onresize = function(){
			   	if (getOverlay().visible) {
					showOverlay();
				}
			};
			window.onscroll = document.onscroll = function(){
				if (getOverlay().visible) {
					adjust();
				}
			};
            
            // display content
            if (paramPop) {
                if (paramPop.type) {
                    switch (paramPop.type) {
                        case CONST.TYPE.DIV:
                            if (paramPop.id) {
                                showContentDiv(id(paramPop.id));
                            }
                            break;
                        case CONST.TYPE.IFRAME:
                            showContentIframe();
                            break;
						case CONST.TYPE.ALERT:
						   showAlert();
						   break;	
                    }
                    popup_container.visible = true;
                }
            }
            //
        }		
		adjust();		
    };
    
	validateParam = function(o) {		
		paramPop = o;
		var result = false;
		var id = dom.id;		
		if (o && o.type ) {
			switch (o.type) {
				case CONST.TYPE.DIV:
				if(o.id && id(o.id)) {
					result = true;
				} else {
					logger.error({source:'DARTY.util.PopUp.displayPopUp',message:'parametres non valides',args: mixin.serialize.apply(o)});
				}
				break;
				case CONST.TYPE.IFRAME: 
				if(o.url) {
				    result = true;
				}else {
					logger.error({source:'DARTY.util.PopUp.displayPopUp',message:'parametres non valides',args:mixin.serialize.apply(o)});
				}
				break;
				case CONST.TYPE.ALERT:
				if(o.style in {'info':null,'warn':null,'error':null,'normal':null} && o.message ) {
					result = true;
				}
				break;
			}
			
			// conditional set of properties
			if (paramPop && paramPop.setConditionalParameters && typeof paramPop.setConditionalParameters === 'function') {
				paramPop.setConditionalParameters();
			}
			
		}else {
			logger.error({source:'DARTY.util.PopUp.displayPopUp',message:'parametres non valides',args:mixin.serialize.apply(o)});
		}
		return result;
	};
	
    //-- event handling launching
	//-- onDisplay --
    //--
    setExternalCommonPopOnDisplay = function(func){ // set global public display popup event handler 
        if (func && typeof func === 'function') {
            externalCommonPopOnDisplay = func;
        }
        
        return this; // for chaining
    };
	setOnDisplay = setExternalCommonPopOnDisplay; // alias
	//--
	addInnerOnDisplay = function(func) {
		if(!innerOnDisplay || !Array.is_array(innerOnDisplay)) {
			innerOnDisplay = [];
		}
		
		if(func && typeof func === 'function') {
			innerOnDisplay.push(func);
		}
	};
	//--
	launchExternalCommonPopOnDisplay = function() {
		if (externalCommonPopOnDisplay && typeof externalCommonPopOnDisplay === 'function') {
            externalCommonPopOnDisplay();
        }
	};
	//--
	launchIndividualPopExternalOnDisplay = function() {
		var f = paramPop && paramPop.ondisplay;
		if (f && typeof f === 'function') {
            f();
        }
	};
	//--
	launchInnerOnDisplay = function() {
		if(innerOnDisplay && Array.is_array(innerOnDisplay)) {
			innerOnDisplay.each(function(item) {
				item();
			});
		}
	};
    //--
    launchAllOnDisplay = function(){ // launch all display popup event handlers
        launchInnerOnDisplay();
		launchExternalCommonPopOnDisplay();
        launchIndividualPopExternalOnDisplay();
    };
	//-- onClose --
    //--
    setExternalCommonPopOnClose = function(func){ // set global public close popup event handler 
        if (func && typeof func === 'function') {
            externalCommonPopOnClose = func;
        }
        
        return this; // for chaining
    };
	setOnClose = setExternalCommonPopOnClose; // alias
	//--
	addInnerOnClose = function(func) {
		if(!innerOnClose || !Array.is_array(innerOnClose)) {
			innerOnClose = [];
		}
		
		if(func && typeof func === 'function') {
			innerOnClose.push(func);
		}
	};
	//--
	launchExternalCommonPopOnClose = function() {
		if (externalCommonPopOnClose && typeof externalCommonPopOnClose === 'function') {
            externalCommonPopOnClose();
        }
	};
	//--
	launchIndividualPopExternalOnClose = function() {
		var f = paramPop && paramPop.onclose;
		if (f && typeof f === 'function') {
            f();
        }
	};
	//--
	launchInnerOnClose = function() {
		if(innerOnClose && Array.is_array(innerOnClose)) {
			innerOnClose.each(function(item) {
				item();
			});
		}
	};
    //--
    launchAllOnClose = function(){ // launch all display popup event handlers
        launchInnerOnClose();
		launchExternalCommonPopOnClose();
        launchIndividualPopExternalOnClose();
    };
    //-- end event handling launching
	
    displayPopUp = function(obj){
        // o parameter objet with structure : 
        // {
        //   type: 'iframe' or 'div' or 'wait' or 'alert'
		//   style: 'info' or 'warn' or 'error' or 'normal' ( for window.alert )
		//   message: '[alert content]',
        //   id: '' div#id to display (if type equals 'div')
        //   url: '/Views/...' relative URI                         
        //   width  : 25, // unit px
        //   height : 25,  // unit px
		//   title: 'Ceci, est un titre'
        // }  
        //
        // <div id="popup_container">
        //  <div id="popup_content"></div>
        //
        //
        //   <div id="popup_container_title"></div>
        // </div>        
        if (validateParam(obj)) {
            showOverlay();	
        }
        // on affiche la pop 
        // si pop de type div : on  clone le div Ã  afficher 
        // et on le place dans le container de la pop-up
    
        // si pop de type iframe : on cree la iframe avec le source qu'il faut
        //  
		return this;          
    };    
	
    displayWaitOverlay = function(){
        var arg = arguments[0];
        var nbArg = arguments.length;
        //--
        oVoile.display();
        //--
        if(nbArg > 0) {
           if(arg && typeof arg === 'function') {
             arg();
           }
        }        
        oVoile.refresh();       
        //--
    };
    
    displayAlertError = function(msg){
        displayPopUp({
            type: CONST.TYPE.ALERT,
            style: CONST.STYLE.ERROR,
            message: msg,
            width: 250
        });
    };
    
    displayAlertInfo = function(msg){
        displayPopUp({
            type: CONST.TYPE.ALERT,
            style: CONST.STYLE.INFO,
            message: msg,
            width: 250
        });
    };
    
    displayAlertWarning = function(msg){
        displayPopUp({
            type: CONST.TYPE.ALERT,
            style: CONST.STYLE.WARNING,
            message: msg,
            width: 250
        });
    };	
	
    return ({
		isLowerOrEqualIE6: isLowerOrEqualIE6,
		setOnClose : setOnClose,
		setOnDisplay : setOnDisplay,		
        displayPopUp : displayPopUp,
        displayWaitOverlay : displayWaitOverlay,
		displayAlertError : displayAlertError,
		displayAlertInfo: displayAlertInfo,
		displayAlertWarning: displayAlertWarning,
		close: close,		
		refresh: refresh,
		resize: resize,
		getPopUpContainer: getPopUpContainer,
		PopUp: PopUp,
        CONST: CONST,
        init: init
    }).init();
}();
