/*
bam.popModule version 1.5
Requires jQuery for DOM operations.

Aleksandar Kolundzija
*/

({

	popModule: (function(){
		//Dependency
		bam.loadSync(bam.homePath + "bam.validation.js");

		var _overlayPreviouslyDisplayed = false,
				_fadeOutTimeoutId,
				_cacheIdx = null;

		var _fixIE6iFrame = function(){
			// IE6 doesn't always display the iframe page.  re-assigning it fixes that
			if ((/MSIE (6)/.test(navigator.userAgent) && navigator.platform == "Win32" && $("#popModule iframe").length)){
				var src = $("#popModule iframe").attr("src");
				$("#popModule iframe").attr("src", src);
			}
		};

        // set up div#popModule, our nifty DOM container
		var _moduleFrame = new bam.string.StringBuffer();
               _moduleFrame.append("<div id=\"popModule\">")
                    .append("<table class=\"module_inner\" cellpadding=\"0\">")
                    .append("<tr><td class=\"module_tl corner pop_bg\"></td><td class=\"module_t pop_bg\"></td><td class=\"module_tr corner pop_bg\"></td></tr>")
                    .append("<tr>")
                         .append("<td class=\"module_l pop_bg\">&nbsp;</td>")
                         .append("<td id=\"module_main\">")
                              .append("<div id=\"module_close\"><a href=\"javascript:void(0)\">CLOSE</a></div>")
                              .append("<div id=\"module_content\"></div>")
                         .append("</td>")
                         .append("<td class=\"module_r pop_bg\">&nbsp;</td>")
                    .append("</tr>")
                    .append("<tr><td class=\"module_bl corner pop_bg\"></td><td class=\"module_b pop_bg\"></td><td class=\"module_br corner pop_bg\"></td></tr>")
                    .append("</table>")
               .append("</div>");

		var _elementInserted = false; //Flags if element has been appended

        /**
         * Returns HTML for requested URL. Looks for DOM cached version of HTML
         * first (stored in <div src="[URL]"). If cached version is not found,
         * or refresh is forced, refetch data
         * 
         * @private
         */
        function __getHtml(__url,__forceRefresh,__showElement){
            var __id = __url.replace("http","").replace(/[-:\/.?&=]/gi,"");
            var __htmlCache =  $("div#"+__id);
        
            // if data is not cached, create the <div> for caching and fetch content from the server
            if (__htmlCache.length===0){
                $("body").append('<div style="display:none;" id="'+__id+'"><div class="cacheContent"></div></div>');
                __htmlCache    = $("div#"+__id);
                __forceRefresh = true;
            }
        
            // if force refresh, re-fetch content
            if (!!__forceRefresh) {
                $.ajax({
                    url: __url,
                    async: false,
                    dataType: "html",
                    success: function(data){
                        __htmlCache.find('.cacheContent').html(data);
                    }
                });
            }
        
            if (!!__showElement) {
                return __htmlCache;
            } else {
                return __htmlCache.find('.cacheContent').html();
            }
        }
            

		var _self = {
			preExit  : null,
			postExit : null,
			preShow  : null,
			postShow : null,

			init: function(customProps){
				var props = $.extend({
					css         : "/shared/css/bam/bam.popModule.css",
					overlayCss  : "/shared/css/bam/bam.overlay.css"
				}, customProps);
                
				bam.loadCSS( props.css );

				if ( $("#popModule").length ){ // if popModule is already in DOM
					return;
				} else {
					bam.loadSync( bam.homePath + "bam.overlay.js" ); //old - /shared/scripts/bam/
					bam.overlay.init( { css: props.overlayCss } );
					$( _moduleFrame.toString() ).appendTo("body");
					$("#module_close a").click(bam.popModule.exit);
				}
			},

			exit: function(customProps){
				var module_content = $("#module_content"),
				    props = $.extend({
                            forceOverlayHide: false, 
							preExit: _self.preExit  || function(){},
							postExit: _self.postExit || function(){}
						}, customProps);

                // fire preExit
				props.preExit();

                // clean up fade out timer
				clearTimeout(_fadeOutTimeoutId);
                
                // unbind ESC key handler
				$("body").unbind("keydown");


                // hide popModule and fire postExit once it's done
				$("#popModule").fadeOut(function() {
                    // hide overlay
				    if ( !!props.forceOverlayHide || !_overlayPreviouslyDisplayed ){
				    	bam.overlay.hide({ 
                            callback: props.postExit
                        });
				    } else {
                        props.postExit();
                    }
                });

                // cache DOM element if using loadAndShow()
				if (!!_cacheIdx) {
					module_content.children().appendTo(_cacheIdx);
					_cacheIdx = null;
				}

                // if using DOM element w/o loadAndShow(), empty the popModule content
				if(!_elementInserted) {
					module_content.empty();
				}

			},

            exitAfterPause: function( pauseTime, exitCustomConfig ) {
                var exitConfig = $.extend( {}, exitCustomConfig ),

				    exitOut = function(){
                        _self.exit( exitConfig );
				    };

				_fadeOutTimeoutId = setTimeout( exitOut, pauseTime);
                
            },

			fadeOut: function( fadeParam, exitCustomConfig ){
                var exitConfig = $.extend( {}, exitCustomConfig );
				$("#popModule").fadeOut(fadeParam, function(){ _self.exit( exitConfig ); });
			},

			fadeOutAfterPause: function( pauseTime, fadeSpeed, exitCustomConfig ){
                if ( typeof fadeSpeed === 'object' && !exitCustomConfig ) {
                    exitCustomConfig = fadeSpeed;    
                }
                var exitConfig = $.extend( {}, exitCustomConfig );

				var fadeOut = function(){
					$("#popModule").fadeOut(fadeSpeed, function(){ 
                        _self.exit( exitConfig );
                    });
				};
				_fadeOutTimeoutId = setTimeout(fadeOut, pauseTime);
			},

            loadAndShow: function(customProps){
                var props = $.extend({
                        url          : "",
                        forceRefresh : false,
                        showElement  : null
                    }, customProps);
            
                
                // if URL gets passed to load(), pass the HTML content from the URL to show()
                if (!bam.validation.isEmpty(props.url)){
                    if (!!props.showElement){
                        _elementInserted = false;
                        _cacheIdx = __getHtml(props.url, props.forceRefresh, props.showElement);
                        _self.setWidth(_cacheIdx.width());
                        _self.show({
                            element: _cacheIdx.find('.cacheContent')
                        });
                    } else {
                        _self.show({
                             htmlContent: __getHtml(props.url, props.forceRefresh)
                        });
                    }
                }
            },


			show: function(customProps){
				var props = $.extend({
					htmlContent    : "",
					element        : null,
					cloneElement   : false,
					overlayOpacity : 0.7,
					preShow        : _self.preShow  || function(){},
					postShow       : _self.postShow || function(){}
				}, customProps);

                // Shows div#popModule 
                function _showPopModule(){
		            $("#popModule").fadeIn(function() {
                        // fire postShow hook
                        props.postShow();
                    });
		            _fixIE6iFrame();
                }

				//If element is present make a clone of it and set back a reference
				if(typeof(props.element)==="object" && props.cloneElement) {
					props.element = props.element.clone(true);
				}
                // fire preShow hook
				props.preShow();

                // show overlay, if needed, then show popModule
				if( !bam.overlay.isDisplayed() ){
					bam.overlay.show({
						opacity  : props.overlayOpacity,
						callback : _showPopModule
					});
					_overlayPreviouslyDisplayed = false;

                // show popModule
				} else {
					_showPopModule();
					_overlayPreviouslyDisplayed = true;
				}

                // set content width
				if(typeof props.width !== "undefined") {
                    $("#popModule #module_content").width(props.width+"px");
                }

                // render HTML content
				if(!!props.htmlContent) {
					$("#module_content").empty().html(props.htmlContent);

                // render DOM content
				} else {
					//if(!_elementInserted && typeof(props.element)==="object") {
					if(typeof(props.element)==="object") {						
						$("#module_content").empty().append(props.element);
						_elementInserted = true;
					}
				}

                // set ESC key listener, which exits popModule
				$("body").keydown(function(e){
					if (e.keyCode==27){
						e.preventDefault();
						_self.exit();
					}
				});

			},

			setWidth: function(w){
				$("#module_content").css("width",w+"px");
			}
		};

		return _self;

	})()

})

