/* @author Russ Tennant (russ@i2rd.com)
* @require logger.js
*/
if(typeof PB == 'undefined') {

	PB = {};
	PB.CONFIG = {};
	PB.CONFIG.CONTENT_RETRIEVE = "cms-popup-contentretrieve";
	PB.CONFIG.CONTENTURL = "cms-popup-contenturl";
	PB.CONFIG.POSITION = "cms-popup-position";
	PB.currentPopup = null;
	PB.hideCurrent = function(evt) {
		if(PB.currentPopup) {
			PB.currentPopup.hide(evt);
		}
	};
	PB.checkEsc = function(evt) {
		if(evt.keyCode == 27 || evt.which == 27) {
		 	PB.hideCurrent(evt);
		}
	};
    PB.scroll = function(evt) {
		if(PB.currentPopup) { PB.currentPopup.position(evt); }
	};
	PB.Popup = function(parentDiv, controlDiv, outerContentDiv, innerContentDiv, buttonList, config) {
		this.parentDiv = parentDiv;
		this.controlDiv = controlDiv;
		this.outerContentDiv = outerContentDiv;
		this.innerContentDiv = innerContentDiv;
		this.buttonList = buttonList;
		this.config = config;
		this.setup();
		this.hasContent = false;
		this.useAjax = this.config[PB.CONFIG.CONTENT_RETRIEVE] == "true";
	};
	PB.Popup.prototype = {
		setup : function() {
			this.outerContentDiv.parentNode.removeChild(this.outerContentDiv);
			i2rd.getBody().appendChild(this.outerContentDiv);
			this.outerContentDiv.style.position = "absolute";
			this.outerContentDiv.style.zIndex = "600";
			this.outerContentDiv.style.left = "0px";
			this.outerContentDiv.style.top = "0px";
			
			this.toggleFunc = i2rd.bind(this.toggle, this);
			this.hideFunc = i2rd.bind(this.hide, this);
  			i2rd.addEvent(this.controlDiv, "click", this.toggleFunc);
  			for(var btn, idx = 0; (btn = this.buttonList[idx]); idx++) {
  				i2rd.addEvent(btn, "click", this.hideFunc);
  			}
		},
  		show: function(evt) {
			evt.stopPropagation();
			evt.preventDefault();
  			PB.currentPopup = this;
			cms.showBackground("pb_popup_background", "599", PB.hideCurrent);
            if(this.hasContent) {
                this.position(evt);
            }else if(this.useAjax) {
	  			this.getContent(evt);
  			} else {
                this.position(evt);
            }
            this.outerContentDiv.style.display = "block";
  			cms.hideObscuredElements(this.outerContentDiv);
            i2rd.addEvent(document, "keypress", PB.checkEsc);
            if(this.config[PB.CONFIG.POSITION] == "viewport_center") {
                i2rd.addEvent(window, "scroll", PB.scroll);
            }
  		},
  		hide: function(evt) {
			evt.stopPropagation();
			evt.preventDefault();
  			this.outerContentDiv.style.display = "none";
  			cms.hideBackground();
	  		i2rd.removeEvent(document, "keypress", PB.checkEsc);
            i2rd.removeEvent(window, "scroll", PB.scroll);
            cms.showObscuredElements();
	  		PB.currentPopup = null; // Update to use stack
  		},
  		toggle: function(evt) {
  			if(this.outerContentDiv.style.display == "none") {
  				this.show(evt);
  			} else {
  				this.hide(evt);
			}
  		},
  		position: function(evt) {
  			this.showButtons();
  			var position = this.config[PB.CONFIG.POSITION];
			if(position == "mouse") {
				cms.positionAtEvt(evt, this.outerContentDiv);
			} else if(position == "viewport_center") {
				cms.positionAtCenter(this.outerContentDiv);
			}
  		},
  		hideButtons : function() {
			for(var btn, idx = 0; (btn = this.buttonList[idx]); idx++) {
				var is = cms.getStyle(btn, "display");
				var ps = cms.getStyle(btn.parentNode, "display");
  				if(ps != 'none' && is != 'none') {
	  				btn.oldPDisplay = ps;
	  				btn.parentNode.style.display = 'none';
  				}
  			}
  		},
  		showButtons : function() {
  			for(var btn, idx = 0; (btn = this.buttonList[idx]); idx++) {
  				if(btn.oldPDisplay) {
	  				btn.parentNode.style.display = btn.oldPDisplay;
  				}
  			}
  		},
  		getContent : function(evt) {
  			if(this.hasContent){return;};
            // Use the event to position immediately for mouse positioning
            if(this.config[PB.CONFIG.POSITION] == "mouse"){cms.positionAtEvt(evt, this.outerContentDiv)};
			var ajax = i2rd.getAjaxTransport();
			this.hideButtons();
			var url = this.config[PB.CONFIG.CONTENTURL];
			if(ajax) {
				cms.setBackgroundLoading(true);
				ajax.onreadystatechange = this.getReqCallBack(ajax, evt);
				ajax.open("POST", url, true);
				ajax.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
				ajax.send('');
			} else { // NO AJAX - use iframe?
				// create iframe and insert into popup
				this.innerContentDiv.innerHTML = '<iframe frameborder="0" marginheight="0" marginwidth="0" src="' 
                  + url + '"><div class="loading_classname_here"></div></iframe>';
                this.position(evt);
			}
  		},
  		getReqCallBack : function(ajax, event) {
			var req = ajax, caller = this, evt = event;
			return function() {
				if (req.readyState != 4) { return; }
                try {
					cms.setBackgroundLoading(false);
					if(this.hasContent) {
						log4js.logger.info("Already have content - aborting.");
						return;
					}
		    	    if (req.status == 200 || req.status == 0) {
                        try {__i2rd_fixIELeak(caller.innerContentDiv, true);} catch(e) {}
                        var resp = req.responseText || req.responseXML;
		    	    	if(resp) {
                            var processed = i2rd.stripScripts(i2rd.xmlToString(resp));
                            caller.innerContentDiv.innerHTML = processed.html;
                            caller.outerContentDiv.style.display='none';
							caller.hasContent = true;
                            var cb = function(){
                                caller.position(evt);
                                caller.outerContentDiv.style.display="block";
                                caller.outerContentDiv.style.visibility="visible";
                            };
							window.setTimeout(cb, 40); // run after scripts for auto-sized divs.
                            
                            if(processed.scripts && processed.scripts.length > 1) {
                                window.setTimeout(function() {
                                    for(var s,i=1,ib=processed.scripts.length;i<ib; i++) {
                                        s = processed.scripts[i];
                                        try {
                                            window.eval(s);
                                        }catch(e) {
                                             if(typeof console != 'undefined'){
                                               console.log(e);  
                                             }
                                        }
                                    }
                                }, 10);
                            }
							if(typeof __i2rd_domupdate_fire != 'undefined') {
								__i2rd_domupdate_fire(caller);
							}								
						}else {
		   	    			log4js.logger.info("Got no response.");
		   	    		}
			        } else {
			        	alert("Unable to retrieve popup content. Please try again later.");
			        }
		    	} finally {
			        	try {req.onreadystatechange = null;} catch(e) {} // Ignore for IE 6
		        }
			}
  		}
    };
	PB.scan = function(start) {
        if(typeof start == 'string') start = document.getElementById(start);
        start = start || document;
		var divList = i2rd.getElementsByTagName("div", start);
		for(var el = null, idx = 0; (el = divList[idx]); idx++) {
			var cn = el.className || "";
			cn = cn.toLowerCase();
			if(cn.match(/cms-popup-component/)) {
				PB.init(el);
			}
		}
	};
  	PB.init = function(div) {
        if(typeof div == 'string') div = document.getElementById(div);
  		if(div.pb_configured) { return; }
  		div.pb_configured = true;
		var divList = i2rd.getElementsByTagName("div", div);
		var configList = i2rd.getElementsByTagName("code", div);
		var controlDiv, outerContentDiv, innerContentDiv, closeButtons = [], config = {};
		for(var el = null, idx = 0; (el = divList[idx]); idx++) {
			var cn = el.className || "";
			cn = cn.toLowerCase();
			if(!controlDiv && cn.match(/cms-popup-control/)) {
				controlDiv = el;
			} else if(!outerContentDiv && cn.match(/cms-popup-content/)) {
				outerContentDiv = el;
			} 
		}
		var buttonList = i2rd.getElementsByTagName("button", outerContentDiv);
		for(var el = null, idx = 0; (el = buttonList[idx]); idx++) {
			var cn = el.parentNode.className || "";
			cn = cn.toLowerCase();
			if(cn.match(/cms-popup-close/)) {
				closeButtons[closeButtons.length] = el;
			}
		}
		var trueID = div.id.replace(/_control$/, "");
		innerContentDiv = document.getElementById("content-" + trueID);
		for(var el = null, idx = 0; (el = configList[idx]); idx++) {
			var cn = el.className;
			if(!cn) continue;
			cn = cn.toLowerCase();
			config[cn] = i2rd.getInnerText(el);
		}
		// Sanity checks.
		if(!innerContentDiv) {
			log4js.logger.warn("Unable to find inner content div for div#" + div.id);
			return;
		}
		if(!outerContentDiv) {
			log4js.logger.warn("Unable to find outer content div for div#" + div.id);
			return;
		}
		if(!controlDiv) {
			log4js.logger.warn("Unable to find control div for div#" + div.id);
			return;
		}
		if(!config[PB.CONFIG.CONTENTURL]) {
			log4js.logger.warn("Unable to content URL config for div#" + div.id);
			return;
		}
		new PB.Popup(div, controlDiv, outerContentDiv, innerContentDiv, buttonList, config);
  	};
}
