Ext.namespace("Flowz");

/**
 * Custom dialog to show a modal message prompt.
 *
 * @param config
 *  - iframe (url to retrieve via an iframe instead of HTML or message. Completely bypasses normal functionality,
 * 			passing it all on to the underlying iframe)
 *  - elId (an element id to use as the source)
 *  - html (html to show instead of text message)
 *  - title (text to show at top of prompt
 *  - message (text to display if not using content)
 *  - width (optional - the width of the prompt window, required when iframe is used)
 *  - height (the height of the prompt window, required when iframe is used)
 *  - mask (optional - set to false to disable masking the body)
 *  - saveLabel (optional the save button label)
 *  - onSave (optional - if a function, skips the close button and becomes a cancel/save setup)
 *  - onShow (function to call when showing)
 *  - onHide (function to execute when closing)
 *  - autoshow (true/false, if true, show() will automatically be called after init.  allows for 1 liners)
 *  - buttons (optional to provide a complete list of buttons.  Array of { cls: '', click: function(), label: '' }
 * 			Specifying this overrides onSave parameter)
 */
Flowz.Prompt = function(config) {
	this.mask = true;
    Ext.apply(this, config);
    Flowz.Prompt.superclass.constructor.call(this, config);
	if(this.autoshow) {
		this.show();
	}
};

Flowz.Prompt = Ext.extend(Flowz.Prompt, Ext.util.Observable, {
	closeLabel: 'Close',
	events: ['show'],

	update: function(html) {
		this.html = html;
		if(this.message) {
			Ext.get("prompt-message").remove();
		}
		Ext.DomHelper.insertFirst(this.el, this.html, true);
		this.center();
	},

    show: function(animTarget) {
        if(!this.el) {
			this.id = Ext.id();
            this.el = Ext.DomHelper.append(Ext.getBody(), {
                tag: 'div', id: this.id, cls: 'flowz-prompt x-hidden'
            }, true);

			if(this.title) {
				Ext.DomHelper.append(this.el, { tag: 'h1', html: this.title });
			}

			this.nav = new Ext.KeyNav(Ext.getBody(), {
				"esc" : function(e){
					this.hide();
				},
				scope : this
			});
			
			if(!this.iframe) {
				this.contentEl = Ext.DomHelper.append(this.el, { cls: 'flowz-prompt-scrollable-content' }, true);
			} else {
				this.contentEl = this.el;
			}

			this.proxy = this.el.createProxy("flowz-prompt-proxy");
        	this.proxy.enableDisplayMode('block');

			if(this.html) {
            	this.fixForIE = Ext.DomHelper.append(this.contentEl, this.html, true);

			} else if(this.iframe) {
				this.fixForIE = Ext.DomHelper.append(this.contentEl, {
					tag: 'iframe', name: 'promptIframe', src: this.iframe, width: this.width - 20, height: this.height - 20, frameborder: 0
				}, true);
				this.iframeSrc = this.iframe;
				this.iframe = this.fixForIE;

			} else if(this.elId) {
				var source = Ext.get(this.elId);
				var node = source.dom.cloneNode(true);
				node.id = Ext.id();
				var content = Ext.get(node);
				content.removeClass("x-hidden");
				this.fixForIE = content;
				this.contentEl.appendChild(content);
			} else {
				this.fixForIE = Ext.DomHelper.append(this.contentEl, {tag: 'div', id: 'prompt-message', html: this.message}, true);
			}

			if(this.buttons) {
				// if the caller is specifing their own buttons, they will handle save/close/etc.
				this.buttonBar = Ext.DomHelper.append(this.el, {
					cls: 'button-bar'
				}, true);

				// fields: button.cls, button.click, button.label
				for(i = 0; i < this.buttons.length; i++) {
					if(this.buttons[i].cls === undefined) {
						this.buttons[i].cls = "";
					}
					var tag = "span";
					if(Ext.isIE)
						tag = "a";
					var button = Ext.DomHelper.append(this.buttonBar, {
							tag: tag,
							html: this.buttons[i].label,
							cls: 'button ' + this.buttons[i].cls
						}, true);
					this.buttons[i].id = button.id;
					button.on('click', this.buttons[i].click);
				}
				Ext.DomHelper.append(this.buttonBar, { tag: 'div', style: 'clear:both;' });
				
			} else if(this.onSave) {
				var saveId = Ext.id();
				var cancelId = Ext.id();
				this.statusId = Ext.id();
				if(!this.saveLabel)
					this.saveLabel = "Save";
				this.buttonBar = Ext.DomHelper.append(this.el, {
					cls: 'button-bar', children: [
						{ tag: 'span', html: this.saveLabel, cls: 'button right highlight', id: saveId },
						{ tag: 'span', html: 'Cancel', cls: 'button right', id: cancelId },
						{ tag: 'span', id: this.statusId, cls: 'status' },
						{ tag: 'div', style: 'clear:both;' }
					]
				}, true);
				var save = Ext.get(saveId);
				save.on('click', this.onSave, this);
				var cancel= Ext.get(cancelId);
				cancel.on('click', this.close, this);

			} else {
				var buttonId = Ext.id();
				this.buttonBar = Ext.DomHelper.append(this.el, {
					cls: 'button-bar', children: [
						{ tag: 'span', html: this.closeLabel, cls: 'button right highlight', id: buttonId },
						{ tag: 'div', style: 'clear:both;' }
					]
				}, true);
				var button = Ext.get(buttonId);
				button.on('click', this.close, this);
			}
        }

		if(this.width) {
			this.el.setWidth(this.width);
		}

		if(!this.iframe) {
			var contentHeight = this.contentEl.getHeight();
			var maxHeight = Ext.getBody().getViewSize().height;
			maxHeight = maxHeight * .68;
			if(contentHeight > maxHeight)
				this.contentEl.setHeight(maxHeight);
		}
		
		this.center();
		if(animTarget !== undefined){
            this.setAnimateTarget(animTarget);
			this.animShow();
		} else {
			this.afterShow();
		}
    },

	center: function() {
		this.el.center();
		if(this.el.getTop() < 0) {
			this.el.setTop(0);
		}
	},

    hide: function() {
		if(this.buttonBar) {
			this.buttonBar.hide();
		}
		if(this.fixForIE) {
			this.fixForIE.hide();
		}
        this.el.hide({
			callback: this.endHide.createDelegate(this),
			useDisplay: false,
			duration: .15
		});

		this.open = false;
		
		Ext.getBody().unmask();
    },

	getStatusEl: function() {
		return Ext.get(this.statusId);
	},

	endHide: function() {
		if(this.onHide) {
            this.onHide();
        }
	},

	close: function() {
		this.el.hide({
			callback: this.endClose.createDelegate(this),
			useDisplay: false,
			duration: .15
		});

		this.open = false;

		Ext.getBody().unmask();
	},

	endClose: function() {
		if(this.onClose) {
            this.onClose();
        }
		this.el.remove();
	},

	expandHeight: function(extraHeight) {
		var curHeight = this.el.getHeight();
		var view = Ext.getBody().getViewSize();
		var top = this.el.getTop();
		if(curHeight + extraHeight < view.height - 60) {
			this.buttonBar.hide();
			this.el.syncFx();
			this.el.setHeight(curHeight + extraHeight, {
				anim: true,
				duration: .3,
				callback: function() {
					if(this.iframe) {
						this.iframe.setHeight(this.iframe.getHeight() + extraHeight);
					}
					this.buttonBar.show();
				}.createDelegate(this)
			});
			this.el.setLocation(this.el.getLeft(), top - (extraHeight / 2), { anim: true, duration: .3 });
		}
	},

	setAnimateTarget : function(el){
        el = Ext.get(el);
        this.animateTarget = el;
    },

	animShow : function() {
		var box = this.animateTarget.getBox();
		// has a problem, right and bottom don't match up correctly and throw everything off.
		delete(box.right);
		delete(box.bottom);
	    this.proxy.show();
        this.proxy.setBox(box);
        this.proxy.setOpacity(.5);

        var b = this.el.getBox(false);

		delete(b.right);
		delete(b.bottom);

        b.callback = this.afterShow;
        b.scope = this;
        b.duration = .25;
        b.easing = 'easeNone';
        b.opacity = 1;
        b.block = true;
        this.el.setStyle('display', 'none');
        this.proxy.shift(b);
        
    },

	afterShow : function() {
		this.proxy.hide();
        this.el.setStyle('display', 'block');

		this.el.removeClass("x-hidden");
		this.el.show();
		//if(Ext.isIE) {
			// Oh IE, how I hate thee
			this.fixForIE.show();
		//}
		this.buttonBar.show();
		log("masking: " + this.mask);
		if(this.mask) {

			Ext.getBody().mask();
			Ext.getBody().clearPositioning(); // ext adds position: relative to body when showing a mask.  FUCKERS
		}

		this.open = true;

        if(this.onShow) {
            this.onShow();
        }

        if(this.monitorResize || this.modal || this.constrain || this.constrainHeader){
            Ext.EventManager.onWindowResize(this.onWindowResize, this);
        }

        this.fireEvent("show", this);
    }
});


function getCheckedValue(radioObj) {
	if(!radioObj)
		return "";
	var radioLength = radioObj.length;
	if(radioLength == undefined)
		if(radioObj.checked)
			return radioObj.value;
		else
			return "";
	for(var i = 0; i < radioLength; i++) {
		if(radioObj[i].checked) {
			return radioObj[i].value;
		}
	}
	return "";
}

function setCheckedValue(radioObj, newValue) {
	if(!radioObj)
		return;
	var radioLength = radioObj.length;
	if(radioLength == undefined) {
		radioObj.checked = (radioObj.value == newValue.toString());
		return;
	}
	for(var i = 0; i < radioLength; i++) {
		radioObj[i].checked = false;
		if(radioObj[i].value == newValue.toString()) {
			radioObj[i].checked = true;
		}
	}
}
