/* @author Russ Tennant (russ@i2rd.com)
* @require logger.js
*/

if(typeof EP == 'undefined') {
	EP = {};
  	EP.Popup = function(beanNode, formDiv, form, link, cancelBtn, statusCon) {
  		this.beanNode = beanNode;
  		this.formDiv = formDiv;
  		this.form = form;
  		this.link = link;
  		this.cancelBtn = cancelBtn;
  		this.statusCon = statusCon;
  		this.init();
  	};
  	EP.Popup.prototype = {
  		init: function() {
            var body = document.body;
  			this.background = document.createElement("div");
  			this.background.className = "ep_popup_background";
  			this.background.style.display = "none";
  			body.appendChild(this.background);
  			//this.background.update("&#160;");
  			this.background.style.position = "absolute";
  			this.background.style.left = 0;
  			this.background.style.top = 0;
  			this.background.style.bottom = 0;
  			this.background.style.right = 0;
  			this.background.style.zIndex = "599";
  			
  			this.popup = document.createElement("div");
  			this.popup.style.display = "none";
  			body.appendChild(this.popup);
  			this.popup.appendChild(this.formDiv);
  			this.popup.style.zIndex = "600";
  			this.popup.id = "popup_" + this.beanNode.id;
  			this.popup.className = "ep_popup";
  			if(document.createComment)
	  			this.popup.appendChild(document.createComment("Auto generated popup for EmailPage component."));
  			
  			this.link.href = "#";
  			this.checkEscFunc = i2rd.bind(this.checkEsc,this);
  			this.hideFunc = i2rd.bind(this.hide,this);
  			i2rd.addEvent(this.link, "click", i2rd.bind(this.toggle,this));
  			i2rd.addEvent(this.background, "click", this.hideFunc);
  			i2rd.addEvent(this.cancelBtn, "click", this.hideFunc);
  			i2rd.addEvent(this.form, "submit", i2rd.bind(this.submitForm,this));
  		},
  		toggle: function(evt) {
            evt.stopPropagation();
            evt.preventDefault();
  			if(this.popup.style.display == "none")
  				this.show();
  			else
  				this.hide();
  		},
  		checkEsc: function(evt) {
  			if(evt.keyCode == 27 || evt.which == 27) {
  			 	this.hide();
  			}
  		},
  		show: function() {
	  		cms.showBackground("ep_popup_background", "599", this.hideFunc);
  			this.popup.style.display = "block";
  			var el = this.form.getElementsByTagName("input")[0];
  			i2rd.addEvent(document, "keypress", this.checkEscFunc);
  			this.scrollTo(this.popup);
  			if(window.scrollBy)
  				window.scrollBy(0, -20);
  			cms.hideObscuredElements(this.popup);
            try {
                el.focus();
            } catch(e) {
                // don't care
            }
  		},
  		scrollTo : function(element) {
		    var x = element.x ? element.x : element.offsetLeft,
	        y = element.y ? element.y : element.offsetTop;
		    window.scrollTo(x, y);
  		},
  		hide: function() {
  			cms.showObscuredElements();
	  		this.popup.style.display = "none";
	  		this.form.reset();
            this.statusCon.innerHTML="<span>&#160;</span>";
	  		i2rd.removeEvent(document, "keypress", this.checkEscFunc);
			cms.hideBackground();
  		},
        serialize:function(){
           var enc,fe,i,ib,el=this.form.elements;;
           // Only have text fields
           enc='';
            for(i=0,ib=el.length;(fe=el[i]);i++){
                if(!fe.name) {continue;}
                enc += '&' + fe.name + '=' + escape(fe.value);
            }
            return enc.substring(1);
        },
  		submitForm: function(evt) {
  			if(evt) {
  				evt.stopPropagation();
  				evt.preventDefault();
  			}
  			this.form.onsubmit = function() { return false; }; // Not sure why this is needed, don't remove without testing.
  			var encodedForm =  this.serialize();
            this.ajax = i2rd.getAjaxTransport();
			this.ajax.onreadystatechange = i2rd.bind(this.handleResponse, this);
			this.ajax.open("POST", this.form.action, true);
			this.ajax.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
			this.ajax.send(encodedForm);
  		},
  		handleResponse: function() {
            if(this.ajax.readyState != 4) { return; }
            if(!(this.ajax.status == 200 || this.ajax.status == 0))
                alert("Unable to send email. Please try again later.");
  			try {
  				var success = true; // for debuggin IE
  				var resp = this.ajax.responseText ||  this.ajax.responseXML;
  				var processed = i2rd.stripScripts(i2rd.xmlToString(resp));
                var success = processed.html.match(/success/ig);
                this.statusCon.innerHTML = processed.html;
		  		if(success) {
                    this.hide();
				} 
                this.ajax.onreadystatechange = null;
                delete this.ajax;
			} catch(e) {
				log4js.logger.error("Unable to process AJAX response.", e);
			}
  		},
  		cleanup: function() {
  			delete this.checkEscFunc;
  		}
  	};
  	
  	EP.init = function(evt) {
		var divList = document.getElementsByTagName("div");
		for(var el = null, idx = 0; (el = divList[idx]); idx++) {
			var cn = el.className || "";
			cn = cn.toLowerCase();
			if(cn.match(/ep_email_form/)) {
				if(el.ep_configured) continue;
				el.ep_configured = true;
				var epNode = el.parentNode;
				var epForm = epNode.getElementsByTagName("form")[0];
				var epDiv = epForm.parentNode;
				if(epDiv && epDiv.processed) continue;
				epDiv.processed = true;
				var epLink = epNode.getElementsByTagName("span")[0].getElementsByTagName("a")[0];
				var epCancel = null;
				var epStatusCon = null;
				var elList = epForm.getElementsByTagName("input");
				for(var el2 = null, idx2 = 0; (el2 = elList[idx2]); idx2++) {
					if(el2.type == "button" && el2.name == "ep_cancel") {
						epCancel = el2;
						break;
					}
				}
				elList = epDiv.getElementsByTagName("div");
				for(var el2 = null, idx2 = 0; (el2 = elList[idx2]); idx2++) {
					var cn2 = el2.className || "";
					cn2 = cn2.toLowerCase();
					if(cn2 == "status_messages") {
						epStatusCon = el2;
						break;
					}
				}
				if(!epForm || !epLink || !epCancel || !epStatusCon) {
					if(!el.id) el.id = "check_" + idx;
					//log4js.logger.warn("Unable to setup email page form. epForm? " + (!!epForm)
					//	+ ", epLink?" + (!!epLink) + ", epCancel?" + (!!epCancel) + ", epStatusCon?" + (!!epStatusCon)
					//	+ " for div.id = " + el.id);
				} else {
					/*log4js.logger.info("Found email form: " + epForm.id + " and anchor: " + epLink.href 
					+ " and statusCon: " + epStatusCon
					+ " for EP: " + epNode.id);*/
					var popup = new EP.Popup(epNode, epDiv, epForm, epLink, epCancel, epStatusCon);
					i2rd.addEvent(window, 'unload', function(evt) {
						popup.cleanup();
						delete popup;
					});
				}
			}
		}
  	};
  i2rd.addEvent(window, 'load', EP.init);
}

