/* SWFObject v2.1 <http://code.google.com/p/swfobject/>
	Copyright (c) 2007-2008 Geoff Stearns, Michael Williams, and Bobby van der Sluis
	This software is released under the MIT License <http://www.opensource.org/licenses/mit-license.php>
*/
var swfobject=function(){var b="undefined",Q="object",n="Shockwave Flash",p="ShockwaveFlash.ShockwaveFlash",P="application/x-shockwave-flash",m="SWFObjectExprInst",j=window,K=document,T=navigator,o=[],N=[],i=[],d=[],J,Z=null,M=null,l=null,e=false,A=false;var h=function(){var v=typeof K.getElementById!=b&&typeof K.getElementsByTagName!=b&&typeof K.createElement!=b,AC=[0,0,0],x=null;if(typeof T.plugins!=b&&typeof T.plugins[n]==Q){x=T.plugins[n].description;if(x&&!(typeof T.mimeTypes!=b&&T.mimeTypes[P]&&!T.mimeTypes[P].enabledPlugin)){x=x.replace(/^.*\s+(\S+\s+\S+$)/,"$1");AC[0]=parseInt(x.replace(/^(.*)\..*$/,"$1"),10);AC[1]=parseInt(x.replace(/^.*\.(.*)\s.*$/,"$1"),10);AC[2]=/r/.test(x)?parseInt(x.replace(/^.*r(.*)$/,"$1"),10):0}}else{if(typeof j.ActiveXObject!=b){var y=null,AB=false;try{y=new ActiveXObject(p+".7")}catch(t){try{y=new ActiveXObject(p+".6");AC=[6,0,21];y.AllowScriptAccess="always"}catch(t){if(AC[0]==6){AB=true}}if(!AB){try{y=new ActiveXObject(p)}catch(t){}}}if(!AB&&y){try{x=y.GetVariable("$version");if(x){x=x.split(" ")[1].split(",");AC=[parseInt(x[0],10),parseInt(x[1],10),parseInt(x[2],10)]}}catch(t){}}}}var AD=T.userAgent.toLowerCase(),r=T.platform.toLowerCase(),AA=/webkit/.test(AD)?parseFloat(AD.replace(/^.*webkit\/(\d+(\.\d+)?).*$/,"$1")):false,q=false,z=r?/win/.test(r):/win/.test(AD),w=r?/mac/.test(r):/mac/.test(AD);/*@cc_on q=true;@if(@_win32)z=true;@elif(@_mac)w=true;@end@*/return{w3cdom:v,pv:AC,webkit:AA,ie:q,win:z,mac:w}}();var L=function(){if(!h.w3cdom){return }f(H);if(h.ie&&h.win){try{K.write("<script id=__ie_ondomload defer=true src=//:><\/script>");J=C("__ie_ondomload");if(J){I(J,"onreadystatechange",S)}}catch(q){}}if(h.webkit&&typeof K.readyState!=b){Z=setInterval(function(){if(/loaded|complete/.test(K.readyState)){E()}},10)}if(typeof K.addEventListener!=b){K.addEventListener("DOMContentLoaded",E,null)}R(E)}();function S(){if(J.readyState=="complete"){J.parentNode.removeChild(J);E()}}function E(){if(e){return }if(h.ie&&h.win){var v=a("span");try{var u=K.getElementsByTagName("body")[0].appendChild(v);u.parentNode.removeChild(u)}catch(w){return }}e=true;if(Z){clearInterval(Z);Z=null}var q=o.length;for(var r=0;r<q;r++){o[r]()}}function f(q){if(e){q()}else{o[o.length]=q}}function R(r){if(typeof j.addEventListener!=b){j.addEventListener("load",r,false)}else{if(typeof K.addEventListener!=b){K.addEventListener("load",r,false)}else{if(typeof j.attachEvent!=b){I(j,"onload",r)}else{if(typeof j.onload=="function"){var q=j.onload;j.onload=function(){q();r()}}else{j.onload=r}}}}}function H(){var t=N.length;for(var q=0;q<t;q++){var u=N[q].id;if(h.pv[0]>0){var r=C(u);if(r){N[q].width=r.getAttribute("width")?r.getAttribute("width"):"0";N[q].height=r.getAttribute("height")?r.getAttribute("height"):"0";if(c(N[q].swfVersion)){if(h.webkit&&h.webkit<312){Y(r)}W(u,true)}else{if(N[q].expressInstall&&!A&&c("6.0.65")&&(h.win||h.mac)){k(N[q])}else{O(r)}}}}else{W(u,true)}}}function Y(t){var q=t.getElementsByTagName(Q)[0];if(q){var w=a("embed"),y=q.attributes;if(y){var v=y.length;for(var u=0;u<v;u++){if(y[u].nodeName=="DATA"){w.setAttribute("src",y[u].nodeValue)}else{w.setAttribute(y[u].nodeName,y[u].nodeValue)}}}var x=q.childNodes;if(x){var z=x.length;for(var r=0;r<z;r++){if(x[r].nodeType==1&&x[r].nodeName=="PARAM"){w.setAttribute(x[r].getAttribute("name"),x[r].getAttribute("value"))}}}t.parentNode.replaceChild(w,t)}}function k(w){A=true;var u=C(w.id);if(u){if(w.altContentId){var y=C(w.altContentId);if(y){M=y;l=w.altContentId}}else{M=G(u)}if(!(/%$/.test(w.width))&&parseInt(w.width,10)<310){w.width="310"}if(!(/%$/.test(w.height))&&parseInt(w.height,10)<137){w.height="137"}K.title=K.title.slice(0,47)+" - Flash Player Installation";var z=h.ie&&h.win?"ActiveX":"PlugIn",q=K.title,r="MMredirectURL="+j.location+"&MMplayerType="+z+"&MMdoctitle="+q,x=w.id;if(h.ie&&h.win&&u.readyState!=4){var t=a("div");x+="SWFObjectNew";t.setAttribute("id",x);u.parentNode.insertBefore(t,u);u.style.display="none";var v=function(){u.parentNode.removeChild(u)};I(j,"onload",v)}U({data:w.expressInstall,id:m,width:w.width,height:w.height},{flashvars:r},x)}}function O(t){if(h.ie&&h.win&&t.readyState!=4){var r=a("div");t.parentNode.insertBefore(r,t);r.parentNode.replaceChild(G(t),r);t.style.display="none";var q=function(){t.parentNode.removeChild(t)};I(j,"onload",q)}else{t.parentNode.replaceChild(G(t),t)}}function G(v){var u=a("div");if(h.win&&h.ie){u.innerHTML=v.innerHTML}else{var r=v.getElementsByTagName(Q)[0];if(r){var w=r.childNodes;if(w){var q=w.length;for(var t=0;t<q;t++){if(!(w[t].nodeType==1&&w[t].nodeName=="PARAM")&&!(w[t].nodeType==8)){u.appendChild(w[t].cloneNode(true))}}}}}return u}function U(AG,AE,t){var q,v=C(t);if(v){if(typeof AG.id==b){AG.id=t}if(h.ie&&h.win){var AF="";for(var AB in AG){if(AG[AB]!=Object.prototype[AB]){if(AB.toLowerCase()=="data"){AE.movie=AG[AB]}else{if(AB.toLowerCase()=="styleclass"){AF+=' class="'+AG[AB]+'"'}else{if(AB.toLowerCase()!="classid"){AF+=" "+AB+'="'+AG[AB]+'"'}}}}}var AD="";for(var AA in AE){if(AE[AA]!=Object.prototype[AA]){AD+='<param name="'+AA+'" value="'+AE[AA]+'" />'}}v.outerHTML='<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"'+AF+">"+AD+"</object>";i[i.length]=AG.id;q=C(AG.id)}else{if(h.webkit&&h.webkit<312){var AC=a("embed");AC.setAttribute("type",P);for(var z in AG){if(AG[z]!=Object.prototype[z]){if(z.toLowerCase()=="data"){AC.setAttribute("src",AG[z])}else{if(z.toLowerCase()=="styleclass"){AC.setAttribute("class",AG[z])}else{if(z.toLowerCase()!="classid"){AC.setAttribute(z,AG[z])}}}}}for(var y in AE){if(AE[y]!=Object.prototype[y]){if(y.toLowerCase()!="movie"){AC.setAttribute(y,AE[y])}}}v.parentNode.replaceChild(AC,v);q=AC}else{var u=a(Q);u.setAttribute("type",P);for(var x in AG){if(AG[x]!=Object.prototype[x]){if(x.toLowerCase()=="styleclass"){u.setAttribute("class",AG[x])}else{if(x.toLowerCase()!="classid"){u.setAttribute(x,AG[x])}}}}for(var w in AE){if(AE[w]!=Object.prototype[w]&&w.toLowerCase()!="movie"){F(u,w,AE[w])}}v.parentNode.replaceChild(u,v);q=u}}}return q}function F(t,q,r){var u=a("param");u.setAttribute("name",q);u.setAttribute("value",r);t.appendChild(u)}function X(r){var q=C(r);if(q&&(q.nodeName=="OBJECT"||q.nodeName=="EMBED")){if(h.ie&&h.win){if(q.readyState==4){B(r)}else{j.attachEvent("onload",function(){B(r)})}}else{q.parentNode.removeChild(q)}}}function B(t){var r=C(t);if(r){for(var q in r){if(typeof r[q]=="function"){r[q]=null}}r.parentNode.removeChild(r)}}function C(t){var q=null;try{q=K.getElementById(t)}catch(r){}return q}function a(q){return K.createElement(q)}function I(t,q,r){t.attachEvent(q,r);d[d.length]=[t,q,r]}function c(t){var r=h.pv,q=t.split(".");q[0]=parseInt(q[0],10);q[1]=parseInt(q[1],10)||0;q[2]=parseInt(q[2],10)||0;return(r[0]>q[0]||(r[0]==q[0]&&r[1]>q[1])||(r[0]==q[0]&&r[1]==q[1]&&r[2]>=q[2]))?true:false}function V(v,r){if(h.ie&&h.mac){return }var u=K.getElementsByTagName("head")[0],t=a("style");t.setAttribute("type","text/css");t.setAttribute("media","screen");if(!(h.ie&&h.win)&&typeof K.createTextNode!=b){t.appendChild(K.createTextNode(v+" {"+r+"}"))}u.appendChild(t);if(h.ie&&h.win&&typeof K.styleSheets!=b&&K.styleSheets.length>0){var q=K.styleSheets[K.styleSheets.length-1];if(typeof q.addRule==Q){q.addRule(v,r)}}}function W(t,q){var r=q?"visible":"hidden";if(e&&C(t)){C(t).style.visibility=r}else{V("#"+t,"visibility:"+r)}}function g(s){var r=/[\\\"<>\.;]/;var q=r.exec(s)!=null;return q?encodeURIComponent(s):s}var D=function(){if(h.ie&&h.win){window.attachEvent("onunload",function(){var w=d.length;for(var v=0;v<w;v++){d[v][0].detachEvent(d[v][1],d[v][2])}var t=i.length;for(var u=0;u<t;u++){X(i[u])}for(var r in h){h[r]=null}h=null;for(var q in swfobject){swfobject[q]=null}swfobject=null})}}();return{registerObject:function(u,q,t){if(!h.w3cdom||!u||!q){return }var r={};r.id=u;r.swfVersion=q;r.expressInstall=t?t:false;N[N.length]=r;W(u,false)},getObjectById:function(v){var q=null;if(h.w3cdom){var t=C(v);if(t){var u=t.getElementsByTagName(Q)[0];if(!u||(u&&typeof t.SetVariable!=b)){q=t}else{if(typeof u.SetVariable!=b){q=u}}}}return q},embedSWF:function(x,AE,AB,AD,q,w,r,z,AC){if(!h.w3cdom||!x||!AE||!AB||!AD||!q){return }AB+="";AD+="";if(c(q)){W(AE,false);var AA={};if(AC&&typeof AC===Q){for(var v in AC){if(AC[v]!=Object.prototype[v]){AA[v]=AC[v]}}}AA.data=x;AA.width=AB;AA.height=AD;var y={};if(z&&typeof z===Q){for(var u in z){if(z[u]!=Object.prototype[u]){y[u]=z[u]}}}if(r&&typeof r===Q){for(var t in r){if(r[t]!=Object.prototype[t]){if(typeof y.flashvars!=b){y.flashvars+="&"+t+"="+r[t]}else{y.flashvars=t+"="+r[t]}}}}f(function(){U(AA,y,AE);if(AA.id==AE){W(AE,true)}})}else{if(w&&!A&&c("6.0.65")&&(h.win||h.mac)){A=true;W(AE,false);f(function(){var AF={};AF.id=AF.altContentId=AE;AF.width=AB;AF.height=AD;AF.expressInstall=w;k(AF)})}}},getFlashPlayerVersion:function(){return{major:h.pv[0],minor:h.pv[1],release:h.pv[2]}},hasFlashPlayerVersion:c,createSWF:function(t,r,q){if(h.w3cdom){return U(t,r,q)}else{return undefined}},removeSWF:function(q){if(h.w3cdom){X(q)}},createCSS:function(r,q){if(h.w3cdom){V(r,q)}},addDomLoadEvent:f,addLoadEvent:R,getQueryParamValue:function(v){var u=K.location.search||K.location.hash;if(v==null){return g(u)}if(u){var t=u.substring(1).split("&");for(var r=0;r<t.length;r++){if(t[r].substring(0,t[r].indexOf("="))==v){return g(t[r].substring((t[r].indexOf("=")+1)))}}}return""},expressInstallCallback:function(){if(A&&M){var q=C(m);if(q){q.parentNode.replaceChild(M,q);if(l){W(l,true);if(h.ie&&h.win){M.style.display="block"}}M=null;l=null;A=false}}}}}();Ext.namespace("Ext.tek");

Ext.tek.TextboxList = function(config) {
	Ext.apply(this, config);
};

Ext.tek.TextboxList = Ext.extend(Ext.Component, {

	options: {
		min: 5,
		max: 500,
		step: 7,
		resizable: {}
	},

	className: 'bit',
	separator: ',',
	extrainputs: true,
	startinput: true,
	value: '',
	dataSource: null, // pass in a Yahoo data source to initialize the autocomplete.
	validate: null,	// pass in function via config for validating new additions

	initComponent: function() {
		Ext.tek.TextboxList.superclass.initComponent.call(this);
		this.values = new Ext.util.MixedCollection();
		this.events = new Ext.util.MixedCollection();
        this.boxes = new Ext.util.MixedCollection();
		this.count = 0;
		this.current = false;
	},

    clear: function() {
        this.boxes.each(function(box) {
           this.dispose(box);
        }, this);
        this.values.clear();
    },

	getValue: function() {
		this.value = "";
		this.values.each(function(item, index, length) {
			this.value += item;
			if(index < length - 1)
				this.value += this.separator;
		}, this);

		return this.value;
	},

	getValues: function() {
		return this.values;
	},

	enable: function() {
		Ext.tek.TextboxList.superclass.enable.call(this);
		this.maininput.input.dom.disabled = false;		
	},

	disable: function() {

		Ext.tek.TextboxList.superclass.disable.call(this);
		this.maininput.input.dom.disabled = true;
	},
	
	size: function() {
		if(this.values)
			return this.values.getCount();
	},

	getCaretPosition: function() {
		if(this.el.dom.createTextRange) {
			var r = document.selection.createRange().duplicate();
			r.moveEnd('character', this.value.length);

			if(r.text === '')
				return this.value.length;

			return this.value.lastIndexOf(r.text);

		} else {
			return this.el.dom.selectionStart;
		}
	},

	onRender: function(container, position) {
		Ext.tek.TextboxList.superclass.onRender.call(this, container, position);
		this.container = container;
		this.el = this.holder = container.createChild({ tag: 'ul', cls: 'holder x-form-field x-form-text' });

		this.holder.on('click', function(e) {
			e.stopEvent();
			if(this.maininput != this.current)
				this.focus(this.maininput);
		}, this);

		this.maininput = this.createInput(this.holder, 'child', 'maininput');

		this.makeResizable(this.maininput);

		this.on('onInputBlur', function() {
			if(!this.current || this.autocomplete.isContainerOpen())
				return;
			var text = this.current.input.dom.value;
			if(text == "")
				return;
			this.add(text);
		});

		//		this.dataSource = null;
		if(this.dataSource) {
			// container.createChild({ tag: 'div', id: 'ac-container', cls: 'yui-ac-container'});
			this.autocomplete = new YAHOO.widget.AutoComplete('maininput', 'ac-container', this.dataSource);
			// do we need a reference to back to this textbox list?
			this.autocomplete.textboxlist = this;

			this.autocomplete.itemSelectEvent.subscribe(function(sType, aArgs) {
				var autocomplete = aArgs[0]; // your AutoComplete instance
				var item = aArgs[1]; //the <li> element selected in the suggestion
				var data = aArgs[2]; //array of the data for the item as returned by the DataSource
				autocomplete.textboxlist.add(data[0]);

			});

			this.autocomplete.animVert = false;
			this.autocomplete.animHoriz = false;
			this.autocomplete.typeAhead = true;
			this.autocomplete.setFooter("Type first name, last name, or email address...");
			this.autocomplete.doBeforeExpandContainer = function(elTexbox, elContainer, sQuery, aResults) {
				var acContainer = Ext.get(elContainer.id);
				acContainer.setLeft(this.container.getLeft());
				acContainer.setTop(this.container.getTop() + this.container.getHeight() + 10);
				acContainer.setWidth(this.container.getWidth() - 2);
				return true;
			}.createDelegate(this);

			this.autocomplete.formatResult = function(aResultItem, sQuery) {
				// aResultItem is defined by the schema
				var email = aResultItem[0];
				var fname = aResultItem[1];
				var lname = aResultItem[2];

				if(email.toLowerCase().indexOf(sQuery.toLowerCase()) == 0) {
					start = email.substr(0, sQuery.length);
					remainder = email.substr(sQuery.length);
					email = "<span style='font-weight:bold'>" + start + "</span>" + remainder;
				}

				if(fname.toLowerCase().indexOf(sQuery.toLowerCase()) == 0) {
					start = fname.substr(0, sQuery.length);
					remainder = fname.substr(sQuery.length);
					fname = "<span style='font-weight:bold'>" + start + "</span>" + remainder;
				}

				if(lname.toLowerCase().indexOf(sQuery.toLowerCase()) == 0) {
					start = lname.substr(0, sQuery.length);
					remainder = lname.substr(sQuery.length);
					lname = "<span style='font-weight:bold'>" + start + "</span>" + remainder;
				}
				var aMarkup = ["<div id='ysearchresult'>",
					fname,
					" ",
					lname,
					" ",
					"&lt;",
					email,
					"&gt;",
					"</div>"
				];

				return (aMarkup.join(""));
			};
		}

		this.setEvents();
	},

	afterRender: function() {
		this.width = this.el.offsetWidth;

		/*
		 this.el.on('keydown', function() {
		 this.rt_value = this.value.length;
		 Ext.log("value: " + this.value + ", rt_value: " + this.rt_value);
		 }, this);
		 */

		this.el.on('keyup', function() {
			var newSize = this.options.step * this.value.length;
			if(newSize <= this.options.min)
				newSize = this.width;
			if(! (this.value.length == this.rt_value) || newsize <= this.options.min || newsize >= this.options.max)
				this.el.setWidth(newSize);
		}, this);
	},

	makeResizable: function(li) {
		var el = li.input;
		var max = this.el.getWidth();
		//this.resizable = new ResizableTextbox(Ext.extend(this.options.resizable, {min: el.offsetWidth, max: max}));
		return this;
	},

	setEvents: function() {
		/**
		 * This KeyMap ends up being global for the entire document.  That means we have to abort the event handlers
		 * if it looks like they were triggered by other UI elements on the page.  Hence, the: if(!this.current) return.
		 */
		this.map = new Ext.KeyMap(document, [
			{
				key: [Ext.EventObject.RETURN,Ext.EventObject.ENTER, Ext.EventObject.TAB, 188], // (return, enter, comma)
				fn: function(key, e) {
					if(!this.current)
						return;
                    // for some reason, even though shift is false in config, we are still being passed events with shift key pressed!
                    if(e.shiftKey) {
                        return;
                    }
                    
					var text = this.current.input.dom.value;
					if(text == "")
						return;
					this.add(text);

					if(key == 188 || key == Ext.EventObject.ENTER) // don't want commas and don't want to submit the form
						e.stopEvent();
				},
                shift: false,
				scope: this
			}, {
			key: Ext.EventObject.LEFT,
			fn: function(key, e) {
				if(this.move) this.move('left');
			},
			scope: this
		}, {
			key: Ext.EventObject.RIGHT,
			fn: function(key, e) {
				if(this.move) this.move('right');
			},
			scope: this
		}, {
			key: [Ext.EventObject.BACKSPACE, Ext.EventObject.DELETE],
			fn: function(key, e) {
				if(!this.current)
					return;
				if(this.current.type == 'input') {
					if(this.current.input.dom.value != '')
						return;

					if(key != Ext.EventObject.BACKSPACE)
						return;

					this.dispose(this.current.prev());
					return;
				}

				this.moveDispose();
				e.stopEvent();

			}, scope: this
		}
		]);

		this.on('click', function() {
			this.fireEvent('onBlur').blur();
		}, this);
	},

	add: function(text, id) {
		if(this.disabled)
			return;

		Ext.log("Add(" + text + ") called.");
		if(this.validate) {
			if(!this.validate(text, id, this)) {
				//Ext.log("Validate failed.  Focusing back on input");
				//this.focus(this.maininput);
				return;
			}
		}
		this.current.input.dom.value = "";

		if(this.values.contains(text))
			return;
		
		if(!id)
			id = "manual-entry-" + this.count++;

		var el = this.createBox(this.current || this.maininput, text, id);
        this.boxes.add(el);
		el.on('click', function (e) {
			e.stopEvent();
			this.focus(el);
		}, this);

		this.values.add(id, text);
		
		if(this.current)
			var prev = this.current.prev();

		if(this.extrainputs && (this.startinput || prev))
			this.addSmallInput(el);

        this.container.setHeight(this.el.getHeight());
		return el;
	},

	/**
	 * Gives focus back to the last entry for editing...
	 */
	redoInput: function() {
		this.privateFocus(this.maininput);
	},

	focus: function(el, nofocus) {
		Ext.log("focus called.");
		if(this.disabled)
			return;

		if(!this.current)
			this.fireEvent('onFocus', el);

		else if(this.current == el)
			return this;


		this.blur();

		return this.privateFocus(el, nofocus);
	},

	privateFocus: function(el, nofocus) {
		Ext.log("privateFocus() called on: "+ el.id);
		//this.el.addClass("x-form-focus");
		this.holder.addClass("x-form-focus");

		el.addClass(this.className + '-' + el.type + '-focus');
		if(el.small)
			el.setStyle('display', 'block');
		if(el.type == 'input') {
			this.fireEvent('onInputFocus', el);
			if(!nofocus)
				this.callEvent(el.input, 'focus');

		} else {
			this.fireEvent('onBoxFocus', el);
		}
		Ext.log("Setting current to el: " + el.id);
		this.current = el;
		return this;
	},

	blur: function(noblur) {
		if(this.disabled)
			return;
		Ext.log("this.current: "+ this.current);
		if(!this.current)
			return this;

		this.el.removeClass("x-form-focus");

		Ext.log("current type: "+ this.current.type);
		if(this.current.type == 'input') {

			var input = this.current.input;

			if(!noblur) {
				Ext.log("CallEvent(blur)");
				this.callEvent(input, 'blur');
			}
			Ext.log("Firing onInputBlur()");
			this.fireEvent('onInputBlur', input);

		} else {

			this.fireEvent('onBoxBlur', this.current);
		}

		if(this.current.small && !input.value) {

			this.current.setStyle('display', 'none');
		} else {
			//alert("Not hiding small input...");
		}


		if(this.current) {
			Ext.log("Removign focus class from current item");
			this.current.removeClass(this.className + '-' + this.current.type + '-focus');
			Ext.log("Setting current to false");
			this.current = false;
		}
		return this;
	},

	addSmallInput: function(el) {
		var input = this.createInput(el, 'before', 'smallinput');
		input.small = true;
		this.makeResizable(input);

		input.setStyle('display', 'none');

		return input;
	},

	createInput: function(el, where, clsName) {
		var tags = { tag: 'li', cls: this.className + '-input', children:[
			{ tag: 'input', id: clsName, type: 'text', cls: clsName}
		]};

		if(where == 'before') {
			var li = Ext.DomHelper.insertBefore(el, tags, true);
		} else {
			var li = el.createChild(tags);
		}

		var input = Ext.get(Ext.DomQuery.selectNode('*', li.dom));

		input.on('click', function(e) {
			e.stopEvent()
		}, this);
		input.on('focus', function(e) {
			if(this.disabled)
				return;
			if(!this.isSelfEvent('focus'))
				this.focus(li, true);
		}, this);
		input.on('blur', function(e) {
			Ext.log("Blur called on " + clsName + " and isSelfEvent: "+ this.isSelfEvent('blur'));
			if(!this.isSelfEvent('blur')) {
				this.blur(true);
			}
		}, this);
		input.on('keydown', function(e) {
			this.lastValue = input.value;
			this.lastCaret = this.getCaretPosition();
		}, this);

		li.type = 'input';
		li.input = input;

		return li;
	},

	createBox: function(el, text, id) {
        // filter for illegal characters in displayed HTML
        text = text.replace("<", "&lt;");
        text = text.replace(">", "&gt;");
        
		var box = this.el.createChild({ tag: 'li', id: id, cls: this.className + '-box', html: text }, el);
		box.type = 'box';
		box.value = text;
		box.textboxlist = this;
		box.on('mouseover', function() {
			if(this.textboxlist.disabled)
				return;
			this.addClass('bit-hover');
		});
		box.on('mouseout', function() {
			if(this.textboxlist.disabled)
				return;				
			this.removeClass('bit-hover');
		});

		var close = box.createChild({ tag: 'a', href: '#', cls: 'closebutton' });

		close.on('click', function(e) {
			if(this.disabled)
				return;
			e.stopEvent();
			if(!this.current)
				this.focus(this.maininput);
			this.dispose(box);
		}, this);

		return box;
	},

	callEvent: function(el, type) {
		Ext.log('Call event called.');
		this.events.add(type, el);
		el[type]();
	},

	dispose: function(box) {
		if(this.disabled)
			return;
		//this.values.remove(el.id);
		if(box.value) {
			this.values.remove(box.value);
		}

		if(box.prev() && box.prev().small)
			box.prev().remove();

		if(this.current == box)
			this.focus(box.next());

		if(box.type == 'box')
			this.fireEvent('onBoxDispose', box);

		box.remove();

        this.container.setHeight(this.el.getHeight());
        
		return this;
	},

	isSelfEvent: function(type) {
		return (this.events.get(type)) ? !!this.events.removeKey(type) : false;
	},

	checkInput: function() {
		var input = this.current.input;
		//return (!input.lastvalue || (input.getCaretPosition() === 0 && input.lastCaret === 0));
		return !this.current.input.dom.value.length
	},

	move: function(direction) {
		if(direction == 'left')
			var el = this.current.prev();
		else
			var el = this.current.next();

		if(el && (!this.current.input || ((this.checkInput() || direction == 'right')))) {
			this.focus(el);
		}
		return this;
	},

	moveDispose: function() {
		if(this.current.type == 'box')
			return this.dispose(this.current);

		var prev = this.current.prev();

		if(this.checkInput() && this.values.getCount() && prev)
			return this.focus(prev);
	}
});/*
Copyright (c) 2009, Yahoo! Inc. All rights reserved.
Code licensed under the BSD License:
http://developer.yahoo.net/yui/license.txt
version: 2.7.0
*/
YAHOO.widget.DS_JSArray=YAHOO.util.LocalDataSource;YAHOO.widget.DS_JSFunction=YAHOO.util.FunctionDataSource;YAHOO.widget.DS_XHR=function(B,A,D){var C=new YAHOO.util.XHRDataSource(B,D);C._aDeprecatedSchema=A;return C;};YAHOO.widget.DS_ScriptNode=function(B,A,D){var C=new YAHOO.util.ScriptNodeDataSource(B,D);C._aDeprecatedSchema=A;return C;};YAHOO.widget.DS_XHR.TYPE_JSON=YAHOO.util.DataSourceBase.TYPE_JSON;YAHOO.widget.DS_XHR.TYPE_XML=YAHOO.util.DataSourceBase.TYPE_XML;YAHOO.widget.DS_XHR.TYPE_FLAT=YAHOO.util.DataSourceBase.TYPE_TEXT;YAHOO.widget.AutoComplete=function(G,B,J,C){if(G&&B&&J){if(J instanceof YAHOO.util.DataSourceBase){this.dataSource=J;}else{return;}this.key=0;var D=J.responseSchema;if(J._aDeprecatedSchema){var K=J._aDeprecatedSchema;if(YAHOO.lang.isArray(K)){if((J.responseType===YAHOO.util.DataSourceBase.TYPE_JSON)||(J.responseType===YAHOO.util.DataSourceBase.TYPE_UNKNOWN)){D.resultsList=K[0];this.key=K[1];D.fields=(K.length<3)?null:K.slice(1);}else{if(J.responseType===YAHOO.util.DataSourceBase.TYPE_XML){D.resultNode=K[0];this.key=K[1];D.fields=K.slice(1);}else{if(J.responseType===YAHOO.util.DataSourceBase.TYPE_TEXT){D.recordDelim=K[0];D.fieldDelim=K[1];}}}J.responseSchema=D;}}if(YAHOO.util.Dom.inDocument(G)){if(YAHOO.lang.isString(G)){this._sName="instance"+YAHOO.widget.AutoComplete._nIndex+" "+G;this._elTextbox=document.getElementById(G);}else{this._sName=(G.id)?"instance"+YAHOO.widget.AutoComplete._nIndex+" "+G.id:"instance"+YAHOO.widget.AutoComplete._nIndex;this._elTextbox=G;}YAHOO.util.Dom.addClass(this._elTextbox,"yui-ac-input");}else{return;}if(YAHOO.util.Dom.inDocument(B)){if(YAHOO.lang.isString(B)){this._elContainer=document.getElementById(B);}else{this._elContainer=B;}if(this._elContainer.style.display=="none"){}var E=this._elContainer.parentNode;var A=E.tagName.toLowerCase();if(A=="div"){YAHOO.util.Dom.addClass(E,"yui-ac");}else{}}else{return;}if(this.dataSource.dataType===YAHOO.util.DataSourceBase.TYPE_LOCAL){this.applyLocalFilter=true;}if(C&&(C.constructor==Object)){for(var I in C){if(I){this[I]=C[I];}}}this._initContainerEl();this._initProps();this._initListEl();this._initContainerHelperEls();var H=this;var F=this._elTextbox;YAHOO.util.Event.addListener(F,"keyup",H._onTextboxKeyUp,H);YAHOO.util.Event.addListener(F,"keydown",H._onTextboxKeyDown,H);YAHOO.util.Event.addListener(F,"focus",H._onTextboxFocus,H);YAHOO.util.Event.addListener(F,"blur",H._onTextboxBlur,H);YAHOO.util.Event.addListener(B,"mouseover",H._onContainerMouseover,H);YAHOO.util.Event.addListener(B,"mouseout",H._onContainerMouseout,H);YAHOO.util.Event.addListener(B,"click",H._onContainerClick,H);YAHOO.util.Event.addListener(B,"scroll",H._onContainerScroll,H);YAHOO.util.Event.addListener(B,"resize",H._onContainerResize,H);YAHOO.util.Event.addListener(F,"keypress",H._onTextboxKeyPress,H);YAHOO.util.Event.addListener(window,"unload",H._onWindowUnload,H);this.textboxFocusEvent=new YAHOO.util.CustomEvent("textboxFocus",this);this.textboxKeyEvent=new YAHOO.util.CustomEvent("textboxKey",this);this.dataRequestEvent=new YAHOO.util.CustomEvent("dataRequest",this);this.dataReturnEvent=new YAHOO.util.CustomEvent("dataReturn",this);this.dataErrorEvent=new YAHOO.util.CustomEvent("dataError",this);this.containerPopulateEvent=new YAHOO.util.CustomEvent("containerPopulate",this);this.containerExpandEvent=new YAHOO.util.CustomEvent("containerExpand",this);this.typeAheadEvent=new YAHOO.util.CustomEvent("typeAhead",this);this.itemMouseOverEvent=new YAHOO.util.CustomEvent("itemMouseOver",this);this.itemMouseOutEvent=new YAHOO.util.CustomEvent("itemMouseOut",this);this.itemArrowToEvent=new YAHOO.util.CustomEvent("itemArrowTo",this);this.itemArrowFromEvent=new YAHOO.util.CustomEvent("itemArrowFrom",this);this.itemSelectEvent=new YAHOO.util.CustomEvent("itemSelect",this);this.unmatchedItemSelectEvent=new YAHOO.util.CustomEvent("unmatchedItemSelect",this);this.selectionEnforceEvent=new YAHOO.util.CustomEvent("selectionEnforce",this);this.containerCollapseEvent=new YAHOO.util.CustomEvent("containerCollapse",this);this.textboxBlurEvent=new YAHOO.util.CustomEvent("textboxBlur",this);this.textboxChangeEvent=new YAHOO.util.CustomEvent("textboxChange",this);F.setAttribute("autocomplete","off");YAHOO.widget.AutoComplete._nIndex++;}else{}};YAHOO.widget.AutoComplete.prototype.dataSource=null;YAHOO.widget.AutoComplete.prototype.applyLocalFilter=null;YAHOO.widget.AutoComplete.prototype.queryMatchCase=false;YAHOO.widget.AutoComplete.prototype.queryMatchContains=false;YAHOO.widget.AutoComplete.prototype.queryMatchSubset=false;YAHOO.widget.AutoComplete.prototype.minQueryLength=1;YAHOO.widget.AutoComplete.prototype.maxResultsDisplayed=10;YAHOO.widget.AutoComplete.prototype.queryDelay=0.2;YAHOO.widget.AutoComplete.prototype.typeAheadDelay=0.5;YAHOO.widget.AutoComplete.prototype.queryInterval=500;YAHOO.widget.AutoComplete.prototype.highlightClassName="yui-ac-highlight";YAHOO.widget.AutoComplete.prototype.prehighlightClassName=null;YAHOO.widget.AutoComplete.prototype.delimChar=null;YAHOO.widget.AutoComplete.prototype.autoHighlight=true;YAHOO.widget.AutoComplete.prototype.typeAhead=false;YAHOO.widget.AutoComplete.prototype.animHoriz=false;YAHOO.widget.AutoComplete.prototype.animVert=true;YAHOO.widget.AutoComplete.prototype.animSpeed=0.3;YAHOO.widget.AutoComplete.prototype.forceSelection=false;YAHOO.widget.AutoComplete.prototype.allowBrowserAutocomplete=true;YAHOO.widget.AutoComplete.prototype.alwaysShowContainer=false;YAHOO.widget.AutoComplete.prototype.useIFrame=false;YAHOO.widget.AutoComplete.prototype.useShadow=false;YAHOO.widget.AutoComplete.prototype.suppressInputUpdate=false;YAHOO.widget.AutoComplete.prototype.resultTypeList=true;YAHOO.widget.AutoComplete.prototype.queryQuestionMark=true;YAHOO.widget.AutoComplete.prototype.toString=function(){return"AutoComplete "+this._sName;};YAHOO.widget.AutoComplete.prototype.getInputEl=function(){return this._elTextbox;};YAHOO.widget.AutoComplete.prototype.getContainerEl=function(){return this._elContainer;
};YAHOO.widget.AutoComplete.prototype.isFocused=function(){return(this._bFocused===null)?false:this._bFocused;};YAHOO.widget.AutoComplete.prototype.isContainerOpen=function(){return this._bContainerOpen;};YAHOO.widget.AutoComplete.prototype.getListEl=function(){return this._elList;};YAHOO.widget.AutoComplete.prototype.getListItemMatch=function(A){if(A._sResultMatch){return A._sResultMatch;}else{return null;}};YAHOO.widget.AutoComplete.prototype.getListItemData=function(A){if(A._oResultData){return A._oResultData;}else{return null;}};YAHOO.widget.AutoComplete.prototype.getListItemIndex=function(A){if(YAHOO.lang.isNumber(A._nItemIndex)){return A._nItemIndex;}else{return null;}};YAHOO.widget.AutoComplete.prototype.setHeader=function(B){if(this._elHeader){var A=this._elHeader;if(B){A.innerHTML=B;A.style.display="block";}else{A.innerHTML="";A.style.display="none";}}};YAHOO.widget.AutoComplete.prototype.setFooter=function(B){if(this._elFooter){var A=this._elFooter;if(B){A.innerHTML=B;A.style.display="block";}else{A.innerHTML="";A.style.display="none";}}};YAHOO.widget.AutoComplete.prototype.setBody=function(A){if(this._elBody){var B=this._elBody;YAHOO.util.Event.purgeElement(B,true);if(A){B.innerHTML=A;B.style.display="block";}else{B.innerHTML="";B.style.display="none";}this._elList=null;}};YAHOO.widget.AutoComplete.prototype.generateRequest=function(B){var A=this.dataSource.dataType;if(A===YAHOO.util.DataSourceBase.TYPE_XHR){if(!this.dataSource.connMethodPost){B=(this.queryQuestionMark?"?":"")+(this.dataSource.scriptQueryParam||"query")+"="+B+(this.dataSource.scriptQueryAppend?("&"+this.dataSource.scriptQueryAppend):"");}else{B=(this.dataSource.scriptQueryParam||"query")+"="+B+(this.dataSource.scriptQueryAppend?("&"+this.dataSource.scriptQueryAppend):"");}}else{if(A===YAHOO.util.DataSourceBase.TYPE_SCRIPTNODE){B="&"+(this.dataSource.scriptQueryParam||"query")+"="+B+(this.dataSource.scriptQueryAppend?("&"+this.dataSource.scriptQueryAppend):"");}}return B;};YAHOO.widget.AutoComplete.prototype.sendQuery=function(B){this._bFocused=null;var A=(this.delimChar)?this._elTextbox.value+B:B;this._sendQuery(A);};YAHOO.widget.AutoComplete.prototype.collapseContainer=function(){this._toggleContainer(false);};YAHOO.widget.AutoComplete.prototype.getSubsetMatches=function(E){var D,C,A;for(var B=E.length;B>=this.minQueryLength;B--){A=this.generateRequest(E.substr(0,B));this.dataRequestEvent.fire(this,D,A);C=this.dataSource.getCachedResponse(A);if(C){return this.filterResults.apply(this.dataSource,[E,C,C,{scope:this}]);}}return null;};YAHOO.widget.AutoComplete.prototype.preparseRawResponse=function(C,B,A){var D=((this.responseStripAfter!=="")&&(B.indexOf))?B.indexOf(this.responseStripAfter):-1;if(D!=-1){B=B.substring(0,D);}return B;};YAHOO.widget.AutoComplete.prototype.filterResults=function(J,L,P,K){if(K&&K.argument&&K.argument.query){J=K.argument.query;}if(J&&J!==""){P=YAHOO.widget.AutoComplete._cloneObject(P);var H=K.scope,O=this,B=P.results,M=[],D=false,I=(O.queryMatchCase||H.queryMatchCase),A=(O.queryMatchContains||H.queryMatchContains);for(var C=B.length-1;C>=0;C--){var F=B[C];var E=null;if(YAHOO.lang.isString(F)){E=F;}else{if(YAHOO.lang.isArray(F)){E=F[0];}else{if(this.responseSchema.fields){var N=this.responseSchema.fields[0].key||this.responseSchema.fields[0];E=F[N];}else{if(this.key){E=F[this.key];}}}}if(YAHOO.lang.isString(E)){var G=(I)?E.indexOf(decodeURIComponent(J)):E.toLowerCase().indexOf(decodeURIComponent(J).toLowerCase());if((!A&&(G===0))||(A&&(G>-1))){M.unshift(F);}}}P.results=M;}else{}return P;};YAHOO.widget.AutoComplete.prototype.handleResponse=function(C,A,B){if((this instanceof YAHOO.widget.AutoComplete)&&this._sName){this._populateList(C,A,B);}};YAHOO.widget.AutoComplete.prototype.doBeforeLoadData=function(C,A,B){return true;};YAHOO.widget.AutoComplete.prototype.formatResult=function(B,D,A){var C=(A)?A:"";return C;};YAHOO.widget.AutoComplete.prototype.doBeforeExpandContainer=function(D,A,C,B){return true;};YAHOO.widget.AutoComplete.prototype.destroy=function(){var B=this.toString();var A=this._elTextbox;var D=this._elContainer;this.textboxFocusEvent.unsubscribeAll();this.textboxKeyEvent.unsubscribeAll();this.dataRequestEvent.unsubscribeAll();this.dataReturnEvent.unsubscribeAll();this.dataErrorEvent.unsubscribeAll();this.containerPopulateEvent.unsubscribeAll();this.containerExpandEvent.unsubscribeAll();this.typeAheadEvent.unsubscribeAll();this.itemMouseOverEvent.unsubscribeAll();this.itemMouseOutEvent.unsubscribeAll();this.itemArrowToEvent.unsubscribeAll();this.itemArrowFromEvent.unsubscribeAll();this.itemSelectEvent.unsubscribeAll();this.unmatchedItemSelectEvent.unsubscribeAll();this.selectionEnforceEvent.unsubscribeAll();this.containerCollapseEvent.unsubscribeAll();this.textboxBlurEvent.unsubscribeAll();this.textboxChangeEvent.unsubscribeAll();YAHOO.util.Event.purgeElement(A,true);YAHOO.util.Event.purgeElement(D,true);D.innerHTML="";for(var C in this){if(YAHOO.lang.hasOwnProperty(this,C)){this[C]=null;}}};YAHOO.widget.AutoComplete.prototype.textboxFocusEvent=null;YAHOO.widget.AutoComplete.prototype.textboxKeyEvent=null;YAHOO.widget.AutoComplete.prototype.dataRequestEvent=null;YAHOO.widget.AutoComplete.prototype.dataReturnEvent=null;YAHOO.widget.AutoComplete.prototype.dataErrorEvent=null;YAHOO.widget.AutoComplete.prototype.containerPopulateEvent=null;YAHOO.widget.AutoComplete.prototype.containerExpandEvent=null;YAHOO.widget.AutoComplete.prototype.typeAheadEvent=null;YAHOO.widget.AutoComplete.prototype.itemMouseOverEvent=null;YAHOO.widget.AutoComplete.prototype.itemMouseOutEvent=null;YAHOO.widget.AutoComplete.prototype.itemArrowToEvent=null;YAHOO.widget.AutoComplete.prototype.itemArrowFromEvent=null;YAHOO.widget.AutoComplete.prototype.itemSelectEvent=null;YAHOO.widget.AutoComplete.prototype.unmatchedItemSelectEvent=null;YAHOO.widget.AutoComplete.prototype.selectionEnforceEvent=null;YAHOO.widget.AutoComplete.prototype.containerCollapseEvent=null;YAHOO.widget.AutoComplete.prototype.textboxBlurEvent=null;
YAHOO.widget.AutoComplete.prototype.textboxChangeEvent=null;YAHOO.widget.AutoComplete._nIndex=0;YAHOO.widget.AutoComplete.prototype._sName=null;YAHOO.widget.AutoComplete.prototype._elTextbox=null;YAHOO.widget.AutoComplete.prototype._elContainer=null;YAHOO.widget.AutoComplete.prototype._elContent=null;YAHOO.widget.AutoComplete.prototype._elHeader=null;YAHOO.widget.AutoComplete.prototype._elBody=null;YAHOO.widget.AutoComplete.prototype._elFooter=null;YAHOO.widget.AutoComplete.prototype._elShadow=null;YAHOO.widget.AutoComplete.prototype._elIFrame=null;YAHOO.widget.AutoComplete.prototype._bFocused=null;YAHOO.widget.AutoComplete.prototype._oAnim=null;YAHOO.widget.AutoComplete.prototype._bContainerOpen=false;YAHOO.widget.AutoComplete.prototype._bOverContainer=false;YAHOO.widget.AutoComplete.prototype._elList=null;YAHOO.widget.AutoComplete.prototype._nDisplayedItems=0;YAHOO.widget.AutoComplete.prototype._sCurQuery=null;YAHOO.widget.AutoComplete.prototype._sPastSelections="";YAHOO.widget.AutoComplete.prototype._sInitInputValue=null;YAHOO.widget.AutoComplete.prototype._elCurListItem=null;YAHOO.widget.AutoComplete.prototype._bItemSelected=false;YAHOO.widget.AutoComplete.prototype._nKeyCode=null;YAHOO.widget.AutoComplete.prototype._nDelayID=-1;YAHOO.widget.AutoComplete.prototype._nTypeAheadDelayID=-1;YAHOO.widget.AutoComplete.prototype._iFrameSrc="javascript:false;";YAHOO.widget.AutoComplete.prototype._queryInterval=null;YAHOO.widget.AutoComplete.prototype._sLastTextboxValue=null;YAHOO.widget.AutoComplete.prototype._initProps=function(){var B=this.minQueryLength;if(!YAHOO.lang.isNumber(B)){this.minQueryLength=1;}var E=this.maxResultsDisplayed;if(!YAHOO.lang.isNumber(E)||(E<1)){this.maxResultsDisplayed=10;}var F=this.queryDelay;if(!YAHOO.lang.isNumber(F)||(F<0)){this.queryDelay=0.2;}var C=this.typeAheadDelay;if(!YAHOO.lang.isNumber(C)||(C<0)){this.typeAheadDelay=0.2;}var A=this.delimChar;if(YAHOO.lang.isString(A)&&(A.length>0)){this.delimChar=[A];}else{if(!YAHOO.lang.isArray(A)){this.delimChar=null;}}var D=this.animSpeed;if((this.animHoriz||this.animVert)&&YAHOO.util.Anim){if(!YAHOO.lang.isNumber(D)||(D<0)){this.animSpeed=0.3;}if(!this._oAnim){this._oAnim=new YAHOO.util.Anim(this._elContent,{},this.animSpeed);}else{this._oAnim.duration=this.animSpeed;}}if(this.forceSelection&&A){}};YAHOO.widget.AutoComplete.prototype._initContainerHelperEls=function(){if(this.useShadow&&!this._elShadow){var A=document.createElement("div");A.className="yui-ac-shadow";A.style.width=0;A.style.height=0;this._elShadow=this._elContainer.appendChild(A);}if(this.useIFrame&&!this._elIFrame){var B=document.createElement("iframe");B.src=this._iFrameSrc;B.frameBorder=0;B.scrolling="no";B.style.position="absolute";B.style.width=0;B.style.height=0;B.tabIndex=-1;B.style.padding=0;this._elIFrame=this._elContainer.appendChild(B);}};YAHOO.widget.AutoComplete.prototype._initContainerEl=function(){YAHOO.util.Dom.addClass(this._elContainer,"yui-ac-container");if(!this._elContent){var C=document.createElement("div");C.className="yui-ac-content";C.style.display="none";this._elContent=this._elContainer.appendChild(C);var B=document.createElement("div");B.className="yui-ac-hd";B.style.display="none";this._elHeader=this._elContent.appendChild(B);var D=document.createElement("div");D.className="yui-ac-bd";this._elBody=this._elContent.appendChild(D);var A=document.createElement("div");A.className="yui-ac-ft";A.style.display="none";this._elFooter=this._elContent.appendChild(A);}else{}};YAHOO.widget.AutoComplete.prototype._initListEl=function(){var C=this.maxResultsDisplayed;var A=this._elList||document.createElement("ul");var B;while(A.childNodes.length<C){B=document.createElement("li");B.style.display="none";B._nItemIndex=A.childNodes.length;A.appendChild(B);}if(!this._elList){var D=this._elBody;YAHOO.util.Event.purgeElement(D,true);D.innerHTML="";this._elList=D.appendChild(A);}};YAHOO.widget.AutoComplete.prototype._focus=function(){var A=this;setTimeout(function(){try{A._elTextbox.focus();}catch(B){}},0);};YAHOO.widget.AutoComplete.prototype._enableIntervalDetection=function(){var A=this;if(!A._queryInterval&&A.queryInterval){A._queryInterval=setInterval(function(){A._onInterval();},A.queryInterval);}};YAHOO.widget.AutoComplete.prototype._onInterval=function(){var A=this._elTextbox.value;var B=this._sLastTextboxValue;if(A!=B){this._sLastTextboxValue=A;this._sendQuery(A);}};YAHOO.widget.AutoComplete.prototype._clearInterval=function(){if(this._queryInterval){clearInterval(this._queryInterval);this._queryInterval=null;}};YAHOO.widget.AutoComplete.prototype._isIgnoreKey=function(A){if((A==9)||(A==13)||(A==16)||(A==17)||(A>=18&&A<=20)||(A==27)||(A>=33&&A<=35)||(A>=36&&A<=40)||(A>=44&&A<=45)||(A==229)){return true;}return false;};YAHOO.widget.AutoComplete.prototype._sendQuery=function(D){if(this.minQueryLength<0){this._toggleContainer(false);return;}if(this.delimChar){var A=this._extractQuery(D);D=A.query;this._sPastSelections=A.previous;}if((D&&(D.length<this.minQueryLength))||(!D&&this.minQueryLength>0)){if(this._nDelayID!=-1){clearTimeout(this._nDelayID);}this._toggleContainer(false);return;}D=encodeURIComponent(D);this._nDelayID=-1;if(this.dataSource.queryMatchSubset||this.queryMatchSubset){var C=this.getSubsetMatches(D);if(C){this.handleResponse(D,C,{query:D});return;}}if(this.responseStripAfter){this.dataSource.doBeforeParseData=this.preparseRawResponse;}if(this.applyLocalFilter){this.dataSource.doBeforeCallback=this.filterResults;}var B=this.generateRequest(D);this.dataRequestEvent.fire(this,D,B);this.dataSource.sendRequest(B,{success:this.handleResponse,failure:this.handleResponse,scope:this,argument:{query:D}});};YAHOO.widget.AutoComplete.prototype._populateList=function(K,F,C){if(this._nTypeAheadDelayID!=-1){clearTimeout(this._nTypeAheadDelayID);}K=(C&&C.query)?C.query:K;var H=this.doBeforeLoadData(K,F,C);if(H&&!F.error){this.dataReturnEvent.fire(this,K,F.results);if(this._bFocused||(this._bFocused===null)){var M=decodeURIComponent(K);this._sCurQuery=M;
this._bItemSelected=false;var R=F.results,A=Math.min(R.length,this.maxResultsDisplayed),J=(this.dataSource.responseSchema.fields)?(this.dataSource.responseSchema.fields[0].key||this.dataSource.responseSchema.fields[0]):0;if(A>0){if(!this._elList||(this._elList.childNodes.length<A)){this._initListEl();}this._initContainerHelperEls();var I=this._elList.childNodes;for(var Q=A-1;Q>=0;Q--){var P=I[Q],E=R[Q];if(this.resultTypeList){var B=[];B[0]=(YAHOO.lang.isString(E))?E:E[J]||E[this.key];var L=this.dataSource.responseSchema.fields;if(YAHOO.lang.isArray(L)&&(L.length>1)){for(var N=1,S=L.length;N<S;N++){B[B.length]=E[L[N].key||L[N]];}}else{if(YAHOO.lang.isArray(E)){B=E;}else{if(YAHOO.lang.isString(E)){B=[E];}else{B[1]=E;}}}E=B;}P._sResultMatch=(YAHOO.lang.isString(E))?E:(YAHOO.lang.isArray(E))?E[0]:(E[J]||"");P._oResultData=E;P.innerHTML=this.formatResult(E,M,P._sResultMatch);P.style.display="";}if(A<I.length){var G;for(var O=I.length-1;O>=A;O--){G=I[O];G.style.display="none";}}this._nDisplayedItems=A;this.containerPopulateEvent.fire(this,K,R);if(this.autoHighlight){var D=this._elList.firstChild;this._toggleHighlight(D,"to");this.itemArrowToEvent.fire(this,D);this._typeAhead(D,K);}else{this._toggleHighlight(this._elCurListItem,"from");}H=this.doBeforeExpandContainer(this._elTextbox,this._elContainer,K,R);this._toggleContainer(H);}else{this._toggleContainer(false);}return;}}else{this.dataErrorEvent.fire(this,K);}};YAHOO.widget.AutoComplete.prototype._clearSelection=function(){var A=(this.delimChar)?this._extractQuery(this._elTextbox.value):{previous:"",query:this._elTextbox.value};this._elTextbox.value=A.previous;this.selectionEnforceEvent.fire(this,A.query);};YAHOO.widget.AutoComplete.prototype._textMatchesOption=function(){var A=null;for(var B=0;B<this._nDisplayedItems;B++){var C=this._elList.childNodes[B];var D=(""+C._sResultMatch).toLowerCase();if(D==this._sCurQuery.toLowerCase()){A=C;break;}}return(A);};YAHOO.widget.AutoComplete.prototype._typeAhead=function(B,D){if(!this.typeAhead||(this._nKeyCode==8)){return;}var A=this,C=this._elTextbox;if(C.setSelectionRange||C.createTextRange){this._nTypeAheadDelayID=setTimeout(function(){var F=C.value.length;A._updateValue(B);var G=C.value.length;A._selectText(C,F,G);var E=C.value.substr(F,G);A.typeAheadEvent.fire(A,D,E);},(this.typeAheadDelay*1000));}};YAHOO.widget.AutoComplete.prototype._selectText=function(D,A,B){if(D.setSelectionRange){D.setSelectionRange(A,B);}else{if(D.createTextRange){var C=D.createTextRange();C.moveStart("character",A);C.moveEnd("character",B-D.value.length);C.select();}else{D.select();}}};YAHOO.widget.AutoComplete.prototype._extractQuery=function(H){var C=this.delimChar,F=-1,G,E,B=C.length-1,D;for(;B>=0;B--){G=H.lastIndexOf(C[B]);if(G>F){F=G;}}if(C[B]==" "){for(var A=C.length-1;A>=0;A--){if(H[F-1]==C[A]){F--;break;}}}if(F>-1){E=F+1;while(H.charAt(E)==" "){E+=1;}D=H.substring(0,E);H=H.substr(E);}else{D="";}return{previous:D,query:H};};YAHOO.widget.AutoComplete.prototype._toggleContainerHelpers=function(D){var E=this._elContent.offsetWidth+"px";var B=this._elContent.offsetHeight+"px";if(this.useIFrame&&this._elIFrame){var C=this._elIFrame;if(D){C.style.width=E;C.style.height=B;C.style.padding="";}else{C.style.width=0;C.style.height=0;C.style.padding=0;}}if(this.useShadow&&this._elShadow){var A=this._elShadow;if(D){A.style.width=E;A.style.height=B;}else{A.style.width=0;A.style.height=0;}}};YAHOO.widget.AutoComplete.prototype._toggleContainer=function(I){var D=this._elContainer;if(this.alwaysShowContainer&&this._bContainerOpen){return;}if(!I){this._toggleHighlight(this._elCurListItem,"from");this._nDisplayedItems=0;this._sCurQuery=null;if(this._elContent.style.display=="none"){return;}}var A=this._oAnim;if(A&&A.getEl()&&(this.animHoriz||this.animVert)){if(A.isAnimated()){A.stop(true);}var G=this._elContent.cloneNode(true);D.appendChild(G);G.style.top="-9000px";G.style.width="";G.style.height="";G.style.display="";var F=G.offsetWidth;var C=G.offsetHeight;var B=(this.animHoriz)?0:F;var E=(this.animVert)?0:C;A.attributes=(I)?{width:{to:F},height:{to:C}}:{width:{to:B},height:{to:E}};if(I&&!this._bContainerOpen){this._elContent.style.width=B+"px";this._elContent.style.height=E+"px";}else{this._elContent.style.width=F+"px";this._elContent.style.height=C+"px";}D.removeChild(G);G=null;var H=this;var J=function(){A.onComplete.unsubscribeAll();if(I){H._toggleContainerHelpers(true);H._bContainerOpen=I;H.containerExpandEvent.fire(H);}else{H._elContent.style.display="none";H._bContainerOpen=I;H.containerCollapseEvent.fire(H);}};this._toggleContainerHelpers(false);this._elContent.style.display="";A.onComplete.subscribe(J);A.animate();}else{if(I){this._elContent.style.display="";this._toggleContainerHelpers(true);this._bContainerOpen=I;this.containerExpandEvent.fire(this);}else{this._toggleContainerHelpers(false);this._elContent.style.display="none";this._bContainerOpen=I;this.containerCollapseEvent.fire(this);}}};YAHOO.widget.AutoComplete.prototype._toggleHighlight=function(A,C){if(A){var B=this.highlightClassName;if(this._elCurListItem){YAHOO.util.Dom.removeClass(this._elCurListItem,B);this._elCurListItem=null;}if((C=="to")&&B){YAHOO.util.Dom.addClass(A,B);this._elCurListItem=A;}}};YAHOO.widget.AutoComplete.prototype._togglePrehighlight=function(B,C){if(B==this._elCurListItem){return;}var A=this.prehighlightClassName;if((C=="mouseover")&&A){YAHOO.util.Dom.addClass(B,A);}else{YAHOO.util.Dom.removeClass(B,A);}};YAHOO.widget.AutoComplete.prototype._updateValue=function(C){if(!this.suppressInputUpdate){var F=this._elTextbox;var E=(this.delimChar)?(this.delimChar[0]||this.delimChar):null;var B=C._sResultMatch;var D="";if(E){D=this._sPastSelections;D+=B+E;if(E!=" "){D+=" ";}}else{D=B;}F.value=D;if(F.type=="textarea"){F.scrollTop=F.scrollHeight;}var A=F.value.length;this._selectText(F,A,A);this._elCurListItem=C;}};YAHOO.widget.AutoComplete.prototype._selectItem=function(A){this._bItemSelected=true;this._updateValue(A);this._sPastSelections=this._elTextbox.value;
this._clearInterval();this.itemSelectEvent.fire(this,A,A._oResultData);this._toggleContainer(false);};YAHOO.widget.AutoComplete.prototype._jumpSelection=function(){if(this._elCurListItem){this._selectItem(this._elCurListItem);}else{this._toggleContainer(false);}};YAHOO.widget.AutoComplete.prototype._moveSelection=function(G){if(this._bContainerOpen){var H=this._elCurListItem,D=-1;if(H){D=H._nItemIndex;}var E=(G==40)?(D+1):(D-1);if(E<-2||E>=this._nDisplayedItems){return;}if(H){this._toggleHighlight(H,"from");this.itemArrowFromEvent.fire(this,H);}if(E==-1){if(this.delimChar){this._elTextbox.value=this._sPastSelections+this._sCurQuery;}else{this._elTextbox.value=this._sCurQuery;}return;}if(E==-2){this._toggleContainer(false);return;}var F=this._elList.childNodes[E],B=this._elContent,C=YAHOO.util.Dom.getStyle(B,"overflow"),I=YAHOO.util.Dom.getStyle(B,"overflowY"),A=((C=="auto")||(C=="scroll")||(I=="auto")||(I=="scroll"));if(A&&(E>-1)&&(E<this._nDisplayedItems)){if(G==40){if((F.offsetTop+F.offsetHeight)>(B.scrollTop+B.offsetHeight)){B.scrollTop=(F.offsetTop+F.offsetHeight)-B.offsetHeight;}else{if((F.offsetTop+F.offsetHeight)<B.scrollTop){B.scrollTop=F.offsetTop;}}}else{if(F.offsetTop<B.scrollTop){this._elContent.scrollTop=F.offsetTop;}else{if(F.offsetTop>(B.scrollTop+B.offsetHeight)){this._elContent.scrollTop=(F.offsetTop+F.offsetHeight)-B.offsetHeight;}}}}this._toggleHighlight(F,"to");this.itemArrowToEvent.fire(this,F);if(this.typeAhead){this._updateValue(F);}}};YAHOO.widget.AutoComplete.prototype._onContainerMouseover=function(A,C){var D=YAHOO.util.Event.getTarget(A);var B=D.nodeName.toLowerCase();while(D&&(B!="table")){switch(B){case"body":return;case"li":if(C.prehighlightClassName){C._togglePrehighlight(D,"mouseover");}else{C._toggleHighlight(D,"to");}C.itemMouseOverEvent.fire(C,D);break;case"div":if(YAHOO.util.Dom.hasClass(D,"yui-ac-container")){C._bOverContainer=true;return;}break;default:break;}D=D.parentNode;if(D){B=D.nodeName.toLowerCase();}}};YAHOO.widget.AutoComplete.prototype._onContainerMouseout=function(A,C){var D=YAHOO.util.Event.getTarget(A);var B=D.nodeName.toLowerCase();while(D&&(B!="table")){switch(B){case"body":return;case"li":if(C.prehighlightClassName){C._togglePrehighlight(D,"mouseout");}else{C._toggleHighlight(D,"from");}C.itemMouseOutEvent.fire(C,D);break;case"ul":C._toggleHighlight(C._elCurListItem,"to");break;case"div":if(YAHOO.util.Dom.hasClass(D,"yui-ac-container")){C._bOverContainer=false;return;}break;default:break;}D=D.parentNode;if(D){B=D.nodeName.toLowerCase();}}};YAHOO.widget.AutoComplete.prototype._onContainerClick=function(A,C){var D=YAHOO.util.Event.getTarget(A);var B=D.nodeName.toLowerCase();while(D&&(B!="table")){switch(B){case"body":return;case"li":C._toggleHighlight(D,"to");C._selectItem(D);return;default:break;}D=D.parentNode;if(D){B=D.nodeName.toLowerCase();}}};YAHOO.widget.AutoComplete.prototype._onContainerScroll=function(A,B){B._focus();};YAHOO.widget.AutoComplete.prototype._onContainerResize=function(A,B){B._toggleContainerHelpers(B._bContainerOpen);};YAHOO.widget.AutoComplete.prototype._onTextboxKeyDown=function(A,B){var C=A.keyCode;if(B._nTypeAheadDelayID!=-1){clearTimeout(B._nTypeAheadDelayID);}switch(C){case 9:if(!YAHOO.env.ua.opera&&(navigator.userAgent.toLowerCase().indexOf("mac")==-1)||(YAHOO.env.ua.webkit>420)){if(B._elCurListItem){if(B.delimChar&&(B._nKeyCode!=C)){if(B._bContainerOpen){YAHOO.util.Event.stopEvent(A);}}B._selectItem(B._elCurListItem);}else{B._toggleContainer(false);}}break;case 13:if(!YAHOO.env.ua.opera&&(navigator.userAgent.toLowerCase().indexOf("mac")==-1)||(YAHOO.env.ua.webkit>420)){if(B._elCurListItem){if(B._nKeyCode!=C){if(B._bContainerOpen){YAHOO.util.Event.stopEvent(A);}}B._selectItem(B._elCurListItem);}else{B._toggleContainer(false);}}break;case 27:B._toggleContainer(false);return;case 39:B._jumpSelection();break;case 38:if(B._bContainerOpen){YAHOO.util.Event.stopEvent(A);B._moveSelection(C);}break;case 40:if(B._bContainerOpen){YAHOO.util.Event.stopEvent(A);B._moveSelection(C);}break;default:B._bItemSelected=false;B._toggleHighlight(B._elCurListItem,"from");B.textboxKeyEvent.fire(B,C);break;}if(C===18){B._enableIntervalDetection();}B._nKeyCode=C;};YAHOO.widget.AutoComplete.prototype._onTextboxKeyPress=function(A,B){var C=A.keyCode;if(YAHOO.env.ua.opera||(navigator.userAgent.toLowerCase().indexOf("mac")!=-1)&&(YAHOO.env.ua.webkit<420)){switch(C){case 9:if(B._bContainerOpen){if(B.delimChar){YAHOO.util.Event.stopEvent(A);}if(B._elCurListItem){B._selectItem(B._elCurListItem);}else{B._toggleContainer(false);}}break;case 13:if(B._bContainerOpen){YAHOO.util.Event.stopEvent(A);if(B._elCurListItem){B._selectItem(B._elCurListItem);}else{B._toggleContainer(false);}}break;default:break;}}else{if(C==229){B._enableIntervalDetection();}}};YAHOO.widget.AutoComplete.prototype._onTextboxKeyUp=function(A,C){var B=this.value;C._initProps();var D=A.keyCode;if(C._isIgnoreKey(D)){return;}if(C._nDelayID!=-1){clearTimeout(C._nDelayID);}C._nDelayID=setTimeout(function(){C._sendQuery(B);},(C.queryDelay*1000));};YAHOO.widget.AutoComplete.prototype._onTextboxFocus=function(A,B){if(!B._bFocused){B._elTextbox.setAttribute("autocomplete","off");B._bFocused=true;B._sInitInputValue=B._elTextbox.value;B.textboxFocusEvent.fire(B);}};YAHOO.widget.AutoComplete.prototype._onTextboxBlur=function(A,C){if(!C._bOverContainer||(C._nKeyCode==9)){if(!C._bItemSelected){var B=C._textMatchesOption();if(!C._bContainerOpen||(C._bContainerOpen&&(B===null))){if(C.forceSelection){C._clearSelection();}else{C.unmatchedItemSelectEvent.fire(C,C._sCurQuery);}}else{if(C.forceSelection){C._selectItem(B);}}}C._clearInterval();C._bFocused=false;if(C._sInitInputValue!==C._elTextbox.value){C.textboxChangeEvent.fire(C);}C.textboxBlurEvent.fire(C);C._toggleContainer(false);}else{C._focus();}};YAHOO.widget.AutoComplete.prototype._onWindowUnload=function(A,B){if(B&&B._elTextbox&&B.allowBrowserAutocomplete){B._elTextbox.setAttribute("autocomplete","on");}};YAHOO.widget.AutoComplete.prototype.doBeforeSendQuery=function(A){return this.generateRequest(A);
};YAHOO.widget.AutoComplete.prototype.getListItems=function(){var C=[],B=this._elList.childNodes;for(var A=B.length-1;A>=0;A--){C[A]=B[A];}return C;};YAHOO.widget.AutoComplete._cloneObject=function(D){if(!YAHOO.lang.isValue(D)){return D;}var F={};if(YAHOO.lang.isFunction(D)){F=D;}else{if(YAHOO.lang.isArray(D)){var E=[];for(var C=0,B=D.length;C<B;C++){E[C]=YAHOO.widget.AutoComplete._cloneObject(D[C]);}F=E;}else{if(YAHOO.lang.isObject(D)){for(var A in D){if(YAHOO.lang.hasOwnProperty(D,A)){if(YAHOO.lang.isValue(D[A])&&YAHOO.lang.isObject(D[A])||YAHOO.lang.isArray(D[A])){F[A]=YAHOO.widget.AutoComplete._cloneObject(D[A]);}else{F[A]=D[A];}}}}else{F=D;}}}return F;};YAHOO.register("autocomplete",YAHOO.widget.AutoComplete,{version:"2.7.0",build:"1799"});/**
 * SWFUpload: http://www.swfupload.org, http://swfupload.googlecode.com
 *
 * mmSWFUpload 1.0: Flash upload dialog - http://profandesign.se/swfupload/,  http://www.vinterwebb.se/
 *
 * SWFUpload is (c) 2006-2007 Lars Huring, Olov Nilzén and Mammon Media and is released under the MIT License:
 * http://www.opensource.org/licenses/mit-license.php
 *
 * SWFUpload 2 is (c) 2007-2008 Jake Roberts and is released under the MIT License:
 * http://www.opensource.org/licenses/mit-license.php
 *
 */


/* ******************* */
/* Constructor & Init  */
/* ******************* */

var SWFUpload = function (settings) {
	this.initSWFUpload(settings);
};

SWFUpload.prototype.initSWFUpload = function (settings) {
	try {
		this.customSettings = {};	// A container where developers can place their own settings associated with this instance.
		this.settings = settings;
		this.eventQueue = [];
		this.movieName = "SWFUpload_" + SWFUpload.movieCount++;
		this.movieElement = null;

		// Setup global control tracking
		SWFUpload.instances[this.movieName] = this;

		// Load the settings.  Load the Flash movie.
		this.initSettings();
		this.loadFlash();
		this.displayDebugInfo();
	} catch (ex) {
		delete SWFUpload.instances[this.movieName];
		throw ex;
	}
};

/* *************** */
/* Static Members  */
/* *************** */
SWFUpload.instances = {};
SWFUpload.movieCount = 0;
SWFUpload.version = "2.2.0 Alpha";
SWFUpload.QUEUE_ERROR = {
	QUEUE_LIMIT_EXCEEDED	  		: -100,
	FILE_EXCEEDS_SIZE_LIMIT  		: -110,
	ZERO_BYTE_FILE			  		: -120,
	INVALID_FILETYPE		  		: -130
};
SWFUpload.UPLOAD_ERROR = {
	HTTP_ERROR				  		: -200,
	MISSING_UPLOAD_URL	      		: -210,
	IO_ERROR				  		: -220,
	SECURITY_ERROR			  		: -230,
	UPLOAD_LIMIT_EXCEEDED	  		: -240,
	UPLOAD_FAILED			  		: -250,
	SPECIFIED_FILE_ID_NOT_FOUND		: -260,
	FILE_VALIDATION_FAILED	  		: -270,
	FILE_CANCELLED			  		: -280,
	UPLOAD_STOPPED					: -290
};
SWFUpload.FILE_STATUS = {
	QUEUED		 : -1,
	IN_PROGRESS	 : -2,
	ERROR		 : -3,
	COMPLETE	 : -4,
	CANCELLED	 : -5
};
SWFUpload.BUTTON_ACTION = {
	SELECT_FILE  : -100,
	SELECT_FILES : -110,
	START_UPLOAD : -120
};

/* ******************** */
/* Instance Members  */
/* ******************** */

// Private: initSettings ensures that all the
// settings are set, getting a default value if one was not assigned.
SWFUpload.prototype.initSettings = function () {
	this.ensureDefault = function (settingName, defaultValue) {
		this.settings[settingName] = (this.settings[settingName] == undefined) ? defaultValue : this.settings[settingName];
	};
	
	// Upload backend settings
	this.ensureDefault("upload_url", "");
	this.ensureDefault("file_post_name", "Filedata");
	this.ensureDefault("post_params", {});
	this.ensureDefault("use_query_string", false);
	this.ensureDefault("requeue_on_error", false);
	
	// File Settings
	this.ensureDefault("file_types", "*.*");
	this.ensureDefault("file_types_description", "All Files");
	this.ensureDefault("file_size_limit", 0);	// Default zero means "unlimited"
	this.ensureDefault("file_upload_limit", 0);
	this.ensureDefault("file_queue_limit", 0);

	// Flash Settings
	this.ensureDefault("flash_url", "swfupload.swf");
	this.ensureDefault("prevent_swf_caching", true);
	
	// Button Settings
	this.ensureDefault("button_image_url", "");
	this.ensureDefault("button_width", 1);
	this.ensureDefault("button_height", 1);
	this.ensureDefault("button_text", "");
	this.ensureDefault("button_text_style", "color: #000000; font-size: 16pt;");
	this.ensureDefault("button_text_top_padding", 0);
	this.ensureDefault("button_text_left_padding", 0);
	this.ensureDefault("button_action", SWFUpload.BUTTON_ACTION.SELECT_FILES);
	this.ensureDefault("button_disabled", false);
	this.ensureDefault("button_placeholder_id", null);
	
	// Debug Settings
	this.ensureDefault("debug", false);
	this.settings.debug_enabled = this.settings.debug;	// Here to maintain v2 API
	
	// Event Handlers
	this.settings.return_upload_start_handler = this.returnUploadStart;
	this.ensureDefault("swfupload_loaded_handler", null);
	this.ensureDefault("file_dialog_start_handler", null);
	this.ensureDefault("file_queued_handler", null);
	this.ensureDefault("file_queue_error_handler", null);
	this.ensureDefault("file_dialog_complete_handler", null);
	
	this.ensureDefault("upload_start_handler", null);
	this.ensureDefault("upload_progress_handler", null);
	this.ensureDefault("upload_error_handler", null);
	this.ensureDefault("upload_success_handler", null);
	this.ensureDefault("upload_complete_handler", null);
	
	this.ensureDefault("debug_handler", this.debugMessage);

	this.ensureDefault("custom_settings", {});

	// Other settings
	this.customSettings = this.settings.custom_settings;
	
	// Update the flash url if needed
	if (this.settings.prevent_swf_caching) {
		this.settings.flash_url = this.settings.flash_url + "?swfuploadrnd=" + Math.floor(Math.random() * 999999999);
	}
	
	delete this.ensureDefault;
};

SWFUpload.prototype.loadFlash = function () {
	if (this.settings.button_placeholder_id !== "") {
		this.replaceWithFlash();
	} else {
		this.appendFlash();
	}
};

// Private: appendFlash gets the HTML tag for the Flash
// It then appends the flash to the body
SWFUpload.prototype.appendFlash = function () {
	var targetElement, container;

	// Make sure an element with the ID we are going to use doesn't already exist
	if (document.getElementById(this.movieName) !== null) {
		throw "ID " + this.movieName + " is already in use. The Flash Object could not be added";
	}

	// Get the body tag where we will be adding the flash movie
	targetElement = document.getElementsByTagName("body")[0];

	if (targetElement == undefined) {
		throw "Could not find the 'body' element.";
	}

	// Append the container and load the flash
	container = document.createElement("div");
	container.style.width = "1px";
	container.style.height = "1px";
	container.style.overflow = "hidden";

	targetElement.appendChild(container);
	container.innerHTML = this.getFlashHTML();	// Using innerHTML is non-standard but the only sensible way to dynamically add Flash in IE (and maybe other browsers)
};

// Private: replaceWithFlash replaces the button_placeholder element with the flash movie.
SWFUpload.prototype.replaceWithFlash = function () {
	var targetElement, tempParent;

	// Make sure an element with the ID we are going to use doesn't already exist
	if (document.getElementById(this.movieName) !== null) {
		throw "ID " + this.movieName + " is already in use. The Flash Object could not be added";
	}

	// Get the element where we will be placing the flash movie
	targetElement = document.getElementById(this.settings.button_placeholder_id);

	if (targetElement == undefined) {
		throw "Could not find the placeholder element.";
	}

	// Append the container and load the flash
	tempParent = document.createElement("div");
	tempParent.innerHTML = this.getFlashHTML();	// Using innerHTML is non-standard but the only sensible way to dynamically add Flash in IE (and maybe other browsers)
	targetElement.parentNode.replaceChild(tempParent.firstChild, targetElement);

};

// Private: getFlashHTML generates the object tag needed to embed the flash in to the document
SWFUpload.prototype.getFlashHTML = function () {
	var transparent = this.settings.button_image_url === "" ? true : false;
	
	// Flash Satay object syntax: http://www.alistapart.com/articles/flashsatay
	return ['<object id="', this.movieName, '" type="application/x-shockwave-flash" data="', this.settings.flash_url, '" width="', this.settings.button_width, '" height="', this.settings.button_height, '" class="swfupload">',
				//'<param name="wmode" value="', transparent ? "transparent" : "window", '" />',
                '<param name="wmode" value="', "transparent", '" />',
				'<param name="movie" value="', this.settings.flash_url, '" />',
				'<param name="quality" value="high" />',
				'<param name="menu" value="false" />',
				'<param name="allowScriptAccess" value="always" />',
				'<param name="flashvars" value="' + this.getFlashVars() + '" />',
				'</object>'].join("");
};

// Private: getFlashVars builds the parameter string that will be passed
// to flash in the flashvars param.
SWFUpload.prototype.getFlashVars = function () {
	// Build a string from the post param object
	var paramString = this.buildParamString();

	// Build the parameter string
	return ["movieName=", encodeURIComponent(this.movieName),
			"&amp;uploadURL=", encodeURIComponent(this.settings.upload_url),
			"&amp;useQueryString=", encodeURIComponent(this.settings.use_query_string),
			"&amp;requeueOnError=", encodeURIComponent(this.settings.requeue_on_error),
			"&amp;params=", encodeURIComponent(paramString),
			"&amp;filePostName=", encodeURIComponent(this.settings.file_post_name),
			"&amp;fileTypes=", encodeURIComponent(this.settings.file_types),
			"&amp;fileTypesDescription=", encodeURIComponent(this.settings.file_types_description),
			"&amp;fileSizeLimit=", encodeURIComponent(this.settings.file_size_limit),
			"&amp;fileUploadLimit=", encodeURIComponent(this.settings.file_upload_limit),
			"&amp;fileQueueLimit=", encodeURIComponent(this.settings.file_queue_limit),
			"&amp;debugEnabled=", encodeURIComponent(this.settings.debug_enabled),
			"&amp;buttonImageURL=", encodeURIComponent(this.settings.button_image_url),
			"&amp;buttonWidth=", encodeURIComponent(this.settings.button_width),
			"&amp;buttonHeight=", encodeURIComponent(this.settings.button_height),
			"&amp;buttonText=", encodeURIComponent(this.settings.button_text),
			"&amp;buttonTextTopPadding=", encodeURIComponent(this.settings.button_text_top_padding),
			"&amp;buttonTextLeftPadding=", encodeURIComponent(this.settings.button_text_left_padding),
			"&amp;buttonTextStyle=", encodeURIComponent(this.settings.button_text_style),
			"&amp;buttonAction=", encodeURIComponent(this.settings.button_action),
			"&amp;buttonDisabled=", encodeURIComponent(this.settings.button_disabled)
		].join("");
};

// Public: getMovieElement retrieves the DOM reference to the Flash element added by SWFUpload
// The element is cached after the first lookup
SWFUpload.prototype.getMovieElement = function () {
	if (this.movieElement == undefined) {
		this.movieElement = document.getElementById(this.movieName);
	}

	if (this.movieElement === null) {
		throw "Could not find Flash element";
	}
	
	return this.movieElement;
};

// Private: buildParamString takes the name/value pairs in the post_params setting object
// and joins them up in to a string formatted "name=value&amp;name=value"
SWFUpload.prototype.buildParamString = function () {
	var postParams = this.settings.post_params; 
	var paramStringPairs = [];

	if (typeof(postParams) === "object") {
		for (var name in postParams) {
			if (postParams.hasOwnProperty(name)) {
				paramStringPairs.push(encodeURIComponent(name.toString()) + "=" + encodeURIComponent(postParams[name].toString()));
			}
		}
	}

	return paramStringPairs.join("&amp;");
};

// Public: Used to remove a SWFUpload instance from the page. This method strives to remove
// all references to the SWF, and other objects so memory is properly freed.
// Returns true if everything was destroyed. Returns a false if a failure occurs leaving SWFUpload in an inconsistant state.
SWFUpload.prototype.destroy = function () {
	try {
		// Make sure Flash is done before we try to remove it
		this.stopUpload();
		
		// Remove the SWFUpload DOM nodes
		var movieElement = null;
		try {
			movieElement = this.getMovieElement();
		} catch (ex) {
		}
		
		if (movieElement != undefined && movieElement.parentNode != undefined && typeof movieElement.parentNode.removeChild === "function") {
			var container = movieElement.parentNode;
			if (container != undefined) {
				container.removeChild(movieElement);
				if (container.parentNode != undefined && typeof container.parentNode.removeChild === "function") {
					container.parentNode.removeChild(container);
				}
			}
		}
		
		// Destroy references
		SWFUpload.instances[this.movieName] = null;
		delete SWFUpload.instances[this.movieName];

		delete this.movieElement;
		delete this.settings;
		delete this.customSettings;
		delete this.eventQueue;
		delete this.movieName;
		
		delete window[this.movieName];
		
		return true;
	} catch (ex1) {
		return false;
	}
};

// Public: displayDebugInfo prints out settings and configuration
// information about this SWFUpload instance.
// This function (and any references to it) can be deleted when placing
// SWFUpload in production.
SWFUpload.prototype.displayDebugInfo = function () {
	this.debug(
		[
			"---SWFUpload Instance Info---\n",
			"Version: ", SWFUpload.version, "\n",
			"Movie Name: ", this.movieName, "\n",
			"Settings:\n",
			"\t", "upload_url:               ", this.settings.upload_url, "\n",
			"\t", "flash_url:                ", this.settings.flash_url, "\n",
			"\t", "use_query_string:         ", this.settings.use_query_string.toString(), "\n",
			"\t", "file_post_name:           ", this.settings.file_post_name, "\n",
			"\t", "post_params:              ", this.settings.post_params.toString(), "\n",
			"\t", "file_types:               ", this.settings.file_types, "\n",
			"\t", "file_types_description:   ", this.settings.file_types_description, "\n",
			"\t", "file_size_limit:          ", this.settings.file_size_limit, "\n",
			"\t", "file_upload_limit:        ", this.settings.file_upload_limit, "\n",
			"\t", "file_queue_limit:         ", this.settings.file_queue_limit, "\n",
			"\t", "debug:                    ", this.settings.debug.toString(), "\n",

			"\t", "prevent_swf_caching:      ", this.settings.prevent_swf_caching.toString(), "\n",

			"\t", "button_placeholder_id:    ", this.settings.button_placeholder_id.toString(), "\n",
			"\t", "button_image_url:         ", this.settings.button_image_url.toString(), "\n",
			"\t", "button_width:             ", this.settings.button_width.toString(), "\n",
			"\t", "button_height:            ", this.settings.button_height.toString(), "\n",
			"\t", "button_text:              ", this.settings.button_text.toString(), "\n",
			"\t", "button_text_style:        ", this.settings.button_text_style.toString(), "\n",
			"\t", "button_text_top_padding:  ", this.settings.button_text_top_padding.toString(), "\n",
			"\t", "button_text_left_padding: ", this.settings.button_text_left_padding.toString(), "\n",
			"\t", "button_action:            ", this.settings.button_action.toString(), "\n",
			"\t", "button_disabled:          ", this.settings.button_disabled.toString(), "\n",

			"\t", "custom_settings:          ", this.settings.custom_settings.toString(), "\n",
			"Event Handlers:\n",
			"\t", "swfupload_loaded_handler assigned:  ", (typeof this.settings.swfupload_loaded_handler === "function").toString(), "\n",
			"\t", "file_dialog_start_handler assigned: ", (typeof this.settings.file_dialog_start_handler === "function").toString(), "\n",
			"\t", "file_queued_handler assigned:       ", (typeof this.settings.file_queued_handler === "function").toString(), "\n",
			"\t", "file_queue_error_handler assigned:  ", (typeof this.settings.file_queue_error_handler === "function").toString(), "\n",
			"\t", "upload_start_handler assigned:      ", (typeof this.settings.upload_start_handler === "function").toString(), "\n",
			"\t", "upload_progress_handler assigned:   ", (typeof this.settings.upload_progress_handler === "function").toString(), "\n",
			"\t", "upload_error_handler assigned:      ", (typeof this.settings.upload_error_handler === "function").toString(), "\n",
			"\t", "upload_success_handler assigned:    ", (typeof this.settings.upload_success_handler === "function").toString(), "\n",
			"\t", "upload_complete_handler assigned:   ", (typeof this.settings.upload_complete_handler === "function").toString(), "\n",
			"\t", "debug_handler assigned:             ", (typeof this.settings.debug_handler === "function").toString(), "\n"
		].join("")
	);
};

/* Note: addSetting and getSetting are no longer used by SWFUpload but are included
	the maintain v2 API compatibility
*/
// Public: (Deprecated) addSetting adds a setting value. If the value given is undefined or null then the default_value is used.
SWFUpload.prototype.addSetting = function (name, value, default_value) {
    if (value == undefined) {
        return (this.settings[name] = default_value);
    } else {
        return (this.settings[name] = value);
	}
};

// Public: (Deprecated) getSetting gets a setting. Returns an empty string if the setting was not found.
SWFUpload.prototype.getSetting = function (name) {
    if (this.settings[name] != undefined) {
        return this.settings[name];
	}

    return "";
};



// Private: callFlash handles function calls made to the Flash element.
// Calls are made with a setTimeout for some functions to work around
// bugs in the ExternalInterface library.
SWFUpload.prototype.callFlash = function (functionName, argumentArray) {
	argumentArray = argumentArray || [];
	var movieElement = this.getMovieElement();
	var returnValue;

	if (typeof movieElement[functionName] === "function") {
		// We have to go through all this if/else stuff because the Flash functions don't have apply() and only accept the exact number of arguments.
		if (argumentArray.length === 0) {
			returnValue = movieElement[functionName]();
		} else if (argumentArray.length === 1) {
			returnValue = movieElement[functionName](argumentArray[0]);
		} else if (argumentArray.length === 2) {
			returnValue = movieElement[functionName](argumentArray[0], argumentArray[1]);
		} else if (argumentArray.length === 3) {
			returnValue = movieElement[functionName](argumentArray[0], argumentArray[1], argumentArray[2]);
		} else {
			throw "Too many arguments";
		}
		
		// Unescape file post param values
		if (returnValue != undefined && typeof returnValue.post === "object") {
			returnValue = this.unescapeFilePostParams(returnValue);
		}
		
		return returnValue;
	} else {
		throw "Invalid function name: " + functionName;
	}
};


/* *****************************
	-- Flash control methods --
	Your UI should use these
	to operate SWFUpload
   ***************************** */

// Public: selectFile causes a File Selection Dialog window to appear.  This
// dialog only allows 1 file to be selected. WARNING: this function does not work in Flash Player 10
SWFUpload.prototype.selectFile = function () {
	this.callFlash("SelectFile");
};

// Public: selectFiles causes a File Selection Dialog window to appear/ This
// dialog allows the user to select any number of files
// Flash Bug Warning: Flash limits the number of selectable files based on the combined length of the file names.
// If the selection name length is too long the dialog will fail in an unpredictable manner.  There is no work-around
// for this bug.  WARNING: this function does not work in Flash Player 10
SWFUpload.prototype.selectFiles = function () {
	this.callFlash("SelectFiles");
};


// Public: startUpload starts uploading the first file in the queue unless
// the optional parameter 'fileID' specifies the ID 
SWFUpload.prototype.startUpload = function (fileID) {
	this.callFlash("StartUpload", [fileID]);
};

/* Cancels a the file upload.  You must specify a file_id */
// Public: cancelUpload cancels any queued file.  The fileID parameter
// must be specified.
SWFUpload.prototype.cancelUpload = function (fileID) {
	this.callFlash("CancelUpload", [fileID]);
};

// Public: stopUpload stops the current upload and requeues the file at the beginning of the queue.
// If nothing is currently uploading then nothing happens.
SWFUpload.prototype.stopUpload = function () {
	this.callFlash("StopUpload");
};

/* ************************
 * Settings methods
 *   These methods change the SWFUpload settings.
 *   SWFUpload settings should not be changed directly on the settings object
 *   since many of the settings need to be passed to Flash in order to take
 *   effect.
 * *********************** */

// Public: getStats gets the file statistics object.
SWFUpload.prototype.getStats = function () {
	return this.callFlash("GetStats");
};

// Public: setStats changes the SWFUpload statistics.  You shouldn't need to 
// change the statistics but you can.  Changing the statistics does not
// affect SWFUpload accept for the successful_uploads count which is used
// by the upload_limit setting to determine how many files the user may upload.
SWFUpload.prototype.setStats = function (statsObject) {
	this.callFlash("SetStats", [statsObject]);
};

// Public: getFile retrieves a File object by ID or Index.  If the file is
// not found then 'null' is returned.
SWFUpload.prototype.getFile = function (fileID) {
	if (typeof(fileID) === "number") {
		return this.callFlash("GetFileByIndex", [fileID]);
	} else {
		return this.callFlash("GetFile", [fileID]);
	}
};

// Public: addFileParam sets a name/value pair that will be posted with the
// file specified by the Files ID.  If the name already exists then the
// exiting value will be overwritten.
SWFUpload.prototype.addFileParam = function (fileID, name, value) {
	return this.callFlash("AddFileParam", [fileID, name, value]);
};

// Public: removeFileParam removes a previously set (by addFileParam) name/value
// pair from the specified file.
SWFUpload.prototype.removeFileParam = function (fileID, name) {
	this.callFlash("RemoveFileParam", [fileID, name]);
};

// Public: setUploadUrl changes the upload_url setting.
SWFUpload.prototype.setUploadURL = function (url) {
	this.settings.upload_url = url.toString();
	this.callFlash("SetUploadURL", [url]);
};

// Public: setPostParams changes the post_params setting
SWFUpload.prototype.setPostParams = function (paramsObject) {
	this.settings.post_params = paramsObject;
	this.callFlash("SetPostParams", [paramsObject]);
};

// Public: addPostParam adds post name/value pair.  Each name can have only one value.
SWFUpload.prototype.addPostParam = function (name, value) {
	this.settings.post_params[name] = value;
	this.callFlash("SetPostParams", [this.settings.post_params]);
};

// Public: removePostParam deletes post name/value pair.
SWFUpload.prototype.removePostParam = function (name) {
	delete this.settings.post_params[name];
	this.callFlash("SetPostParams", [this.settings.post_params]);
};

// Public: setFileTypes changes the file_types setting and the file_types_description setting
SWFUpload.prototype.setFileTypes = function (types, description) {
	this.settings.file_types = types;
	this.settings.file_types_description = description;
	this.callFlash("SetFileTypes", [types, description]);
};

// Public: setFileSizeLimit changes the file_size_limit setting
SWFUpload.prototype.setFileSizeLimit = function (fileSizeLimit) {
	this.settings.file_size_limit = fileSizeLimit;
	this.callFlash("SetFileSizeLimit", [fileSizeLimit]);
};

// Public: setFileUploadLimit changes the file_upload_limit setting
SWFUpload.prototype.setFileUploadLimit = function (fileUploadLimit) {
	this.settings.file_upload_limit = fileUploadLimit;
	this.callFlash("SetFileUploadLimit", [fileUploadLimit]);
};

// Public: setFileQueueLimit changes the file_queue_limit setting
SWFUpload.prototype.setFileQueueLimit = function (fileQueueLimit) {
	this.settings.file_queue_limit = fileQueueLimit;
	this.callFlash("SetFileQueueLimit", [fileQueueLimit]);
};

// Public: setFilePostName changes the file_post_name setting
SWFUpload.prototype.setFilePostName = function (filePostName) {
	this.settings.file_post_name = filePostName;
	this.callFlash("SetFilePostName", [filePostName]);
};

// Public: setUseQueryString changes the use_query_string setting
SWFUpload.prototype.setUseQueryString = function (useQueryString) {
	this.settings.use_query_string = useQueryString;
	this.callFlash("SetUseQueryString", [useQueryString]);
};

// Public: setRequeueOnError changes the requeue_on_error setting
SWFUpload.prototype.setRequeueOnError = function (requeueOnError) {
	this.settings.requeue_on_error = requeueOnError;
	this.callFlash("SetRequeueOnError", [requeueOnError]);
};

// Public: setDebugEnabled changes the debug_enabled setting
SWFUpload.prototype.setDebugEnabled = function (debugEnabled) {
	this.settings.debug_enabled = debugEnabled;
	this.callFlash("SetDebugEnabled", [debugEnabled]);
};

// Public: setButtonImageURL loads a button image sprite
SWFUpload.prototype.setButtonImageURL = function (buttonImageURL) {
	if (buttonImageURL == undefined) {
		buttonImageURL = "";
	}
	
	this.settings.button_image_url = buttonImageURL;
	this.callFlash("SetButtonImageURL", [buttonImageURL]);
};

// Public: setButtonDimensions resizes the Flash Movie and button
SWFUpload.prototype.setButtonDimensions = function (width, height) {
	this.settings.button_width = width;
	this.settings.button_height = height;
	
	var movie = this.getMovieElement();
	if (movie != undefined) {
		movie.style.width = width + "px";
		movie.style.height = height + "px";
	}
	
	this.callFlash("SetButtonDimensions", [width, height]);
};
// Public: setButtonText Changes the text overlaid on the button
SWFUpload.prototype.setButtonText = function (html) {
	this.settings.button_text = html;
	this.callFlash("SetButtonText", [html]);
};
// Public: setButtonTextPadding changes the top and left padding of the text overlay
SWFUpload.prototype.setButtonTextPadding = function (left, top) {
	this.settings.button_text_top_padding = top;
	this.settings.button_text_left_padding = left;
	this.callFlash("SetButtonTextPadding", [left, top]);
};

// Public: setButtonTextStyle changes the CSS used to style the HTML/Text overlaid on the button
SWFUpload.prototype.setButtonTextStyle = function (css) {
	this.settings.button_text_style = css;
	this.callFlash("SetButtonTextStyle", [css]);
};
// Public: setButtonDisabled disables/enables the button
SWFUpload.prototype.setButtonDisabled = function (isDisabled) {
	this.settings.button_disabled = isDisabled;
	this.callFlash("SetButtonDisabled", [isDisabled]);
};
// Public: setButtonAction sets the action that occurs when the button is clicked
SWFUpload.prototype.setButtonAction = function (buttonAction) {
	this.settings.button_action = buttonAction;
	this.callFlash("SetButtonAction", [buttonAction]);
};

/* *******************************
	Flash Event Interfaces
	These functions are used by Flash to trigger the various
	events.
	
	All these functions a Private.
	
	Because the ExternalInterface library is buggy the event calls
	are added to a queue and the queue then executed by a setTimeout.
	This ensures that events are executed in a determinate order and that
	the ExternalInterface bugs are avoided.
******************************* */

SWFUpload.prototype.queueEvent = function (handlerName, argumentArray) {
	// Warning: Don't call this.debug inside here or you'll create an infinite loop
	
	if (argumentArray == undefined) {
		argumentArray = [];
	} else if (!(argumentArray instanceof Array)) {
		argumentArray = [argumentArray];
	}
	
	var self = this;
	if (typeof this.settings[handlerName] === "function") {
		// Queue the event
		this.eventQueue.push(function () {
			this.settings[handlerName].apply(this, argumentArray);
		});
		
		// Execute the next queued event
		setTimeout(function () {
			self.executeNextEvent();
		}, 0);
		
	} else if (this.settings[handlerName] !== null) {
		throw "Event handler " + handlerName + " is unknown or is not a function";
	}
};

// Private: Causes the next event in the queue to be executed.  Since events are queued using a setTimeout
// we must queue them in order to garentee that they are executed in order.
SWFUpload.prototype.executeNextEvent = function () {
	// Warning: Don't call this.debug inside here or you'll create an infinite loop

	var  f = this.eventQueue ? this.eventQueue.shift() : null;
	if (typeof(f) === "function") {
		f.apply(this);
	}
};

// Private: unescapeFileParams is part of a workaround for a flash bug where objects passed through ExternalInterface cannot have
// properties that contain characters that are not valid for JavaScript identifiers. To work around this
// the Flash Component escapes the parameter names and we must unescape again before passing them along.
SWFUpload.prototype.unescapeFilePostParams = function (file) {
	var reg = /[$]([0-9a-f]{4})/i;
	var unescapedPost = {};
	var uk;

	if (file != undefined) {
		for (var k in file.post) {
			if (file.post.hasOwnProperty(k)) {
				uk = k;
				var match;
				while ((match = reg.exec(uk)) !== null) {
					uk = uk.replace(match[0], String.fromCharCode(parseInt("0x" + match[1], 16)));
				}
				unescapedPost[uk] = file.post[k];
			}
		}

		file.post = unescapedPost;
	}

	return file;
};

SWFUpload.prototype.flashReady = function () {
	// Check that the movie element is loaded correctly with its ExternalInterface methods defined
	var movieElement = this.getMovieElement();
	if (typeof movieElement.StartUpload !== "function") {
		throw "ExternalInterface methods failed to initialize.";
	}

	// Fix IE Flash/Form bug
	if (window[this.movieName] == undefined) {
		window[this.movieName] = movieElement;
	}
	
	this.queueEvent("swfupload_loaded_handler");
};


/* This is a chance to do something before the browse window opens */
SWFUpload.prototype.fileDialogStart = function () {
	this.queueEvent("file_dialog_start_handler");
};


/* Called when a file is successfully added to the queue. */
SWFUpload.prototype.fileQueued = function (file) {
	file = this.unescapeFilePostParams(file);
	this.queueEvent("file_queued_handler", file);
};


/* Handle errors that occur when an attempt to queue a file fails. */
SWFUpload.prototype.fileQueueError = function (file, errorCode, message) {
	file = this.unescapeFilePostParams(file);
	this.queueEvent("file_queue_error_handler", [file, errorCode, message]);
};

/* Called after the file dialog has closed and the selected files have been queued.
	You could call startUpload here if you want the queued files to begin uploading immediately. */
SWFUpload.prototype.fileDialogComplete = function (numFilesSelected, numFilesQueued) {
	this.queueEvent("file_dialog_complete_handler", [numFilesSelected, numFilesQueued]);
};

SWFUpload.prototype.uploadStart = function (file) {
	file = this.unescapeFilePostParams(file);
	this.queueEvent("return_upload_start_handler", file);
};

SWFUpload.prototype.returnUploadStart = function (file) {
	var returnValue;
	if (typeof this.settings.upload_start_handler === "function") {
		file = this.unescapeFilePostParams(file);
		returnValue = this.settings.upload_start_handler.call(this, file);
	} else if (this.settings.upload_start_handler != undefined) {
		throw "upload_start_handler must be a function";
	}

	// Convert undefined to true so if nothing is returned from the upload_start_handler it is
	// interpretted as 'true'.
	if (returnValue === undefined) {
		returnValue = true;
	}
	
	returnValue = !!returnValue;
	
	this.callFlash("ReturnUploadStart", [returnValue]);
};



SWFUpload.prototype.uploadProgress = function (file, bytesComplete, bytesTotal) {
	file = this.unescapeFilePostParams(file);
	this.queueEvent("upload_progress_handler", [file, bytesComplete, bytesTotal]);
};

SWFUpload.prototype.uploadError = function (file, errorCode, message) {
	file = this.unescapeFilePostParams(file);
	this.queueEvent("upload_error_handler", [file, errorCode, message]);
};

SWFUpload.prototype.uploadSuccess = function (file, serverData) {
	file = this.unescapeFilePostParams(file);
	this.queueEvent("upload_success_handler", [file, serverData]);
};

SWFUpload.prototype.uploadComplete = function (file) {
	file = this.unescapeFilePostParams(file);
	this.queueEvent("upload_complete_handler", file);
};

/* Called by SWFUpload JavaScript and Flash functions when debug is enabled. By default it writes messages to the
   internal debug console.  You can override this event and have messages written where you want. */
SWFUpload.prototype.debug = function (message) {
	this.queueEvent("debug_handler", message);
};


/* **********************************
	Debug Console
	The debug console is a self contained, in page location
	for debug message to be sent.  The Debug Console adds
	itself to the body if necessary.

	The console is automatically scrolled as messages appear.
	
	If you are using your own debug handler or when you deploy to production and
	have debug disabled you can remove these functions to reduce the file size
	and complexity.
********************************** */
   
// Private: debugMessage is the default debug_handler.  If you want to print debug messages
// call the debug() function.  When overriding the function your own function should
// check to see if the debug setting is true before outputting debug information.
SWFUpload.prototype.debugMessage = function (message) {
	if (this.settings.debug) {
		var exceptionMessage, exceptionValues = [];

		// Check for an exception object and print it nicely
		if (typeof message === "object" && typeof message.name === "string" && typeof message.message === "string") {
			for (var key in message) {
				if (message.hasOwnProperty(key)) {
					exceptionValues.push(key + ": " + message[key]);
				}
			}
			exceptionMessage = exceptionValues.join("\n") || "";
			exceptionValues = exceptionMessage.split("\n");
			exceptionMessage = "EXCEPTION: " + exceptionValues.join("\nEXCEPTION: ");
			SWFUpload.Console.writeLine(exceptionMessage);
		} else {
			SWFUpload.Console.writeLine(message);
		}
	}
};

SWFUpload.Console = {};
SWFUpload.Console.writeLine = function (message) {
	var console, documentForm;

	try {
		console = document.getElementById("SWFUpload_Console");

		if (!console) {
			documentForm = document.createElement("form");
			document.getElementsByTagName("body")[0].appendChild(documentForm);

			console = document.createElement("textarea");
			console.id = "SWFUpload_Console";
			console.style.fontFamily = "monospace";
			console.setAttribute("wrap", "off");
			console.wrap = "off";
			console.style.overflow = "auto";
			console.style.width = "700px";
			console.style.height = "350px";
			console.style.margin = "5px";
			documentForm.appendChild(console);
		}

		console.value += message + "\n";

		console.scrollTop = console.scrollHeight - console.clientHeight;
	} catch (ex) {
		alert("Exception: " + ex.name + " Message: " + ex.message);
	}
};
if(typeof YAHOO=="undefined"){throw"Unable to load Shadowbox, core YUI utilities (yahoo, dom, event) not found"}var Shadowbox={};Shadowbox.lib=function(){var A=YAHOO.util.Event;var B=YAHOO.util.Dom;return{adapter:"yui",getStyle:function(D,C){return B.getStyle(D,C)},setStyle:function(F,E,G){if(typeof E!="object"){var C={};C[E]=G;E=C}for(var D in E){B.setStyle(F,D,E[D])}},get:function(C){return B.get(C)},remove:function(C){C.parentNode.removeChild(C)},getTarget:function(C){return A.getTarget(C)},getPageXY:function(C){return[A.getPageX(C),A.getPageY(C)]},preventDefault:function(C){A.preventDefault(C)},keyCode:function(C){return C.keyCode},addEvent:function(E,C,D){A.addListener(E,C,D)},removeEvent:function(E,C,D){A.removeListener(E,C,D)},append:function(E,D){if(E.insertAdjacentHTML){E.insertAdjacentHTML("BeforeEnd",D)}else{if(E.lastChild){var C=E.ownerDocument.createRange();C.setStartAfter(E.lastChild);var F=C.createContextualFragment(D);E.appendChild(F)}else{E.innerHTML=D}}}}}();
if(typeof Shadowbox=="undefined"){throw"Unable to load Shadowbox, no base library adapter found"}(function(){var version="2.0";var options={animate:true,animateFade:true,animSequence:"wh",flvPlayer:"flvplayer.swf",modal:false,overlayColor:"#000",overlayOpacity:0.8,flashBgColor:"#000000",autoplayMovies:true,showMovieControls:true,slideshowDelay:0,resizeDuration:0.55,fadeDuration:0.35,displayNav:true,continuous:false,displayCounter:true,counterType:"default",counterLimit:10,viewportPadding:20,handleOversize:"resize",handleException:null,handleUnsupported:"link",initialHeight:160,initialWidth:320,enableKeys:true,onOpen:null,onFinish:null,onChange:null,onClose:null,skipSetup:false,errors:{fla:{name:"Flash",url:"http://www.adobe.com/products/flashplayer/"},qt:{name:"QuickTime",url:"http://www.apple.com/quicktime/download/"},wmp:{name:"Windows Media Player",url:"http://www.microsoft.com/windows/windowsmedia/"},f4m:{name:"Flip4Mac",url:"http://www.flip4mac.com/wmv_download.htm"}},ext:{img:["png","jpg","jpeg","gif","bmp"],swf:["swf"],flv:["flv"],qt:["dv","mov","moov","movie","mp4","m4p"],wmp:["asf","wm","wmv"],qtwmp:["avi","mpg","mpeg","m4a"],iframe:["asp","aspx","cgi","cfm","htm","html","pl","php","php3","php4","php5","phtml","rb","rhtml","shtml","txt","vbs"]}};var SB=Shadowbox;var SL=SB.lib;var default_options;var RE={domain:/:\/\/(.*?)[:\/]/,inline:/#(.+)$/,rel:/^(light|shadow)box/i,gallery:/^(light|shadow)box\[(.*?)\]/i,unsupported:/^unsupported-(\w+)/,param:/\s*([a-z_]*?)\s*=\s*(.+)\s*/,empty:/^(?:br|frame|hr|img|input|link|meta|range|spacer|wbr|area|param|col)$/i};var cache=[];var gallery;var current;var content;var content_id="shadowbox_content";var dims;var initialized=false;var activated=false;var slide_timer;var slide_start;var slide_delay=0;var ua=navigator.userAgent.toLowerCase();var client={isStrict:document.compatMode=="CSS1Compat",isOpera:ua.indexOf("opera")>-1,isIE:ua.indexOf("msie")>-1,isIE7:ua.indexOf("msie 7")>-1,isSafari:/webkit|khtml/.test(ua),isWindows:ua.indexOf("windows")!=-1||ua.indexOf("win32")!=-1,isMac:ua.indexOf("macintosh")!=-1||ua.indexOf("mac os x")!=-1,isLinux:ua.indexOf("linux")!=-1};client.isBorderBox=client.isIE&&!client.isStrict;client.isSafari3=client.isSafari&&!!(document.evaluate);client.isGecko=ua.indexOf("gecko")!=-1&&!client.isSafari;var ltIE7=client.isIE&&!client.isIE7;var plugins;if(navigator.plugins&&navigator.plugins.length){var detectPlugin=function(plugin_name){var detected=false;for(var i=0,len=navigator.plugins.length;i<len;++i){if(navigator.plugins[i].name.indexOf(plugin_name)>-1){detected=true;break}}return detected};var f4m=detectPlugin("Flip4Mac");plugins={fla:detectPlugin("Shockwave Flash"),qt:detectPlugin("QuickTime"),wmp:!f4m&&detectPlugin("Windows Media"),f4m:f4m}}else{var detectPlugin=function(plugin_name){var detected=false;try{var axo=new ActiveXObject(plugin_name);if(axo){detected=true}}catch(e){}return detected};plugins={fla:detectPlugin("ShockwaveFlash.ShockwaveFlash"),qt:detectPlugin("QuickTime.QuickTime"),wmp:detectPlugin("wmplayer.ocx"),f4m:false}}var apply=function(o,e){for(var p in e){o[p]=e[p]}return o};var isLink=function(el){return el&&typeof el.tagName=="string"&&(el.tagName.toUpperCase()=="A"||el.tagName.toUpperCase()=="AREA")};SL.getViewportHeight=function(){var h=window.innerHeight;var mode=document.compatMode;if((mode||client.isIE)&&!client.isOpera){h=client.isStrict?document.documentElement.clientHeight:document.body.clientHeight}return h};SL.getViewportWidth=function(){var w=window.innerWidth;var mode=document.compatMode;if(mode||client.isIE){w=client.isStrict?document.documentElement.clientWidth:document.body.clientWidth}return w};SL.createHTML=function(obj){var html="<"+obj.tag;for(var attr in obj){if(attr=="tag"||attr=="html"||attr=="children"){continue}if(attr=="cls"){html+=' class="'+obj.cls+'"'}else{html+=" "+attr+'="'+obj[attr]+'"'}}if(RE.empty.test(obj.tag)){html+="/>"}else{html+=">";var cn=obj.children;if(cn){for(var i=0,len=cn.length;i<len;++i){html+=this.createHTML(cn[i])}}if(obj.html){html+=obj.html}html+="</"+obj.tag+">"}return html};var ease=function(x){return 1+Math.pow(x-1,3)};var animate=function(el,p,to,d,cb){var from=parseFloat(SL.getStyle(el,p));if(isNaN(from)){from=0}if(from==to){if(typeof cb=="function"){cb()}return }var delta=to-from;var op=p=="opacity";var unit=op?"":"px";var fn=function(ease){SL.setStyle(el,p,from+ease*delta+unit)};if(!options.animate&&!op||op&&!options.animateFade){fn(1);if(typeof cb=="function"){cb()}return }d*=1000;var begin=new Date().getTime();var end=begin+d;var timer=setInterval(function(){var time=new Date().getTime();if(time>=end){clearInterval(timer);fn(1);if(typeof cb=="function"){cb()}}else{fn(ease((time-begin)/d))}},10)};var clearOpacity=function(el){var s=el.style;if(client.isIE){if(typeof s.filter=="string"&&(/alpha/i).test(s.filter)){s.filter=s.filter.replace(/[\w\.]*alpha\(.*?\);?/i,"")}}else{s.opacity="";s["-moz-opacity"]="";s["-khtml-opacity"]=""}};var getComputedHeight=function(el){var h=Math.max(el.offsetHeight,el.clientHeight);if(!h){h=parseInt(SL.getStyle(el,"height"),10)||0;if(!client.isBorderBox){h+=parseInt(SL.getStyle(el,"padding-top"),10)+parseInt(SL.getStyle(el,"padding-bottom"),10)+parseInt(SL.getStyle(el,"border-top-width"),10)+parseInt(SL.getStyle(el,"border-bottom-width"),10)}}return h};var getPlayer=function(url){var m=url.match(RE.domain);var d=m&&document.domain==m[1];if(url.indexOf("#")>-1&&d){return"inline"}var q=url.indexOf("?");if(q>-1){url=url.substring(0,q)}if(RE.img.test(url)){return"img"}if(RE.swf.test(url)){return plugins.fla?"swf":"unsupported-swf"}if(RE.flv.test(url)){return plugins.fla?"flv":"unsupported-flv"}if(RE.qt.test(url)){return plugins.qt?"qt":"unsupported-qt"}if(RE.wmp.test(url)){if(plugins.wmp){return"wmp"}if(plugins.f4m){return"qt"}if(client.isMac){return plugins.qt?"unsupported-f4m":"unsupported-qtf4m"}return"unsupported-wmp"}else{if(RE.qtwmp.test(url)){if(plugins.qt){return"qt"}if(plugins.wmp){return"wmp"}return client.isMac?"unsupported-qt":"unsupported-qtwmp"}else{if(!d||RE.iframe.test(url)){return"iframe"}}}return"unsupported"};var handleClick=function(ev){var link;if(isLink(this)){link=this}else{link=SL.getTarget(ev);while(!isLink(link)&&link.parentNode){link=link.parentNode}}if(link){SB.open(link);if(gallery.length){SL.preventDefault(ev)}}};var toggleNav=function(id,on){var el=SL.get("shadowbox_nav_"+id);if(el){el.style.display=on?"":"none"}};var buildBars=function(cb){var obj=gallery[current];var title_i=SL.get("shadowbox_title_inner");title_i.innerHTML=obj.title||"";var nav=SL.get("shadowbox_nav");if(nav){var c,n,pl,pa,p;if(options.displayNav){c=true;var len=gallery.length;if(len>1){if(options.continuous){n=p=true}else{n=(len-1)>current;p=current>0}}if(options.slideshowDelay>0&&hasNext()){pa=slide_timer!="paused";pl=!pa}}else{c=n=pl=pa=p=false}toggleNav("close",c);toggleNav("next",n);toggleNav("play",pl);toggleNav("pause",pa);toggleNav("previous",p)}var counter=SL.get("shadowbox_counter");if(counter){var co="";if(options.displayCounter&&gallery.length>1){if(options.counterType=="skip"){var i=0,len=gallery.length,end=len;var limit=parseInt(options.counterLimit);if(limit<len){var h=Math.round(limit/2);i=current-h;if(i<0){i+=len}end=current+(limit-h);if(end>len){end-=len}}while(i!=end){if(i==len){i=0}co+='<a onclick="Shadowbox.change('+i+');"';if(i==current){co+=' class="shadowbox_counter_current"'}co+=">"+(++i)+"</a>"}}else{co=(current+1)+" "+SB.LANG.of+" "+len}}counter.innerHTML=co}cb()};var hideBars=function(anim,cb){var obj=gallery[current];var title=SL.get("shadowbox_title");var info=SL.get("shadowbox_info");var title_i=SL.get("shadowbox_title_inner");var info_i=SL.get("shadowbox_info_inner");var fn=function(){buildBars(cb)};var title_h=getComputedHeight(title);var info_h=getComputedHeight(info)*-1;if(anim){animate(title_i,"margin-top",title_h,0.35);animate(info_i,"margin-top",info_h,0.35,fn)}else{SL.setStyle(title_i,"margin-top",title_h+"px");SL.setStyle(info_i,"margin-top",info_h+"px");fn()}};var showBars=function(cb){var title_i=SL.get("shadowbox_title_inner");var info_i=SL.get("shadowbox_info_inner");var t=title_i.innerHTML!="";if(t){animate(title_i,"margin-top",0,0.35)}animate(info_i,"margin-top",0,0.35,cb)};var loadContent=function(){var obj=gallery[current];if(!obj){return }var changing=false;if(content){content.remove();changing=true}var p=obj.player=="inline"?"html":obj.player;if(typeof SB[p]!="function"){SB.raise("Unknown player "+obj.player)}content=new SB[p](content_id,obj);listenKeys(false);toggleLoading(true);hideBars(changing,function(){if(!content){return }if(!changing){SL.get("shadowbox").style.display=""}var fn=function(){resizeContent(function(){if(!content){return }showBars(function(){if(!content){return }SL.get("shadowbox_body_inner").innerHTML=SL.createHTML(content.markup(dims));toggleLoading(false,function(){if(!content){return }if(typeof content.onLoad=="function"){content.onLoad()}if(options.onFinish&&typeof options.onFinish=="function"){options.onFinish(gallery[current])}if(slide_timer!="paused"){SB.play()}listenKeys(true)})})})};if(typeof content.ready!="undefined"){var id=setInterval(function(){if(content){if(content.ready){clearInterval(id);id=null;fn()}}else{clearInterval(id);id=null}},100)}else{fn()}});if(gallery.length>1){var next=gallery[current+1]||gallery[0];if(next.player=="img"){var a=new Image();a.src=next.content}var prev=gallery[current-1]||gallery[gallery.length-1];if(prev.player=="img"){var b=new Image();b.src=prev.content}}};var setDimensions=function(height,width,resizable){resizable=resizable||false;var sb=SL.get("shadowbox_body");var h=height=parseInt(height);var w=width=parseInt(width);var view_h=SL.getViewportHeight();var view_w=SL.getViewportWidth();var border_w=parseInt(SL.getStyle(sb,"border-left-width"),10)+parseInt(SL.getStyle(sb,"border-right-width"),10);var extra_w=border_w+2*options.viewportPadding;if(w+extra_w>=view_w){w=view_w-extra_w}var border_h=parseInt(SL.getStyle(sb,"border-top-width"),10)+parseInt(SL.getStyle(sb,"border-bottom-width"),10);var bar_h=getComputedHeight(SL.get("shadowbox_title"))+getComputedHeight(SL.get("shadowbox_info"));var extra_h=border_h+2*options.viewportPadding+bar_h;if(h+extra_h>=view_h){h=view_h-extra_h}var drag=false;var resize_h=height;var resize_w=width;var handle=options.handleOversize;if(resizable&&(handle=="resize"||handle=="drag")){var change_h=(height-h)/height;var change_w=(width-w)/width;if(handle=="resize"){if(change_h>change_w){w=Math.round((width/height)*h)}else{if(change_w>change_h){h=Math.round((height/width)*w)}}resize_w=w;resize_h=h}else{var link=gallery[current];if(link){drag=link.player=="img"&&(change_h>0||change_w>0)}}}dims={height:h+border_h+bar_h,width:w+border_w,inner_h:h,inner_w:w,top:(view_h-(h+extra_h))/2+options.viewportPadding,resize_h:resize_h,resize_w:resize_w,drag:drag}};var resizeContent=function(cb){if(!content){return }setDimensions(content.height,content.width,content.resizable);if(cb){switch(options.animSequence){case"hw":adjustHeight(dims.inner_h,dims.top,true,function(){adjustWidth(dims.width,true,cb)});break;case"wh":adjustWidth(dims.width,true,function(){adjustHeight(dims.inner_h,dims.top,true,cb)});break;case"sync":default:adjustWidth(dims.width,true);adjustHeight(dims.inner_h,dims.top,true,cb)}}else{adjustWidth(dims.width,false);adjustHeight(dims.inner_h,dims.top,false);var c=SL.get(content_id);if(c){if(content.resizable&&options.handleOversize=="resize"){c.height=dims.resize_h;c.width=dims.resize_w}if(gallery[current].player=="img"&&options.handleOversize=="drag"){var top=parseInt(SL.getStyle(c,"top"));if(top+content.height<dims.inner_h){SL.setStyle(c,"top",dims.inner_h-content.height+"px")}var left=parseInt(SL.getStyle(c,"left"));if(left+content.width<dims.inner_w){SL.setStyle(c,"left",dims.inner_w-content.width+"px")}}}}};var adjustHeight=function(height,top,anim,cb){height=parseInt(height);var sb=SL.get("shadowbox_body");if(anim){animate(sb,"height",height,options.resizeDuration)}else{SL.setStyle(sb,"height",height+"px")}var s=SL.get("shadowbox");if(anim){animate(s,"top",top,options.resizeDuration,cb)}else{SL.setStyle(s,"top",top+"px");if(typeof cb=="function"){cb()}}};var adjustWidth=function(width,anim,cb){width=parseInt(width);var s=SL.get("shadowbox");if(anim){animate(s,"width",width,options.resizeDuration,cb)}else{SL.setStyle(s,"width",width+"px");if(typeof cb=="function"){cb()}}};var listenKeys=function(on){if(!options.enableKeys){return }SL[(on?"add":"remove")+"Event"](document,"keydown",handleKey)};var handleKey=function(e){var code=SL.keyCode(e);SL.preventDefault(e);if(code==81||code==88||code==27){SB.close()}else{if(code==37){SB.previous()}else{if(code==39){SB.next()}else{if(code==32){SB[(typeof slide_timer=="number"?"pause":"play")]()}}}}};var toggleLoading=function(on,cb){var loading=SL.get("shadowbox_loading");if(on){loading.style.display="";if(typeof cb=="function"){cb()}}else{var p=gallery[current].player;var anim=(p=="img"||p=="html");var fn=function(){loading.style.display="none";clearOpacity(loading);if(typeof cb=="function"){cb()}};if(anim){animate(loading,"opacity",0,options.fadeDuration,fn)}else{fn()}}};var fixTop=function(){SL.get("shadowbox_container").style.top=document.documentElement.scrollTop+"px"};var fixHeight=function(){SL.get("shadowbox_overlay").style.height=SL.getViewportHeight()+"px"};var hasNext=function(){return gallery.length>1&&(current!=gallery.length-1||options.continuous)};var toggleVisible=function(cb){var els,v=(cb)?"hidden":"visible";var hide=["select","object","embed"];for(var i=0;i<hide.length;++i){els=document.getElementsByTagName(hide[i]);for(var j=0,len=els.length;j<len;++j){els[j].style.visibility=v}}var so=SL.get("shadowbox_overlay");var sc=SL.get("shadowbox_container");var sb=SL.get("shadowbox");if(cb){SL.setStyle(so,{backgroundColor:options.overlayColor,opacity:0});if(!options.modal){SL.addEvent(so,"click",SB.close)}if(ltIE7){fixTop();fixHeight();SL.addEvent(window,"scroll",fixTop)}sb.style.display="none";sc.style.visibility="visible";animate(so,"opacity",parseFloat(options.overlayOpacity),options.fadeDuration,cb)}else{SL.removeEvent(so,"click",SB.close);if(ltIE7){SL.removeEvent(window,"scroll",fixTop)}sb.style.display="none";animate(so,"opacity",0,options.fadeDuration,function(){sc.style.visibility="hidden";sb.style.display="";clearOpacity(so)})}};Shadowbox.init=function(opts){if(initialized){return }if(typeof SB.LANG=="undefined"){SB.raise("No Shadowbox language loaded");return }if(typeof SB.SKIN=="undefined"){SB.raise("No Shadowbox skin loaded");return }apply(options,opts||{});var markup=SB.SKIN.markup.replace(/\{(\w+)\}/g,function(m,p){return SB.LANG[p]});var bd=document.body||document.documentElement;SL.append(bd,markup);if(ltIE7){SL.setStyle(SL.get("shadowbox_container"),"position","absolute");SL.get("shadowbox_body").style.zoom=1;var png=SB.SKIN.png_fix;if(png&&png.constructor==Array){for(var i=0;i<png.length;++i){var el=SL.get(png[i]);if(el){var match=SL.getStyle(el,"background-image").match(/url\("(.*\.png)"\)/);if(match){SL.setStyle(el,{backgroundImage:"none",filter:"progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled=true,src="+match[1]+",sizingMethod=scale);"})}}}}}for(var e in options.ext){RE[e]=new RegExp(".("+options.ext[e].join("|")+")s*$","i")}var id;SL.addEvent(window,"resize",function(){if(id){clearTimeout(id);id=null}id=setTimeout(function(){if(ltIE7){fixHeight()}resizeContent()},50)});if(!options.skipSetup){SB.setup()}initialized=true};Shadowbox.loadSkin=function(skin,dir){if(!(/\/$/.test(dir))){dir+="/"}skin=dir+skin+"/";document.write('<link rel="stylesheet" type="text/css" href="'+skin+'skin.css">');document.write('<script type="text/javascript" src="'+skin+'skin.js"><\/script>')};Shadowbox.loadLanguage=function(lang,dir){if(!(/\/$/.test(dir))){dir+="/"}document.write('<script type="text/javascript" src="'+dir+"shadowbox-"+lang+'.js"><\/script>')};Shadowbox.loadPlayer=function(players,dir){if(typeof players=="string"){players=[players]}if(!(/\/$/.test(dir))){dir+="/"}for(var i=0,len=players.length;i<len;++i){document.write('<script type="text/javascript" src="'+dir+"shadowbox-"+players[i]+'.js"><\/script>')}};Shadowbox.setup=function(links,opts){if(!links){var links=[];var a=document.getElementsByTagName("a"),rel;for(var i=0,len=a.length;i<len;++i){rel=a[i].getAttribute("rel");if(rel&&RE.rel.test(rel)){links[links.length]=a[i]}}}else{if(!links.length){links=[links]}}var link;for(var i=0,len=links.length;i<len;++i){link=links[i];if(typeof link.shadowboxCacheKey=="undefined"){link.shadowboxCacheKey=cache.length;SL.addEvent(link,"click",handleClick)}cache[link.shadowboxCacheKey]=this.buildCacheObj(link,opts)}};Shadowbox.buildCacheObj=function(link,opts){var href=link.href;var o={el:link,title:link.getAttribute("title"),player:getPlayer(href),options:apply({},opts||{}),content:href};var opt,l_opts=["player","title","height","width","gallery"];for(var i=0,len=l_opts.length;i<len;++i){opt=l_opts[i];if(typeof o.options[opt]!="undefined"){o[opt]=o.options[opt];delete o.options[opt]}}var rel=link.getAttribute("rel");if(rel){var match=rel.match(RE.gallery);if(match){o.gallery=escape(match[2])}var params=rel.split(";");for(var i=0,len=params.length;i<len;++i){match=params[i].match(RE.param);if(match){if(match[1]=="options"){eval("apply(o.options, "+match[2]+")")}else{o[match[1]]=match[2]}}}}return o};Shadowbox.applyOptions=function(opts){if(opts){default_options=apply({},options);options=apply(options,opts)}};Shadowbox.revertOptions=function(){if(default_options){options=default_options;default_options=null}};Shadowbox.open=function(obj,opts){this.revertOptions();if(isLink(obj)){if(typeof obj.shadowboxCacheKey=="undefined"||typeof cache[obj.shadowboxCacheKey]=="undefined"){obj=this.buildCacheObj(obj,opts)}else{obj=cache[obj.shadowboxCacheKey]}}if(obj.constructor==Array){gallery=obj;current=0}else{var copy=apply({},obj);if(!obj.gallery){gallery=[copy];current=0}else{current=null;gallery=[];var ci;for(var i=0,len=cache.length;i<len;++i){ci=cache[i];if(ci.gallery){if(ci.content==obj.content&&ci.gallery==obj.gallery&&ci.title==obj.title){current=gallery.length}if(ci.gallery==obj.gallery){gallery.push(apply({},ci))}}}if(current==null){gallery.unshift(copy);current=0}}}obj=gallery[current];if(obj.options||opts){this.applyOptions(apply(apply({},obj.options||{}),opts||{}))}var match,r;for(var i=0,len=gallery.length;i<len;++i){r=false;if(gallery[i].player=="unsupported"){r=true}else{if(match=RE.unsupported.exec(gallery[i].player)){if(options.handleUnsupported=="link"){gallery[i].player="html";var s,a,oe=options.errors;switch(match[1]){case"qtwmp":s="either";a=[oe.qt.url,oe.qt.name,oe.wmp.url,oe.wmp.name];break;case"qtf4m":s="shared";a=[oe.qt.url,oe.qt.name,oe.f4m.url,oe.f4m.name];break;default:s="single";if(match[1]=="swf"||match[1]=="flv"){match[1]="fla"}a=[oe[match[1]].url,oe[match[1]].name]}var msg=SB.LANG.errors[s].replace(/\{(\d+)\}/g,function(m,i){return a[i]});gallery[i].content='<div class="shadowbox_message">'+msg+"</div>"}else{r=true}}else{if(gallery[i].player=="inline"){var match=RE.inline.exec(gallery[i].content);if(match){var el;if(el=SL.get(match[1])){gallery[i].content=el.innerHTML}else{SB.raise("Cannot find element with id "+match[1])}}else{SB.raise("Cannot find element id for inline content")}}}}if(r){gallery.splice(i,1);if(i<current){--current}else{if(i==current){current=i>0?current-1:i}}--i;len=gallery.length}}if(gallery.length){if(options.onOpen&&typeof options.onOpen=="function"){options.onOpen(obj)}if(!activated){setDimensions(options.initialHeight,options.initialWidth);adjustHeight(dims.inner_h,dims.top,false);adjustWidth(dims.width,false);toggleVisible(loadContent)}else{loadContent()}activated=true}};Shadowbox.change=function(num){if(!gallery){return }if(!gallery[num]){if(!options.continuous){return }else{num=num<0?(gallery.length-1):0}}if(typeof slide_timer=="number"){clearTimeout(slide_timer);slide_timer=null;slide_delay=slide_start=0}current=num;if(options.onChange&&typeof options.onChange=="function"){options.onChange(gallery[current])}loadContent()};Shadowbox.next=function(){this.change(current+1)};Shadowbox.previous=function(){this.change(current-1)};Shadowbox.play=function(){if(!hasNext()){return }if(!slide_delay){slide_delay=options.slideshowDelay*1000}if(slide_delay){slide_start=new Date().getTime();slide_timer=setTimeout(function(){slide_delay=slide_start=0;SB.next()},slide_delay);toggleNav("play",false);toggleNav("pause",true)}};Shadowbox.pause=function(){if(typeof slide_timer=="number"){var time=new Date().getTime();slide_delay=Math.max(0,slide_delay-(time-slide_start));if(slide_delay){clearTimeout(slide_timer);slide_timer="paused"}toggleNav("pause",false);toggleNav("play",true)}};Shadowbox.close=function(){if(!activated){return }listenKeys(false);toggleVisible(false);if(content){content.remove();content=null}if(typeof slide_timer=="number"){clearTimeout(slide_timer)}slide_timer=null;slide_delay=0;if(options.onClose&&typeof options.onClose=="function"){options.onClose(gallery[current])}activated=false};Shadowbox.clearCache=function(){for(var i=0,len=cache.length;i<len;++i){if(cache[i].el){SL.removeEvent(cache[i].el,"click",handleClick);delete cache[i].el.shadowboxCacheKey}}cache=[]};Shadowbox.getPlugins=function(){return plugins};Shadowbox.getOptions=function(){return options};Shadowbox.getCurrent=function(){return gallery[current]};Shadowbox.getVersion=function(){return version};Shadowbox.getClient=function(){return client};Shadowbox.getContent=function(){return content};Shadowbox.getDimensions=function(){return dims};Shadowbox.raise=function(e){if(typeof options.handleException=="function"){options.handleException(e)}else{throw e}}})();
if(typeof Shadowbox=="undefined"){throw"Unable to load Shadowbox language file, base library not found."}Shadowbox.LANG={code:"en",of:"of",loading:"loading",cancel:"Cancel",next:"Next",previous:"Previous",play:"Play",pause:"Pause",close:"Close",errors:{single:'You must install the <a href="{0}">{1}</a> browser plugin to view this content.',shared:'You must install both the <a href="{0}">{1}</a> and <a href="{2}">{3}</a> browser plugins to view this content.',either:'You must install either the <a href="{0}">{1}</a> or the <a href="{2}">{3}</a> browser plugin to view this content.'}};
(function(){var F=Shadowbox;var L=F.lib;var A=F.getClient();var I;var M;var J="shadowbox_drag_layer";var K;var D=function(){I={x:0,y:0,start_x:null,start_y:null}};var E=function(N,O,C){if(N){D();var P=["position:absolute","height:"+O+"px","width:"+C+"px","cursor:"+(A.isGecko?"-moz-grab":"move"),"background-color:"+(A.isIE?"#fff;filter:alpha(opacity=0)":"transparent")];L.append(L.get("shadowbox_body_inner"),'<div id="'+J+'" style="'+P.join(";")+'"></div>');L.addEvent(L.get(J),"mousedown",H)}else{var Q=L.get(J);if(Q){L.removeEvent(Q,"mousedown",H);L.remove(Q)}}};var H=function(N){L.preventDefault(N);var C=L.getPageXY(N);I.start_x=C[0];I.start_y=C[1];M=L.get("shadowbox_content");L.addEvent(document,"mousemove",G);L.addEvent(document,"mouseup",B);if(A.isGecko){L.setStyle(L.get(J),"cursor","-moz-grabbing")}};var B=function(){L.removeEvent(document,"mousemove",G);L.removeEvent(document,"mouseup",B);if(A.isGecko){L.setStyle(L.get(J),"cursor","-moz-grab")}};var G=function(Q){var O=F.getContent();var R=F.getDimensions();var P=L.getPageXY(Q);var N=P[0]-I.start_x;I.start_x+=N;I.x=Math.max(Math.min(0,I.x+N),R.inner_w-O.width);L.setStyle(M,"left",I.x+"px");var C=P[1]-I.start_y;I.start_y+=C;I.y=Math.max(Math.min(0,I.y+C),R.inner_h-O.height);L.setStyle(M,"top",I.y+"px")};Shadowbox.img=function(O,N){this.id=O;this.obj=N;this.resizable=true;this.ready=false;var C=this;K=new Image();K.onload=function(){C.height=C.obj.height?parseInt(C.obj.height,10):K.height;C.width=C.obj.width?parseInt(C.obj.width,10):K.width;C.ready=true;K.onload="";K=null};K.src=N.content};Shadowbox.img.prototype={markup:function(C){return{tag:"img",id:this.id,height:C.resize_h,width:C.resize_w,src:this.obj.content,style:"position:absolute"}},onLoad:function(){var C=F.getDimensions();if(C.drag&&F.getOptions().handleOversize=="drag"){E(true,C.resize_h,C.resize_w)}},remove:function(){var C=L.get(this.id);if(C){L.remove(C)}E(false);if(K){K.onload="";K=null}}}})();
(function(){var A=Shadowbox;var B=A.lib;Shadowbox.html=function(D,C){this.id=D;this.obj=C;this.height=this.obj.height?parseInt(this.obj.height,10):300;this.width=this.obj.width?parseInt(this.obj.width,10):500};Shadowbox.html.prototype={markup:function(C){return{tag:"div",id:this.id,cls:"html",html:this.obj.content}},remove:function(){var C=B.get(this.id);if(C){B.remove(C)}}}})();
(function(){var A=Shadowbox;var B=A.lib;var D=A.getClient();Shadowbox.iframe=function(E,C){this.id=E;this.obj=C;this.height=this.obj.height?parseInt(this.obj.height,10):B.getViewportHeight();this.width=this.obj.width?parseInt(this.obj.width,10):B.getViewportWidth()};Shadowbox.iframe.prototype={markup:function(E){var C={tag:"iframe",id:this.id,name:this.id,height:"100%",width:"100%",frameborder:"0",marginwidth:"0",marginheight:"0",scrolling:"auto"};if(D.isIE){C.allowtransparency="true";if(!D.isIE7){C.src='javascript:false;document.write("");'}}return C},onLoad:function(){var C=(D.isIE)?B.get(this.id).contentWindow:window.frames[this.id];C.location=this.obj.content},remove:function(){var C=B.get(this.id);if(C){B.remove(C);if(D.isGecko){delete window.frames[this.id]}}}}})();
(function(){var A=Shadowbox;var B=A.lib;Shadowbox.swf=function(D,C){this.id=D;this.obj=C;this.resizable=true;this.height=this.obj.height?parseInt(this.obj.height,10):300;this.width=this.obj.width?parseInt(this.obj.width,10):300};Shadowbox.swf.prototype={markup:function(D){var C=A.getOptions().flashBgColor;return{tag:"object",id:this.id,name:this.id,type:"application/x-shockwave-flash",data:this.obj.content,children:[{tag:"param",name:"movie",value:this.obj.content},{tag:"param",name:"bgcolor",value:C}],height:D.resize_h,width:D.resize_w}},remove:function(){var C=B.get(this.id);if(C){B.remove(C)}}}})();
(function(){var A=Shadowbox;var B=A.lib;Shadowbox.flv=function(D,C){this.id=D;this.obj=C;this.resizable=true;this.height=this.obj.height?parseInt(this.obj.height,10):300;if(A.getOptions().showMovieControls==true){this.height+=20}this.width=this.obj.width?parseInt(this.obj.width,10):300};Shadowbox.flv.prototype={markup:function(G){var E=this.obj;var F=G.resize_h;var I=G.resize_w;var L=A.getOptions();var C=String(L.autoplayMovies);var J=L.showMovieControls;var H=String(J);var K=F-(J?20:0);var D=["file="+this.obj.content,"height="+F,"width="+I,"autostart="+C,"displayheight="+K,"showicons="+H,"backcolor=0x000000","frontcolor=0xCCCCCC","lightcolor=0x557722"];return{tag:"object",id:this.id,name:this.id,type:"application/x-shockwave-flash",data:L.flvPlayer,children:[{tag:"param",name:"movie",value:L.flvPlayer},{tag:"param",name:"flashvars",value:D.join("&amp;")},{tag:"param",name:"allowfullscreen",value:"true"}],height:F,width:I}},remove:function(){var C=B.get(this.id);if(C){B.remove(C)}}}})();
(function(){var A=Shadowbox;var B=A.lib;var D=A.getClient();Shadowbox.qt=function(E,C){this.id=E;this.obj=C;this.height=this.obj.height?parseInt(this.obj.height,10):300;if(A.getOptions().showMovieControls==true){this.height+=16}this.width=this.obj.width?parseInt(this.obj.width,10):300};Shadowbox.qt.prototype={markup:function(H){var F=A.getOptions();var G=String(F.autoplayMovies);var E=String(F.showMovieControls);var C={tag:"object",id:this.id,name:this.id,height:this.height,width:this.width,children:[{tag:"param",name:"src",value:this.obj.content},{tag:"param",name:"scale",value:"aspect"},{tag:"param",name:"controller",value:E},{tag:"param",name:"autoplay",value:G}],kioskmode:"true"};if(D.isIE){C.classid="clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B";C.codebase="http://www.apple.com/qtactivex/qtplugin.cab#version=6,0,2,0"}else{C.type="video/quicktime";C.data=this.obj.content}return C},remove:function(){try{document[this.id].Stop()}catch(E){}var C=B.get(this.id);if(C){B.remove(C)}}}})();
(function(){var A=Shadowbox;var B=A.lib;var D=A.getClient();Shadowbox.wmp=function(E,C){this.id=E;this.obj=C;this.height=this.obj.height?parseInt(this.obj.height,10):300;if(A.getOptions().showMovieControls){this.height+=(D.isIE?70:45)}this.width=this.obj.width?parseInt(this.obj.width,10):300};Shadowbox.wmp.prototype={markup:function(H){var F=A.getOptions();var G=F.autoplayMovies?1:0;var E={tag:"object",id:this.id,name:this.id,height:this.height,width:this.width,children:[{tag:"param",name:"autostart",value:G}]};if(D.isIE){var C=F.showMovieControls?"full":"none";E.classid="clsid:6BF52A52-394A-11d3-B153-00C04F79FAA6";E.children[E.children.length]={tag:"param",name:"url",value:this.obj.content};E.children[E.children.length]={tag:"param",name:"uimode",value:C}}else{var C=F.showMovieControls?1:0;E.type="video/x-ms-wmv";E.data=this.obj.content;E.children[E.children.length]={tag:"param",name:"showcontrols",value:C}}return E},remove:function(){if(D.isIE){try{window[this.id].controls.stop();window[this.id].URL="non-existent.wmv";window[this.id]=function(){}}catch(E){}}var C=B.get(this.id);if(C){setTimeout(function(){B.remove(C)},10)}}}})();
/**
 * The "classic" theme markup for Shadowbox.
 *
 * This file is part of Shadowbox.
 *
 * Shadowbox is an online media viewer application that supports all of the
 * web's most popular media publishing formats. Shadowbox is written entirely
 * in JavaScript and CSS and is highly customizable. Using Shadowbox, website
 * authors can showcase a wide assortment of media in all major browsers without
 * navigating users away from the linking page.
 *
 * Shadowbox is released under version 3.0 of the Creative Commons Attribution-
 * Noncommercial-Share Alike license. This means that it is absolutely free
 * for personal, noncommercial use provided that you 1) make attribution to the
 * author and 2) release any derivative work under the same or a similar
 * license.
 *
 * If you wish to use Shadowbox for commercial purposes, licensing information
 * can be found at http://mjijackson.com/shadowbox/.
 *
 * @author      Michael J. I. Jackson <mjijackson@gmail.com>
 * @copyright   2007-2008 Michael J. I. Jackson
 * @license     http://creativecommons.org/licenses/by-nc-sa/3.0/
 * @version     SVN: $Id: skin.js 108 2008-07-11 04:19:01Z mjijackson $
 */

if(typeof Shadowbox == 'undefined'){
    throw 'Unable to load Shadowbox skin, base library not found.';
}

/**
 * The HTML markup to use for Shadowbox.
 *
 * IMPORTANT: The script depends on most of these elements being present.
 *
 * @property    {Object}    SKIN
 * @public
 * @static
 */
Shadowbox.SKIN = {

    markup:     '<div id="shadowbox_container">' +
                    '<div id="shadowbox_overlay"></div>' +
                    '<div id="shadowbox">' +
                        '<div id="shadowbox_title">' +
                            '<div id="shadowbox_title_inner"></div>' +
                        '</div>' +
                        '<div id="shadowbox_body">' +
                            '<div id="shadowbox_body_inner"></div>' +
                            '<div id="shadowbox_loading">' +
                                '<div id="shadowbox_loading_indicator"></div>' +
                                '<span><a onclick="Shadowbox.close();">{cancel}</a></span>' +
                            '</div>' +
                        '</div>' +
                        '<div id="shadowbox_info">' +
                            '<div id="shadowbox_info_inner">' +
                                '<div id="shadowbox_counter"></div>' +
                                '<div id="shadowbox_nav">' +
                                    '<a id="shadowbox_nav_close" title="{close}" onclick="Shadowbox.close()"></a>' +
                                    '<a id="shadowbox_nav_next" title="{next}" onclick="Shadowbox.next()"></a>' +
                                    '<a id="shadowbox_nav_play" title="{play}" onclick="Shadowbox.play()"></a>' +
                                    '<a id="shadowbox_nav_pause" title="{pause}" onclick="Shadowbox.pause()"></a>' +
                                    '<a id="shadowbox_nav_previous" title="{previous}" onclick="Shadowbox.previous()"></a>' +
                                '</div>' +
                                '<div class="shadowbox_clear"></div>' +
                            '</div>' +
                        '</div>' +
                    '</div>' +
                '</div>',

    png_fix:    [
        'shadowbox_nav_close',
        'shadowbox_nav_next',
        'shadowbox_nav_play',
        'shadowbox_nav_pause',
        'shadowbox_nav_previous'
    ]

};
Ext.namespace("Flowz");


/**
 * A smaller button than the typical extjs button.  This only uses a single div and is fixed width and height.
 *
 * @param config
 */

Flowz.MiniButton = function(config) {
	Flowz.MiniButton.superclass.constructor.call(this, config);
	Ext.apply(this, config);
};

Flowz.MiniButton = Ext.extend(Ext.Component, {
	cls: 'x-mini-btn',
	sprite: '',
	width: 31,
	height: 31,
	posLeft: 0,

	initComponent: function() {

	},

	onRender: function(container, position) {
		Flowz.MiniButton.superclass.onRender.call(this, container, position);

		this.el = Ext.DomHelper.append(container, {
			tag: 'div', cls: this.cls, style: 'background: url(' + this.sprite + ') no-repeat ' + this.posLeft + 'px 0; float: right; width: ' + this.width + 'px; height: ' + this.height + 'px;'
		}, true);

		this.el.on('click', function() {
			this.fireEvent('click', this);
		}, this);

		this.el.on('mousedown', function() {
			this.el.setStyle("background-position", this.posLeft + "px " + (this.height * 2 * -1) + "px");
		}, this);

		this.el.on('mouseup', function() {
			this.el.setStyle("background-position", this.posLeft + "px " + (this.height * -1) + "px");

		}, this);

		this.el.on('mouseout', function() {
			this.el.setStyle("background-position", this.posLeft + "px 0px");
			this.el.setStyle("cursor", "default");
		}, this);

		this.el.on('mouseover', function(e) {
			this.el.setStyle("background-position", this.posLeft + "px " + (this.height * -1) + "px");
			this.el.setStyle("cursor", "pointer");
		}, this);
	}

});Ext.namespace("Flowz");


/**
 * A popup window that allows for editing short blurbs of text.
 *
 * @param config
 */

Flowz.DescEditor = function(config) {
	Flowz.DescEditor.superclass.constructor.call(this, config);
};

Flowz.DescEditor = Ext.extend(Ext.Component, {
	cls: 'x-desc-input',
	textareaId: "desc-editor-textarea",
	sprite: '',
	width: 37,
	height: 38,
	defaultDesc: 'You may enter an optional description for your file.',

	initComponent: function() {

	},

	getDescription: function() {
		return this.description;
	},

	onRender: function(container, position) {
		Flowz.DescEditor.superclass.onRender.call(this, container, position);

		this.el = Ext.DomHelper.append(this.container.dom, {
			tag: 'div', cls: 'x-desc-input x-hidden', children:[{
			tag: 'textarea', html: 'Enter an optional description...', id: this.textareaId
		},{
			tag: 'div', cls: 'x-desc-toolbar'
		}]
		}, true);

		//this.el.setVisibilityMode(Ext.Element.DISPLAY);
		
		this.textarea = this.el.child("textarea");

		this.textarea.on('focus', function() {
			this.textarea.setStyle("color", "#d0d0d0");
			if(this.textarea.dom.value == this.defaultDesc) {
				this.textarea.dom.value = "";
			}
		}, this);

		var toolbar = this.el.child("div.x-desc-toolbar");

		//var ok = new Ext.tek.MiniButton({ renderTo: toolbar, sprite:	 '/scripts/extjs/resources/images/default/tek/btn-yes-small-sprite.png'});
		var ok = new Flowz.MiniButton({ renderTo: toolbar, sprite:	 '/images/file-control/btn-save-sprite.png',
												width: 51, height: 26, posLeft: -51});
		//var cancel = new Ext.tek.MiniButton({ renderTo: toolbar, sprite: '/scripts/extjs/resources/images/default/tek/btn-no-small-sprite.png'});
		var cancel = new Flowz.MiniButton({ renderTo: toolbar, sprite: '/images/file-control/btn-save-sprite.png',
												width: 51, height: 26, posLeft: 0});

		//Ext.DomHelper.append(toolbar, { tag: 'div', style: 'clear: both;'});
		cancel.on('click', function() {
			this.cancel();
		}, this);

		ok.on('click', function() {
			this.save();
		}, this);

//		this.el.setStyle("padding", "10px");
		//this.el.setHeight(this.el.getHeight() + 26);

		this.proxy = this.el.createProxy("x-desc-input");
		this.proxy.setStyle('display', 'none');
		this.proxy.enableDisplayMode('block');
	},
	
	save: function() {
		this.textarea.blur();
		if(this.callback) {
			this.description = this.textarea.dom.value;
			this.callback(this.objectId, this.description);
		}

		this.hide(this.curTarget);
	},

	cancel: function() {
		this.textarea.blur();
		if(this.isOpen) {
			this.puff({useDisplay: true});
			this.isOpen = false;
		}
	},

	change: function(objectId, desc, left, top) {
		this.setDescription(desc);
		this.objectId = objectId;
		//this.setTop(top);
		//this.setLeft(left);
		this.moveTo(left, top, true);
	},

	setDescription: function(desc) {
		this.description = this.defaultDesc;
		if(desc) {
			this.description = desc;
			this.textarea.setStyle("color", "#d0d0d0");
		} else {
			this.textarea.setStyle("color", "#333333");	
		}
		this.textarea.dom.value = this.description;
	},

	show: function(target, objectId, desc, callback) {

		var left = this.getLeft();
		if(left < 5)
			left = 5;

		var view = Ext.getBody().getViewSize();
		if(left + this.getWidth() > view.width - 5)
			left = view.width - this.getWidth() - 5;

		this.el.setLeft(left);
		
		this.setDescription(desc);
		
		this.objectId = objectId;
		
		if(callback)
			this.callback = callback;

		if(target) {
			this.curTarget = target;
			this.proxy.show();
			this.proxy.setBox(target.getBox());
			this.proxy.setOpacity(0);
			var b = this.el.getBox(false);
			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);
		}
		this.isOpen = true;
		//this.el.show(arguments);
	},

	hide: function(target, anim) {
		this.isOpen = false;
		this.proxy.hide();
		if(target) {
			this.proxy.show();
			this.proxy.setBox(this.el.getBox());
			this.proxy.setOpacity(1);
			var b = target.getBox(false);
			b.scope = this;
			b.duration = .25;
			b.easing = 'easeNone';
			b.opacity = 0;
			b.block = true;
			b.callback = this.afterHide;
			//this.el.setStyle('display', 'none');
			this.proxy.shift(b);
			this.el.hide();
		} else {
			this.el.hide({anim: true, duration: .15, useDisplay: true});
		}

		//this.callback(this.description);
	},

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

	afterHide: function() {
		this.proxy.hide();
		this.textarea.blur();
	},

	puff: function() {
		this.el.puff(arguments);
	},

	frame: function() {
		this.el.frame(arguments);
	},

	getWidth: function() {
		return this.el.getWidth();
	},

	getHeight: function() {
		return this.el.getHeight();
	},

	getTop: function() {
		return this.el.getTop();
	},

	getLeft: function() {
		return this.el.getLeft();
	},
	/*
	 setWidth: function(width) {
		 this.el.setWidth(width);
	 },

	 setHeight: function(height) {
		 this.el.setHeight(height);
	 },
 */
	setTop: function(top) {
		this.el.setTop(top);
	},

	setLeft: function(left) {
		this.el.setLeft(left);
	},

	moveTo: function(left, top, animate) {
		if(left < 5)
			left = 5;

		var view = Ext.getBody().getViewSize();
		if(left + this.getWidth() > view.width - 5)
			left = view.width - this.getWidth() - 5;

		this.el.moveTo(left, top, animate);
	}

});

//Ext.reg('toolbarbutton', Ext.tek.ToolbarButton);Ext.namespace("Flowz");

Flowz.Editor = function(config) {
	Ext.apply(this, config);

};

Flowz.Editor = Ext.extend(Ext.form.HtmlEditor, {
	
	setReadOnly: function(readOnly){
		if(readOnly){
			this.getToolbar().disable();
			this.syncValue();
			if(!this.iwrap) {
				var iframe = Ext.get(this.iframe);
				this.iwrap = iframe.wrap();
			}
			var roMask = this.iwrap.mask();
			roMask.dom.style.filter = "alpha(opacity=7);"; //IE
			roMask.dom.style.opacity = ".07"; //Mozilla
			roMask.dom.style.background = "#ccc";
			this.el.dom.readOnly = true;
		} else {
			if(this.rendered){
                if(this.iwrap)
				    this.iwrap.unmask();
			}
			this.el.dom.readOnly = false;
			this.getToolbar().enable();
		}
	},

	/*
	initEditor : function() {
		Flowz.Editor.superclass.initEditor.call(this);
		var dbody = Ext.get(this.getEditorBody());
		//dbody.setStyle("padding-left", "6px");

        //Ext.DomHelper.applyStyles(dbody, ss);
	},*/

	onRender : function(ct, position){
		Flowz.Editor.superclass.onRender.call(this, ct, position);
		this.tb.items.each(function(item){
           item.enable();
        });
	},

	getDocMarkup : function(){
        return '<html><head><style type="text/css">body{font-size: 1.25em; border:0;margin:0;padding:3px;padding-left:6px;height:98%;cursor:text;}</style></head><body></body></html>';
    }

	/*  ... original code ... but might have found a workaround...
	onDisable: function(){
		if(this.rendered){
			this.wrap.mask();
		}
		Ext.form.HtmlEditor.superclass.onDisable.call(this);
	},

	onEnable: function(){
		if(this.rendered){
			this.wrap.unmask();
		}
		Ext.form.HtmlEditor.superclass.onEnable.call(this);
	},

	 mask : function(msg, msgCls){
        if(this.getStyle("position") == "static"){
            this.setStyle("position", "relative");
        }
        if(this._maskMsg){
            this._maskMsg.remove();
        }
        if(this._mask){
            this._mask.remove();
        }

        this._mask = Ext.DomHelper.append(this.dom, {cls:maskCls}, true);  // seriously, that's the fucking change (cls:maskCls) right there. 

        this.addClass("x-masked");
        this._mask.setDisplayed(true);
        if(typeof msg == 'string'){
            this._maskMsg = Ext.DomHelper.append(this.dom, {cls:"ext-el-mask-msg", cn:{tag:'div'}}, true);
            var mm = this._maskMsg;
            mm.dom.className = msgCls ? "ext-el-mask-msg " + msgCls : "ext-el-mask-msg";
            mm.dom.firstChild.innerHTML = msg;
            mm.setDisplayed(true);
            mm.center(this);
        }
        if(Ext.isIE && !(Ext.isIE7 && Ext.isStrict) && this.getStyle('height') == 'auto'){ // ie will not expand full height automatically
            this._mask.setSize(this.dom.clientWidth, this.getHeight());
        }
        return this._mask;
    },

    unmask : function(){
        if(this._mask){
            if(this._maskMsg){
                this._maskMsg.remove();
                delete this._maskMsg;
            }
            this._mask.remove();
            delete this._mask;
        }
        this.removeClass("x-masked");
    }
    */

});

Ext.namespace("Flowz");

Flowz.Attach = function(config) {
	Flowz.Attach.superclass.constructor.call(this, config);
	Ext.apply(this, config);
	
	// our internal queue when using basic upload
	this.basicQueue = new Ext.util.MixedCollection();
	// unlike, basic upload, swf will maintain it's own queue.  This is a copy for when we are working
	// with properties of a file not maintained by swf.
	this.swfQueueCopy = new Ext.util.MixedCollection();

	this.context = "/";

    this.iconPath = config && config.iconPath ? config.iconPath : '/images/icons';
	this.imagePath = config && config.imagePath ? config.imagePath : '/scripts/extjs/resources/images/default/tek';

	this.deleteIcon = config && config.deleteIcon ? config.deleteIcon : 'remove-btn.png';
	this.deleteIcon = this.imagePath + '/' + this.deleteIcon;

	this.buttonClass = config && config.buttonClass ? config.buttonClass : 'x-attach-btn';

	this.baseParams = {
		"uploadTicket": this.uploadTicket ? this.uploadTicket : 'bunk',  // uunique for every view of upload screen...
		"userId": this.userId,
		disposition: config && config.disposition ? config.disposition : this.disposition
	};
};

Ext.extend(Flowz.Attach, Ext.Component, {
	maxNameLength: 65,
	totalBytes: 0,
	fileCount: 0,
	rowCount: 0,
	width: 780,
	thumbCheckDelay: 3000,
	buttonWidth: 150,
	buttonHeight: 120,
	buttonSprite: "/images/attach-btn-sprite.png",
	okayToProceed: true,
	enableDescEditor: false,
	buttonClass: 'x-attach-btn',
	name: "Attachment Control",
	useAdvanced: false,
	immediateUpload: false,
	debug: false,
	single: false,
	disposition: "MESSAGE",
    unknownErrorText: "Unknown Error.",
    lameFormPostFix: 0,
	fileTemplate: [
			'<div class="x-file">',
			'<div class="x-file-preview"><img src="{iconPath}/thumb-{fileExt}.jpg"></div>',
			'<div class="x-file-reflection"><img src="{iconPath}/ref/thumb-{fileExt}-ref.png"></div>',
			'<div class="x-file-name">{fileName}</div>',
			'<div class="x-file-size">{fileSize}</div>',
			'</div>'
		],
    
    /**
	 * @cfg {Number} progressInterval How often (in ms) is progress requested from server
	 */
	progressInterval: 1000,

	/*
	 * Private constants:
	 */
	/**
	 * @property FLOAT_EL_WIDTH
	 * @type Number
	 * The width (in pixels) of floatEl.
	 * It should be less than the width of the IE "Browse" button's width (65 pixels), since IE doesn't let you resize it.
	 * We define this width so we can quickly center floatEl at the mouse cursor without having to make any function calls.
	 * @private
	 */
	FLOAT_EL_WIDTH: 60,

	/**
	 * @property FLOAT_EL_HEIGHT
	 * @type Number
	 * The heigh (in pixels) of floatEl.
	 * It should be less than the height of the "Browse" button's height.
	 * We define this height so we can quickly center floatEl at the mouse cursor without having to make any function calls.
	 * @private
	 */
	FLOAT_EL_HEIGHT: 30,
    INPUT_EL_HEIGHT: 35,
	
	initComponent: function() {
		Flowz.Attach.superclass.initComponent.call(this);
		this.files = new Ext.util.MixedCollection();
	},

    /**
     * UI
     *  Add
     *  Remove
     *  Start
     *  Cancel
     *
     * Upload
     *  Progress Update
     *  Finished File
     *  Finished Queue
     *  Error
     *  
     */
    //

	onRender : function(container, position) {
		this.container = container;
		Flowz.Attach.superclass.onRender.call(this, container, position);
		this.createUI();
		this.createUploader();
	},

	createUI: function() {
		var playerVersion = swfobject.getFlashPlayerVersion();
		this.haveFlash = (playerVersion.major >= 9);

		this.button = Ext.DomHelper.append(this.container.dom, {
            tag: 'div', id: 'attach-btn', cls: this.buttonClass, style: 'width: ' + this.buttonWidth + 'px; height: ' + this.buttonHeight + 'px;'
		}, true);

		this.holder = Ext.DomHelper.append(this.button.dom, {
		    tag: 'div', id: 'attach-btn-holder', style: 'width: ' + this.buttonWidth + 'px; height: ' + this.buttonHeight + 'px;'
		}, true);

        this.type = "Advanced Uploader";
		if(!this.haveFlash || !this.useAdvanced) {
            this.type = "Basic Uploader";
         	this.button.on('mouseover', function() {
				 this.button.setStyle("background-position", "0px -" + this.buttonHeight + "px");
				this.button.setStyle("cursor", "pointer");
			}, this);

			this.button.on('mouseout', function() {
				this.button.setStyle("background-position", "0px 0px");
				this.button.setStyle("cursor", "default");
			}, this);
		
			this.button.on('mousedown', function() {
				this.button.setStyle("background-position", "0px -" + (this.buttonHeight * 2) + "px");
			}, this);
			this.button.on('mouseup', function() {
				this.button.setStyle("background-position", "0px -" + this.buttonHeight + "px");
			}, this);

			////////////////////
			this.holder.position('relative');
			var styleCfg = {
				position: 'absolute',
				overflow: 'hidden',
				top: '0px', // default
				left: '0px' // default
			};

			if (Ext.isIE) {
				Ext.apply(styleCfg, {
					left: '-3px',
					top: '-3px'
				});
			} else if (Ext.isGecko) {
				Ext.apply(styleCfg, {
					left: '-3px',
					top: '-3px'
				});
			} else if (Ext.isSafari) {
				Ext.apply(styleCfg, {
					left: '-4px',
					top: '-2px'
				});
			}
			this.clipEl = this.holder.createChild({
				tag: 'div',
				style: styleCfg
			});
			this.setClipSize();
			this.clipEl.on({
				'mousemove': this.onButtonMouseMove,
				'mouseover': this.onButtonMouseMove,
				scope: this
			});

			this.floatEl = this.clipEl.createChild({
				tag: 'div',
				style: {
					position: 'absolute',
					width: this.FLOAT_EL_WIDTH + 'px',
					height: this.FLOAT_EL_HEIGHT + 'px',
					overflow: 'hidden'
				}
			});


			if (this.debug) {
				/*
                this.clipEl.applyStyles({
					'background-color': 'green'
				});
				*/
				this.floatEl.applyStyles({
					'background-color': 'red'
				});
			} else {
				this.clipEl.setOpacity(0.0);
			}

			this.createInputFile();
			////////////////////
		} else {

        }
		
		if(this.enableDescEditor) {
			this.descEditor = new Flowz.DescEditor({ renderTo: this.container.dom });
		}
	},

	createUploader: function() {
		if(this.haveFlash && this.useAdvanced) {
        	this.swfu = new SWFUpload({
				// Backend Settings
				upload_url: this.url ? this.url : 'files.html',  // Relative to the SWF file

				post_params: {
                    uploadTicket: this.uploadTicket,
                    userId: this.userId,
					disposition: this.disposition
                },

				file_post_name: 'filedata',
				use_query_string: true,

				// File Upload Settings
				file_size_limit : "2048000",
				file_types: this.allowedTypes ? this.allowedTypes : "",
				//file_types_description : "JPG Images",
				file_upload_limit : "0",

				// Event Handler Settings
				file_queued_handler: this.fileQueued.createDelegate(this),
				file_queue_error_handler: this.fileQueueError.createDelegate(this),
				upload_progress_handler: this.uploadProgress.createDelegate(this),
				upload_error_handler: this.uploadError.createDelegate(this),
				upload_complete_handler: this.uploadComplete.createDelegate(this),
				upload_success_handler: this.uploadSuccess.createDelegate(this),
				upload_start_handler: this.queuedUploadStarted.createDelegate(this),
				transparent: 'true',
				button_placeholder_id: "attach-btn-holder",
				button_image_url: this.buttonSprite,
				button_width: this.buttonWidth,
				button_height: this.buttonHeight,

				// Flash Settings (Contains code for the swf upload)
				flash_url : "/scripts/swf/swfupload.swf",	// Relative to this file

				// Debug Settings
				debug: this.debug
			});
		} else {
			// setup basic upload
		}
	},

	/**
	 * Creates the input file element and adds it to inputFileCt.
	 * The created input file elementis sized, positioned, and styled appropriately.
	 * Event handlers for the element are set up, and a tooltip is applied if defined in the original config.
	 * @private
	 */
	createInputFile: function(){
		// When an input file gets detached and set as the child of a different DOM element,
		// straggling <em> elements get left behind.
		// I don't know why this happens but we delete any <em> elements we can find under the floatEl to prevent a memory leak.
		this.floatEl.select('em').each(function(el){
			el.remove();
		});
		this.inputFileEl = this.floatEl.createChild({
			tag: 'input',
			type: 'file',
			size: 1, // must be > 0. It's value doesn't really matter due to our masking div (inputFileCt).
			name: this.inputFileName || Ext.id(this.el),
			tabindex: this.tabIndex,
			// Use the same pointer as an Ext.Button would use.  This doesn't work in Firefox.
			// This positioning right-aligns the input file to ensure that the "Browse" button is visible.
			style: {
				position: 'absolute',
				cursor: 'pointer',
				right: '0px',
				top: '0px'
			}
		});

        //this.inputFileEl.setStyle("font-size", "25px");
        this.inputFileEl.setStyle("font-size", this.INPUT_EL_HEIGHT + "px");
		this.inputFileEl = this.inputFileEl.child('input') || this.inputFileEl;

		// setup events
		this.inputFileEl.on({
			'click': this.onInputFileClick,
			'change': this.onInputFileChange,
			'focus': this.onInputFileFocus,
			'select': this.onInputFileFocus,
			'blur': this.onInputFileBlur,
			scope: this
		});

		// add a tooltip
		if (this.tooltip) {
			if (typeof this.tooltip == 'object') {
				Ext.QuickTips.register(Ext.apply({
					target: this.inputFileEl
				}, this.tooltip));
			} else {
				this.inputFileEl.dom[this.tooltipType] = this.tooltip;
			}
		}
	},

	createForm:function(file, uploadCount) {
		var form = Ext.getBody().createChild({
			 tag:'form',
			action:this.url,
			method:'post',
			cls:'x-hidden',
			id:Ext.id(),
			cn:[{
				tag:'input',
				type:'hidden',
				name:'Filename',
				value:file.name
			},{
				tag:'input',
				type:'hidden',
				name:'uploadTicket',
				value:this.uploadTicket
			},{
				tag:'input',
				type:'hidden',
				name:'userID',
				value:this.userId
			},{
				tag:'input',
				type:'hidden',
				name:'uploadCount',
				value:uploadCount
			}]
		});
		if(file) {
			file.form = form;
            file.uploadCount = uploadCount;
			file.uploadTicket = this.uploadTicket;
		}
		return form;

	},

	deleteForm:function(form, file) {
		form.remove();
		file.form = null;
	},

	// event handler for both uploads, called by SWF or by even handler for file input
	fileQueued: function(file) {
//		alert("fileQueued");
		if(this.swfu) {
			this.swfu.addFileParam(file.id, "Filename", file.name);
            this.totalBytes += file.size;
			this.swfQueueCopy.add(file.id, file);
        } else {
			this.basicQueue.add(file);
		}
		this.addUIEntry(file);

		if(this.immediateUpload) {
			this.startUpload();
		}

		if(this.single) {
			this.disable();
		}
		//this.updateProgressUI(file, null, .45);
	},

	fileQueueError: function(file, error_code, message) {
		try {
			//var image_name = "error.gif";
			var error_name = "";
			if(error_code === SWFUpload.ERROR_CODE_QUEUE_LIMIT_EXCEEDED) {
				// TODO: JS Externalize...
				error_name = "You have attempted to queue too many files.";
			}

			if(error_name !== "") {
				alert("Test: " + error_name);
				return;
			}

			switch(error_code) {
			case SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT:
			//	image_name = "toobig.gif";
			//	break;
			case SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE:
			case SWFUpload.QUEUE_ERROR.INVALID_FILETYPE:
			default:
				alert("Unknown error code: " + message);
				this.okayToProceed = false;
				break;
			}

			//addImage("images/" + image_name);

		} catch (ex) {
			this.swfu.debug(ex);
		}
	},

	// for swf upload, when a queued file upload is started
	queuedUploadStarted: function(file) {
		if(this.swfu)
			this.currentUploadFile = this.swfQueueCopy.get(file.id);
	},

	removeFile: function(file) {
		if(this.disabled)
			return;
		if(this.swfu)
			this.swfu.cancelUpload(file.id);
        else
		    this.basicQueue.remove(file);
		//this.spacer.setWidth(this.spacer.getWidth() + (file.cell.getWidth()/2));
		this.fileCount--;
		if(this.fileCount < 0)
			this.fileCount = 0;

		file.cell.remove();
		delete file.cell;
	},

    getFilesQueued: function() {
        if(this.swfu) {
            return this.swfu.getStats().files_queued;
        } else {
            return this.basicQueue.getCount();
        }
    },

	// for both uploads, public API to initiate upload
	startUpload: function(progressbar) {
//		alert("startUpload");

		if(this.queueStart)
			this.queueStart();
        this.transferredFiles = 0;
		this.transferredBytes = 0;
		this.totalFiles = this.getFilesQueued();
        if(this.totalFiles == 0)
            return;
		this.progressBar = progressbar;
		// TODO: JS Externalize...
		this.updateProgressUI(null, "Starting upload...", 0);


		this.startTime = new Date();
        if(this.swfu) {
//			alert("calling startUpload()");
		    this.swfu.startUpload();
//			alert("what the shit?");
        } else {
            this.currentUploadIndex = 1;
            var file = this.basicQueue.get(0);
			this.currentUploadFile = file;
            this.uploadFile(file, this.currentUploadIndex);
            this.startProgress();
        }
	},

	// for basic upload
    uploadFile: function(file, uploadCount) {

		// create form for upload
		var form = this.createForm(file, uploadCount);

		// append input to the form
		var inp = file.input;
		inp.set({name:"filedata"});
		form.appendChild(inp);

		// get params for request
		var o = this.getOptions(file);
		o.form = form;

		// request upload
		Ext.Ajax.request(o);

		// todo:delete after devel
		this.getIframe.defer(100, this, [file]);

		this.updateProgressUI(file, "Uploading file: " + file.name, 0);
	},

	// for basic upload
    getOptions: function(file, params) {
		var o = {
			url:this.url + "?uploadTicket=" + this.uploadTicket + "&userId=" + this.userId + "&Filename=" + file.name + "&uploadCount=" + this.currentUploadIndex,
			method:'post',
			isUpload:true,
			scope:this,
			callback:this.uploadCallback,
			file:file,
			params:this.getParams(file, params)
		};
		return o;
	},

	// for basic upload
    getParams: function(file, params) {
		var p = {path:this.path};
		Ext.apply(p, this.baseParams || {}, params || {});
		return p;
	},

	// for basic upload
    getIframe: function(file) {
		var iframe = null;
		var form = file.form;
		if(form && form.dom && form.dom.target) {
			iframe = Ext.get(form.dom.target);
		}
		return iframe;
	},

	// for basic upload
    startProgress: function() {
		if(!this.progressTask) {
			this.progressTask = new Ext.util.DelayedTask(this.requestProgress, this);
		}
		this.progressTask.delay.defer(this.progressInterval / 2, this.progressTask, [this.progressInterval]);
	},

	// for basic upload
    requestProgress:function() {
        if(this.currentUploadIndex > this.basicQueue.getCount()) {
            return;
        }
	    progress.getProgress(this.uploadTicket, this.currentUploadIndex, this.handleUploadProgress.createDelegate(this, [ this.currentUploadFile ]));
	},

	// for basic upload
    handleUploadProgress: function(data, file) {
        this.currentTransfer = data.transferred;
            // record progress and then call progress event handler...
		var message = "";
        if(data.progress < 100)
            message = "Transferring " + this.currentUploadIndex + " of " + this.totalFiles + "...";
        else {
            if(this.currentUploadIndex == this.totalFiles) {
                this.lameFormPostFix++;
                if(this.lameFormPostFix == 4)
                    this.lameFormPostFix = 1;
                var ellipse = "";
                for(j = 1; j <= this.lameFormPostFix; j++) { ellipse += "." }
                message = "Completed " + this.currentUploadIndex + " of " + this.totalFiles + ".  Cleaning up" + ellipse;

            } else
                message = "Completed " + this.currentUploadIndex + " of " + this.totalFiles + "...";
        }
		this.updateProgressUI(file, message, (data.progress / 100));
        this.progressTask.delay(this.progressInterval);
    },

	// for swf upload
	uploadProgress: function(file, bytesLoaded) {
//		alert("Upload Progress.");
		try {
            this.currentTransfer = bytesLoaded;

			//var percent = Math.ceil((bytesLoaded / file.size) * 100);
			var percent = Math.ceil(((this.currentTransfer + this.transferredBytes) / this.totalBytes) * 100);

			// for some reason, SWF is reporting that it transferred more bytes then the file size...
			if(percent > 100)
				percent = 100;

			// TODO: JS Externalize...
			var message = percent + "% completed...";

			// TODO: JS Externalize...
			if(this.transferredFiles > 0)
				message = "Transferring " + (this.transferredFiles + 1) + " of " + this.totalFiles + " and " + message;

			this.updateProgressUI(this.swfQueueCopy.get(file.id), message, (percent / 100));

		} catch (ex) {
			if(window.console)
				console.log(ex);
		}
	},

	// for both uploads, updates the actual UI.
	updateProgressUI: function(fileEntry, label, percentComplete) {
		if(this.immediateUpload) {
			if(fileEntry == null) {
//				console.log("fileEntry is null and immediate upload is checked, can't update progress.");
				return;
			}
			if(!fileEntry.progressBar) {
				if(!fileEntry.cell) {
//					console.log("file's cell is null, unable to create progress bar.");
					return;
				}
				var container = Ext.DomQuery.selectNode("div.progress-container", fileEntry.cell.dom);
				if(!container) {
//					console.log("Could not find progress container in file entry dom, unable to create progress bar.");
					return;
				}
				fileEntry.progressBar = new Ext.ProgressBar({
					renderTo: container.id,
					animate: true,
					height: 10
				});
			}
			fileEntry.progressBar.show();
			fileEntry.progressBar.updateProgress(percentComplete);

		} else {
			this.progressBar.show();
			this.progressBar.updateProgress(percentComplete, label);
		}
	},

    // for basic upload, called when a response is received from server about upload completing
	uploadCallback:function(options, success, response) {

		var o;
		this.upCount--;
		this.form = false;
		// process ajax success
		if(true === success) {
			try {
				o = Ext.decode(response.responseText);
			}
			catch(e) {
				this.processFailure(options, response, this.jsonErrorText);
				this.fireFinishEvents(options);
				return;
			}
			// process command success
			if(true === o.success) {
				this.processSuccess(options, response, o);
			}
			// process command failure
			else {
				this.processFailure(options, response, o);
			}
		}
		// process ajax failure
		else {
			this.processFailure(options, response);
		}

		this.fireFinishEvents(options);
	},

    /**
	 * processes success response
	 * @private
	 * @param {Object} options options the request was called with
	 * @param {Object} response request response object
	 * @param {Object} o decoded response.responseText
	 */
	// for basic upload, process good response
	processSuccess:function(options, response, o) {
		var file = options.file;
		this.deleteForm(options.form, file);
		this.updateProressUI(file, "Completed file " + this.currentUploadIndex, 1);
        this.currentUploadIndex++;
        this.transferredFiles++;
        this.transferredBytes += this.currentTransfer;
        this.currentTransfer = 0;
        if(this.currentUploadIndex <= this.basicQueue.getCount()) {
            var nextFile = this.basicQueue.get(this.currentUploadIndex - 1);
            this.uploadFile(nextFile, this.currentUploadIndex);
        } else {
            this.progressTask.cancel();
            this.basicQueue.clear();
            var elapsedTime = new Date().getTime() - this.startTime.getTime();
            // convert to seconds...
            elapsedTime = parseInt(elapsedTime / 1000);
            if(elapsedTime < 1)
                elapsedTime = 1;

            // For small uploads, transferredBytes might be 0 because the progress task hasn't returned yet.
            if(this.transferredBytes > 0)
                this.updateProgressUI(file, "Upload complete, transferred " + formatBytes(this.transferredBytes) + " in " + formatTime(elapsedTime) + ".  Now sending message...", 1);
            else
                this.updateProgressUI(file, "Upload complete, transferred " + this.transferredFiles + " files in " + formatTime(elapsedTime) + ".  Now sending message...", 1);

            if(this.queueComplete)
                this.queueComplete();
        }
	},

	/**
	 * processes failure response
	 * @private
	 * @param {Object} options options the request was called with
	 * @param {Object} response request response object
	 * @param {String/Object} error Error text or JSON decoded object. Optional.
	 */
	// for basic upload
	processFailure:function(options, response, error) {
		var file = options.file;

        // is this first one ever true?
        if(error && 'object' === Ext.type(error)) {
            file.error = error.errors && error.errors[file.id] ? error.errors[file.id] : this.unknownErrorText;
        }
        else if(error) {
            file.error = error;
        }
        else if(response && response.responseText) {
            file.error = response.responseText;
        }
        else {
            file.error = this.unknownErrorText;
        }
	},

	// for swf upload
	uploadComplete: function(swfFile) {
		if(swfFile.filestatus != SWFUpload.FILE_STATUS.COMPLETE) {
			// problem, skip everything else. (complete is still called even if there is an error!)
			return;
		}
		//console.log("uploadComplete: " + swfFile.id);
		var file = this.swfQueueCopy.get(swfFile.id);

		if(this.immediateUpload) {
			if(file.progressBar) {
				file.progressBar.hide();
				var container = Ext.DomQuery.selectNode("div.progress-container", file.cell.dom);
				container = Ext.get(container);
				container.hide();
				//file.progressBar.remove();
			}
			// if this is a thumbnailable file, load the thumb.
			var ext = getFileExt(file.name);
			if(ext == "jpg" || ext == "jpeg" || ext == "gif" || ext == "png" || ext == "psd" || ext == "bmp" || ext == "tif" || ext == "tiff" || ext == "eps") {
				if(file.infoBar) {
					Ext.DomHelper.overwrite(file.infoBar, [{ tag: 'img', src: this.context + "images/icon-loading-thumb.gif", width: 16, height: 16 },
						{ tag: 'span', html: ' Loading ' + (this.disposition == 'LOGO' ? 'image' : 'thumbnail...') }]);
				}
				this.checkThumb.defer(this.thumbCheckDelay, this, [ file, 0 ]);
			} else {
				if(file.infoBar) {
					file.infoBar.hide({ anim: true, callback: file.infoBar.remove.createDelegate(file.infoBar)});
				}
			}
		}
	},

	checkThumb: function(file, count) {
		count++;
		if(count > 10) {
			// abort...
			if(file.infoBar) {
				file.infoBar.hide({ anim: true, callback: file.infoBar.remove.createDelegate(file.infoBar)});
				return;
			}
		}
		var checkUrl;
		if(this.disposition == "AVATAR")
			checkUrl = this.context + 'files/' + file.systemId + '/1/FACE/view/' + file.name + '.jpg?bypassDefault=true';
		else if(this.disposition == 'LOGO')
			checkUrl = this.context + 'files/' + file.systemId + '/1/view/' + file.name + '.jpg?bypassDefault=true';
		else
			checkUrl = this.context + 'files/' + file.systemId + '/1/THUMB/view/' + file.name + '.jpg?bypassDefault=true';
		//console.log("checking to see if thumb exists: " + checkUrl);

		Ext.Ajax.request({
			url: checkUrl,
			success: this.swapForThumb.createDelegate(this, [ file, checkUrl ]),
			failure: function() {
				//console.log("thumb doesn't exist yet, deferring another second for file: " + file.name);
				this.checkThumb.defer(this.thumbCheckDelay, this, [ file, count ]);
			},
			scope: this

		});
	},

	swapForThumb: function(file, thumbUrl) {
		//console.log("Thumb is ready. Stopping check for file: " + file.name);
		//var container = Ext.DomQuery.selectNode("div.x-file-preview:first-child", file.cell.dom);
		var container = Ext.DomQuery.selectNode("div.x-file-preview img", file.cell.dom);
		if(!container) {
			//console.log("could not find image container!");
		} else {
			//console.log("updating div");
			if(file.infoBar) {
				file.infoBar.hide({ anim: true, callback: file.infoBar.remove.createDelegate(file.infoBar)});
			}
			//Ext.DomHelper.overwrite(container, { tag: 'img', src: thumbUrl});
			this.crossFade(container, { tag: 'img', src: thumbUrl, style: 'position: absolute; z-index: 5'});
		}
	},

	crossFade: function(elout, elin) {
		elout = Ext.get(elout);
		elin = Ext.DomHelper.insertAfter(elout, elin, true);
		elin.hide();
		//elout.hide(true);
		elout.remove();
		elin.show(true);
	},

	// for swf upload.  needed to get ahold of the response from the server that isn't passed to uploadComplete
	uploadSuccess: function(swfFile, responseString) {
		var response = "";
		try {
			response = Ext.util.JSON.decode(responseString);
		} catch(ex) {
			if(window.console)
				console.log("Error parsing response from server.\n" + responseString);
			//return;
		}
		var file = this.swfQueueCopy.get(swfFile.id);
		file.systemId = response.id;
		if(this.onSystemIdAssigned)
			this.onSystemIdAssigned(file);
		try {
			/*  We want the next upload to continue automatically so I'll call startUpload here */
            this.transferredBytes += swfFile.size;
            this.currentTransfer = 0;
			this.transferredFiles++;
			if(this.swfu.getStats().files_queued > 0) {
				this.swfu.startUpload();
			} else {
				// find the elapsed time in milliseconds...
				var elapsedTime = new Date().getTime() - this.startTime.getTime();
				// convert to seconds...
				elapsedTime = parseInt(elapsedTime / 1000);
				if(elapsedTime < 1)
					elapsedTime = 1;
				// TODO: JS Externalize...
				this.updateProgressUI(file, "Upload complete, transferred " + formatBytes(this.totalBytes) + " in " + formatTime(elapsedTime) + ".  Now sending message...", 1);

				if(this.queueComplete)
					this.queueComplete();
			}
		} catch (ex) {
			Ext.log(ex);
		}
	},

	// for swf upload
	uploadError: function(file, error_code, message) {

        this.okayToProceed = false;
		var image_name = "error.gif";
		var progress;
        var url = this.context + "mail/compose";
        if(message == "Error #2038") {

			var dialog = new Flowz.Dialog({type: "error", message: "<div style='padding: 10px;'><h1>Your message could not be sent.</h1>" +
                          "<p>We are very sorry.  There was a problem with your upload.  It is related to an Adobe Flash bug (Error #2038).  There are " +
                            "two work arounds you can try:</p><ol><li>You can disable the advanced uploader in your <a href='" +
                            this.context + "user/options'>user options page.</a></li><li>Or you can visit this link to try and fix Flash:<blockquote>" +
                            "<a href='http://support.flowz.com/forums/11072/entries/13200' target='_new'>http://support.flowz.com/forums/11072/entries/13200</a></blockquote></li></ol>" +
                          "<p>Once you have performed either of these two steps, you can try sending your message again.</p></div>"});
			dialog.show();
			//alert("Flash error: #2038\n" + error_code);
			/*
            var win = new Ext.Window({
                    layout      : 'fit',
                    width       : 500,
                    height      : 300,
                    //closeAction :'hide',
                    plain       : true,
                    resizable: false,
                    closable: false,
                    stateful: false,
                    modal: true,
                    html: "<div style='padding: 10px;'><h1>Your message could not be sent.</h1>" +
                          "<p>We are very sorry.  There was a problem with your upload.  It is related to an Adobe Flash bug (Error #2038).  There are " +
                            "two work arounds you can try:</p><ol><li>You can disable the advanced uploader in your <a href='" +
                            this.context + "user/options'>user options page.</a></li><li>Or you can visit this link to try and fix Flash:<blockquote>" +
                            "<a href='http://support.flowz.com/forums/11072/entries/13200' target='_new'>http://support.flowz.com/forums/11072/entries/13200</a></blockquote></li></ol>" +
                          "<p>Once you have performed either of these two steps, you can try sending your message again.</p></div>",

                    buttons: [{
                        text     : 'Close',
                        handler  : function(){
                            win.hide();
                            //window.location = url;
							window.reload();
                        }
                    }]
                });
            win.show();
            */
            return;
        }
		try {
			switch(error_code) {
			case SWFUpload.UPLOAD_ERROR.FILE_CANCELLED:
                this.okayToProceed = true; // file cancel doesn't mean cancel everything!
				try {
					progress = new FileProgress(file, this.customSettings.upload_target);
					progress.SetCancelled();
					progress.SetStatus("Cancelled");
					progress.ToggleCancel(false);

				}
				catch (ex1) {
					Ext.log(ex1);
				}
				break;
			case SWFUpload.UPLOAD_ERROR.UPLOAD_STOPPED:

				try {
					progress = new FileProgress(file, this.customSettings.upload_target);
					progress.SetCancelled();
					progress.SetStatus("Stopped");
					progress.ToggleCancel(true);
				}
				catch (ex2) {
					Ext.log(ex2);
				}
                break;
			case SWFUpload.UPLOAD_ERROR.UPLOAD_LIMIT_EXCEEDED:
				image_name = "uploadlimit.gif";
				break;
         	default:
				alert("Problem uploading file: " + file + "\nError Code: "+ error_code + "\nMessage: " + message);
				// borken
				break;
			}
		} catch (ex3) {
			if(window.console)
				console.log(ex3);
		}
	},


	// for basic upload
    fireFinishEvents:function(options) {
		if(true !== this.eventsSuspended && !this.singleUpload) {
			this.fireEvent('filefinished', this, options && options.record);
		}
		if(true !== this.eventsSuspended && 0 === this.upCount) {
			this.stopProgress();
			this.fireEvent('allfinished', this);
		}
	},

	// for both uploads, add file entry to UI
	addUIEntry: function(file) {
		var filename = file.name;
		//Ext.log("File Cls: " + this.getFileCls(filename));
		var o = {
			id: file.id,
			fileExt: getFileExt(filename),
			fileCls: getFileCls(filename),
			fileName: Ext.util.Format.ellipsis(filename, this.maxNameLength),
			fileSize: formatBytes(file.size),
			fileQtip: filename,
			iconPath: this.iconPath
		};

		var t = new Ext.Template(this.fileTemplate);

		this.fileCount++;

        file.cell = t.insertBefore(this.button, o, true);

		file.removeMeCallback = this.removeFile.createDelegate(this);

		file.removeButton = new Flowz.ToolbarButton({renderTo: file.cell});

		file.removeButton.on('click', function(e) {
			if(this.disabled)
				return;
			file.removeMeCallback(file);
		}, file);

		file.cell.on('mouseover', function(e) {
			if(this.disabled)
				return;
			file.removeButton.fireMouseOver(e);
		}, this);
		file.cell.on('mouseout', function(e) {
			if(this.disabled)
				return;
			file.removeButton.fireMouseOut(e);
		}, this);

		file.swfu = this.swfu;

		if(this.enableDescEditor) {
			file.descEditor = this.descEditor;
			file.descCallback = function(newDesc) {
				file.description = newDesc;

				if(file.description == "") {
					file.swfu.removeFileParam("d-" + file.id, "description");

				} else {
					file.swfu.addFileParam(file.id, "description", file.description);
				}

				var tag = Ext.DomHelper.append(file.cell, { tag: 'div', cls: 'x-file-desc', html: file.description}, true);
				tag.hide();
				tag.show({ callback: tag.highlight("ffff9c", {
					attr: "background-color",
					endColor: "e1e1e1",
					easing: 'easeIn',
					duration: 1
				}) });
			}.createDelegate(file);

			file.cell.on('click', function(e) {
				file.descEditor.setLeft(file.cell.getLeft() - ((file.descEditor.getWidth() - file.cell.getWidth()) / 2));
				file.descEditor.setTop(file.cell.getTop() + file.cell.getHeight());
				file.descEditor.show(file.cell.child(".x-file-preview"), file.description, file.descCallback);
				//file.descInput.frame("ff0000", 3, { duration: 3 });
				//file.descEditor.frame("#C3DAF9", 1, { duration: 1});
			}, file);
		}
		if(this.immediateUpload) {
			var container = Ext.DomQuery.selectNode("div.info-container", file.cell.dom);
			if(!container) {
				//console.log("Could not find info container in file entry dom, unable to create info bar.");
				return;
			}
			// for some reason, selectNode is not returning a real EXT element...
			container = Ext.get(container);
			file.infoBar = container;
//			Ext.DomHelper.overwrite(container, [{ tag: 'img', src: this.context + "images/icon-loading-thumb.gif", width: 16, height: 16 },
//				{ tag: 'span', html: ' Uploading file...'}]);
			Ext.DomHelper.overwrite(container, { tag: 'span', html: ' Uploading file...'});
		}
		if(this.onEntryAdded) {
			this.onEntryAdded(file, file.cell);
		}
	},

	enable: function() {
		this.button.show();
		this.disabled = false;
	},

	disable: function() {
//		this.button.hide();
		this.swfu.getMovieElement().style.width = "0px";
		this.disabled = true;
	},

	/**
	 * Handler when the cursor moves over the clipEl.
	 * The floatEl gets centered to the cursor location.
	 * @param {Event} e mouse event.
	 * @private
	 */
	onButtonMouseMove: function(e){
		var xy = e.getXY();
		xy[0] -= this.FLOAT_EL_WIDTH / 2;
		xy[1] -= this.FLOAT_EL_HEIGHT / 2;
		this.floatEl.setXY(xy);
	},

	/**
	 * Add the visual enhancement to the button when the input file recieves focus.
	 * This is the tip for the user that now he/she can press space to select the file.
	 * @private
	 */
	onInputFileFocus: function(e){
		// todo: remove this
		if (!this.isDisabled) {
			//this.el.addClass("x-btn-over");
		}
	},

	/**
	 * Removes the visual enhancement from the button.
	 * @private
	 */
	onInputFileBlur: function(e){
		//this.el.removeClass("x-btn-over");
	},

	/**
	 * Handler when inputFileEl's "Browse..." button is clicked.
	 * @param {Event} e click event.
	 * @private
	 */
	onInputFileClick: function(e){
		e.stopPropagation();
	},

	/**
	 * Handler when inputFileEl changes value (i.e. a new file is selected).
	 * @private
	 */
	onInputFileChange: function() {
		var input = this.detachInputFile();
		var file = {
			name: this.getFilename(input),
			path: this.getFilePath(input),
			input: input
		};
		this.fileQueued(file);
	},

	/**
	 * get file name
	 * @private
	 * @param {Ext.Element} inp Input element containing the full file path
	 * @return {String}
	 */
	getFilename:function(inp) {
		return inp.getValue().split(/[\/\\]/).pop();
	},

	/**
	 * get file path (excluding the file name)
	 * @private
	 * @param {Ext.Element} inp Input element containing the full file path
	 * @return {String}
	 */
	getFilePath:function(inp) {
		return inp.getValue().replace(/[^\/\\]+$/,'');
	},

	/**
	 * Sets the size of clipEl so that is covering as much of the button as possible.
	 * @private
	 */
	setClipSize: function(){
		if (this.clipEl) {
			var width = this.holder.getWidth();
			var height = this.holder.getHeight();
			// The button container can have a width and height of zero when it's rendered in a hidden panel.
			// This is most noticable when using a card layout, as the items are all rendered but hidden,
			// (unless deferredRender is set to true).
			// In this case, the clip size can't be determined, so we attempt to set it later.
			// This check repeats until the button container has a size.
			if (width === 0 || height === 0) {
				this.setClipSize.defer(100, this);
			} else {
				if (Ext.isIE) {
					width = width + 5;
					height = height + 5;
				} else if (Ext.isGecko) {
					width = width + 6;
					height = height + 6;
				} else if (Ext.isSafari) {
					width = width + 6;
					height = height + 6;
				}
				this.clipEl.setSize(width, height);
			}
		}
	},

	/**
	 * Detaches the input file associated with this so that it can be used for other purposed (e.g. uplaoding).
	 * The returned input file has all listeners and tooltips applied to it by this class removed.
	 * @param {Boolean} whether to create a new input file element for this after detaching.
	 * True will prevent creation.  Defaults to false.
	 * @return {Ext.Element} the detached input file element.
	 */
	detachInputFile: function(noCreate){
		var result = this.inputFileEl;

		if (typeof this.tooltip == 'object') {
			Ext.QuickTips.unregister(this.inputFileEl);
		} else {
			this.inputFileEl.dom[this.tooltipType] = null;
		}
		this.inputFileEl.removeAllListeners();
		this.inputFileEl = null;

		if (!noCreate) {
			this.createInputFile();
		}
		return result;
	},

	/**
	 * @return {Ext.Element} the input file element attached to this BrowseButton.
	 */
	getInputFile: function(){
		return this.inputFileEl;
	}
});Ext.namespace("Flowz");

/**
 * Provides a button that will toggle between on/off states.
 * @param config
 */
Flowz.ToggleButton = function(config) {
	Ext.apply(this, config);
};

Flowz.ToggleButton = Ext.extend(Ext.Component, {
	cls: 'x-toggle-btn', // rounded rectangle
    labelCls: 'x-toggle-btn-label',
    lable: '',
    height: 38,

	autoEl: { tag: 'div', cls: this.cls },

	toggled: false,

	allowTurnOff: true,

	initComponents: function() {
		Flowz.ToggleButton.superclass.initComponent.call(this);

		this.addEvents(
			'toggleon',
			'toggleoff'
		);
	},

    toggleOff: function() {
        this.toggled = false;
        this.el.setStyle("background-position", "0px -" + (3 * this.height) + "px");
		if(this.labelEl)
        	this.labelEl.removeClass(this.onCls);
    },

    toggleOn: function() {
        this.toggled = true;
        this.el.setStyle("background-position", "0px 0px");
		if(this.labelEl)
        	this.labelEl.addClass(this.onCls);
    },

    onRender: function(container, position) {
		this.el = Ext.DomHelper.append(container, this.autoEl, true);
        this.container = container;
        if(this.label)
            this.labelEl = Ext.DomHelper.append(container, { cls: this.labelCls + " x-unselectable", html: this.label}, true);
        
        this.container.on('click', function() {
			this.fireEvent('click', this);
			if(!this.allowTurnOff && this.toggled)
				return;
			
            this.toggled = this.toggled ? false : true;
            if(this.toggled) {
                this.toggleOn();
                this.fireEvent('toggleon', this);
            } else {
                this.toggleOff();
                this.fireEvent('toggleoff', this);
            }

		}, this);

		this.container.on('mousedown', function() {
			if(!this.allowTurnOff && this.toggled)
				return;
			this.el.setStyle("background-position", "0px -" + this.height + "px");
			this.el.setStyle("cursor", "pointer");
		}, this);

		this.container.on('mouseup', function() {
			if(!this.allowTurnOff && this.toggled)
				return;
			this.el.setStyle("background-position", "0px -" + (2 * this.height) + "px");
			this.el.setStyle("cursor", "pointer");
		}, this);

		this.container.on('mouseout', function() {
            if(this.toggled) {
                this.el.setStyle("background-position", "0px 0px");
            } else {
			    this.el.setStyle("background-position", "0px -" + (3 * this.height) + "px");
            }
			this.el.setStyle("cursor", "default");
		}, this);

		this.container.on('mouseover', function() {

			if(!this.allowTurnOff && this.toggled)
				return;
			this.okayToClose = false;
			this.el.setStyle("cursor", "pointer");
			this.el.setStyle("background-position", "0px -" + (2 * this.height) + "px");

		}, this);
		if(this.toggled) {
			this.toggleOn();
		}
    }

});

Ext.namespace("Flowz");

/**
 * Provides a button that handles being shown and hidden by events.
 */
Flowz.ToolbarButton = function(config) {
    Flowz.ToolbarButton.superclass.constructor.call(this, config);
};

Ext.extend(Flowz.ToolbarButton, Ext.Component, {
	okayToClose: false,
	active: false,
	animating: false,
	animateSpeed: .2,
	hoverDelay: 250,
	height: 38,
	topOffset: 0,
	cls: 'x-remove-btn',

	initComponent: function() {
		Flowz.ToolbarButton.superclass.initComponent.call(this);
		this.id = Ext.id();
	},

	onRender: function(container, position) {
        Flowz.ToolbarButton.superclass.onRender.call(this, container, position);
		this.el = Ext.DomHelper.append(container, {
			id: this.id, tag: 'div', cls: this.cls + ' x-hidden', style: 'top: ' + this.topOffset + 'px'
		}, true);

		this.el.sequenceFx();

		this.el.on('click', function() {
			this.fireEvent('click', this);
		}, this);

		this.el.on('mousedown', function() {
			this.el.setStyle("background-position", "0px -" + (2 * this.height) + "px");
			this.el.setStyle("cursor", "pointer");
		}, this);

		this.el.on('mouseup', function() {
			this.el.setStyle("background-position", "0px -" + this.height + "px");
			this.el.setStyle("cursor", "pointer");
		}, this);

		this.el.on('mouseout', function() {
			this.el.setStyle("background-position", "0px 0px");
			this.el.setStyle("cursor", "default");
		}, this);

		this.el.on('mouseover', function() {
			this.okayToClose = false;
			this.el.setStyle("background-position", "0px -" + this.height + "px");
			this.el.setStyle("cursor", "pointer");
		}, this);
	},

	toString: function(obj) {
		var s;
		for(var p in obj) {
			s += p + " = '" + obj[p] + "', \n";
		}
		return s;
	},

	fireMouseOver: function() {
		var animConfig = {
			duration: this.animateSpeed,
            scope: this
		};

		this.el.setTop(this.container.getTop() + this.topOffset);
		this.el.setLeft(this.container.getLeft() - 16);

		this.okayToClose = false;
		if(this.hideTask) {
			this.hideTask.cancel();
		}

		if(!this.active) {
			if(this.animConfig && this.animConfig.anim && this.animConfig.anim.isAnimated()) {
				this.animConfig.anim.stop(true);		
			}

			this.animConfig=animConfig;
            if(Ext.isIE)
			    this.el.show();
            else
                this.el.show(animConfig);
			this.active = true;
		}
	},

	fireMouseOut: function() {
		this.okayToClose = true;
		this.hideTask = new Ext.util.DelayedTask(this.hide, this, [true, false]);
		this.hideTask.delay(this.hoverDelay);
	},

	hide: function(animate, overrideMouse) {
		var animConfig = {
			duration: this.animateSpeed,
            scope: this
		};

		if(this.okayToClose || overrideMouse) {
			this.active = false;
			this.animConfig = animConfig;
            if(Ext.isIE || !animate)
			    this.el.hide();
            else
                this.el.hide(animConfig);
		}
	}

});


//Ext.reg('toolbarbutton', Flowz.ToolbarButton);
Ext.namespace("Flowz");

/**
 * Manages a set of toggle buttons such that only one is toggled on at a time.
 */
Flowz.ToggleSet = function() {
};

Flowz.ToggleSet = Ext.extend(Flowz.ToggleSet, {
	addToggle: function(t) {
        if(!this.toggles)
            this.toggles = new Ext.util.MixedCollection();

        t.setId = this.toggles.getCount();
        this.toggles.add(t);
        t.on('toggleon', function(tg) {
            this.toggled = tg;
            this.value = tg.value;
            this.toggles.each(function(item, index) {
                if(this.toggled.setId != index)
                    item.toggleOff();
            }, this);
        }, this);

        t.on('toggleoff', function() {
            this.toggled = null;
            this.value = null;
        }, this);
    }
});



function getFileExt(name) {
    if(!name)
        return "";
    var atmp = name.split('.');
    if(1 === atmp.length) {
        return "";
    } else {
        return atmp.pop().toLowerCase();
    }
}

function getFileCls(name) {
    var atmp = name.split('.');
    if(1 === atmp.length) {
        return "file";
    } else {
        return "file-" + atmp.pop().toLowerCase();
    }
}

/**
 * Formats raw bytes to kB/mB/GB/TB
 * formating is decadic not binary
 * override this function if you want different format
 * @param {Integer} bytes
 * @return {Array} [value, unit]
 */
function formatBytes(bytes) {
    if(isNaN(bytes)) {
        return "";
    }
    var unit, val;
    if(999 > bytes) {
        unit = 'B';
        val = bytes;

    } else if(999999 > bytes) {
        unit = 'KB';
        val = Math.round(bytes / 1000);

    } else if(999999999 > bytes) {
        unit = 'MB';
        val = Math.round(bytes / 100000) / 10;

    } else if(999999999999 > bytes) {
        unit = 'GB';
        val = Math.round(bytes / 100000000) / 10;

    } else {
        unit = 'TB';
        val = Math.round(bytes / 100000000000) / 10;
    }

    return val + " " + unit;
}

/**
 * Formats time to hh:mm:ss omitting hh: if zero
 * override this function if you want different time format
 * @param {Integer} seconds Seconds to format
 * @return {String} Formatted time
 */
function formatTime(seconds) {
    var s = m = h = 0;
    if(3599 < seconds) {
        h = parseInt(seconds / 3600);
        seconds -= h * 3600;
    }
    if(59 < seconds) {
        m = parseInt(seconds / 60);
        seconds -= m * 60;
    }

    if(m == 0 && h == 0)
        return seconds + " seconds";

    // I don't like the extra padding right now in the progress bar
    //s = this.padLeft("" + seconds, 2, 0);

    if(h > 0) {
        //m = this.padLeft("" + m, 2, 0);
        //h = this.padLeft("" + h, 2, 0);
    }

    return (h == 0 ? '' : h + 'h ') + m + 'min, ' + s + 'secs';
}

function padLeft(str, len, pad) {
    // this doesn't work... have to do it when the method is called.
    //str = "" + str; // fix numbers passed in.
    var amount = len + 1 - str.length;
    if(amount <= 0)
        return str;
    return Array(amount).join(pad) + str;
}
/*
Copyright (c) 2009, Yahoo! Inc. All rights reserved.
Code licensed under the BSD License:
http://developer.yahoo.net/yui/license.txt
version: 2.7.0
*/
if(!YAHOO.util.DragDropMgr){YAHOO.util.DragDropMgr=function(){var A=YAHOO.util.Event,B=YAHOO.util.Dom;return{useShim:false,_shimActive:false,_shimState:false,_debugShim:false,_createShim:function(){var C=document.createElement("div");C.id="yui-ddm-shim";if(document.body.firstChild){document.body.insertBefore(C,document.body.firstChild);}else{document.body.appendChild(C);}C.style.display="none";C.style.backgroundColor="red";C.style.position="absolute";C.style.zIndex="99999";B.setStyle(C,"opacity","0");this._shim=C;A.on(C,"mouseup",this.handleMouseUp,this,true);A.on(C,"mousemove",this.handleMouseMove,this,true);A.on(window,"scroll",this._sizeShim,this,true);},_sizeShim:function(){if(this._shimActive){var C=this._shim;C.style.height=B.getDocumentHeight()+"px";C.style.width=B.getDocumentWidth()+"px";C.style.top="0";C.style.left="0";}},_activateShim:function(){if(this.useShim){if(!this._shim){this._createShim();}this._shimActive=true;var C=this._shim,D="0";if(this._debugShim){D=".5";}B.setStyle(C,"opacity",D);this._sizeShim();C.style.display="block";}},_deactivateShim:function(){this._shim.style.display="none";this._shimActive=false;},_shim:null,ids:{},handleIds:{},dragCurrent:null,dragOvers:{},deltaX:0,deltaY:0,preventDefault:true,stopPropagation:true,initialized:false,locked:false,interactionInfo:null,init:function(){this.initialized=true;},POINT:0,INTERSECT:1,STRICT_INTERSECT:2,mode:0,_execOnAll:function(E,D){for(var F in this.ids){for(var C in this.ids[F]){var G=this.ids[F][C];if(!this.isTypeOfDD(G)){continue;}G[E].apply(G,D);}}},_onLoad:function(){this.init();A.on(document,"mouseup",this.handleMouseUp,this,true);A.on(document,"mousemove",this.handleMouseMove,this,true);A.on(window,"unload",this._onUnload,this,true);A.on(window,"resize",this._onResize,this,true);},_onResize:function(C){this._execOnAll("resetConstraints",[]);},lock:function(){this.locked=true;},unlock:function(){this.locked=false;},isLocked:function(){return this.locked;},locationCache:{},useCache:true,clickPixelThresh:3,clickTimeThresh:1000,dragThreshMet:false,clickTimeout:null,startX:0,startY:0,fromTimeout:false,regDragDrop:function(D,C){if(!this.initialized){this.init();}if(!this.ids[C]){this.ids[C]={};}this.ids[C][D.id]=D;},removeDDFromGroup:function(E,C){if(!this.ids[C]){this.ids[C]={};}var D=this.ids[C];if(D&&D[E.id]){delete D[E.id];}},_remove:function(E){for(var D in E.groups){if(D){var C=this.ids[D];if(C&&C[E.id]){delete C[E.id];}}}delete this.handleIds[E.id];},regHandle:function(D,C){if(!this.handleIds[D]){this.handleIds[D]={};}this.handleIds[D][C]=C;},isDragDrop:function(C){return(this.getDDById(C))?true:false;},getRelated:function(H,D){var G=[];for(var F in H.groups){for(var E in this.ids[F]){var C=this.ids[F][E];if(!this.isTypeOfDD(C)){continue;}if(!D||C.isTarget){G[G.length]=C;}}}return G;},isLegalTarget:function(G,F){var D=this.getRelated(G,true);for(var E=0,C=D.length;E<C;++E){if(D[E].id==F.id){return true;}}return false;},isTypeOfDD:function(C){return(C&&C.__ygDragDrop);},isHandle:function(D,C){return(this.handleIds[D]&&this.handleIds[D][C]);},getDDById:function(D){for(var C in this.ids){if(this.ids[C][D]){return this.ids[C][D];}}return null;},handleMouseDown:function(E,D){this.currentTarget=YAHOO.util.Event.getTarget(E);this.dragCurrent=D;var C=D.getEl();this.startX=YAHOO.util.Event.getPageX(E);this.startY=YAHOO.util.Event.getPageY(E);this.deltaX=this.startX-C.offsetLeft;this.deltaY=this.startY-C.offsetTop;this.dragThreshMet=false;this.clickTimeout=setTimeout(function(){var F=YAHOO.util.DDM;F.startDrag(F.startX,F.startY);F.fromTimeout=true;},this.clickTimeThresh);},startDrag:function(C,E){if(this.dragCurrent&&this.dragCurrent.useShim){this._shimState=this.useShim;this.useShim=true;}this._activateShim();clearTimeout(this.clickTimeout);var D=this.dragCurrent;if(D&&D.events.b4StartDrag){D.b4StartDrag(C,E);D.fireEvent("b4StartDragEvent",{x:C,y:E});}if(D&&D.events.startDrag){D.startDrag(C,E);D.fireEvent("startDragEvent",{x:C,y:E});}this.dragThreshMet=true;},handleMouseUp:function(C){if(this.dragCurrent){clearTimeout(this.clickTimeout);if(this.dragThreshMet){if(this.fromTimeout){this.fromTimeout=false;this.handleMouseMove(C);}this.fromTimeout=false;this.fireEvents(C,true);}else{}this.stopDrag(C);this.stopEvent(C);}},stopEvent:function(C){if(this.stopPropagation){YAHOO.util.Event.stopPropagation(C);}if(this.preventDefault){YAHOO.util.Event.preventDefault(C);}},stopDrag:function(E,D){var C=this.dragCurrent;if(C&&!D){if(this.dragThreshMet){if(C.events.b4EndDrag){C.b4EndDrag(E);C.fireEvent("b4EndDragEvent",{e:E});}if(C.events.endDrag){C.endDrag(E);C.fireEvent("endDragEvent",{e:E});}}if(C.events.mouseUp){C.onMouseUp(E);C.fireEvent("mouseUpEvent",{e:E});}}if(this._shimActive){this._deactivateShim();if(this.dragCurrent&&this.dragCurrent.useShim){this.useShim=this._shimState;this._shimState=false;}}this.dragCurrent=null;this.dragOvers={};},handleMouseMove:function(F){var C=this.dragCurrent;if(C){if(YAHOO.util.Event.isIE&&!F.button){this.stopEvent(F);return this.handleMouseUp(F);}else{if(F.clientX<0||F.clientY<0){}}if(!this.dragThreshMet){var E=Math.abs(this.startX-YAHOO.util.Event.getPageX(F));var D=Math.abs(this.startY-YAHOO.util.Event.getPageY(F));if(E>this.clickPixelThresh||D>this.clickPixelThresh){this.startDrag(this.startX,this.startY);}}if(this.dragThreshMet){if(C&&C.events.b4Drag){C.b4Drag(F);C.fireEvent("b4DragEvent",{e:F});}if(C&&C.events.drag){C.onDrag(F);C.fireEvent("dragEvent",{e:F});}if(C){this.fireEvents(F,false);}}this.stopEvent(F);}},fireEvents:function(V,L){var a=this.dragCurrent;if(!a||a.isLocked()||a.dragOnly){return;}var N=YAHOO.util.Event.getPageX(V),M=YAHOO.util.Event.getPageY(V),P=new YAHOO.util.Point(N,M),K=a.getTargetCoord(P.x,P.y),F=a.getDragEl(),E=["out","over","drop","enter"],U=new YAHOO.util.Region(K.y,K.x+F.offsetWidth,K.y+F.offsetHeight,K.x),I=[],D={},Q=[],c={outEvts:[],overEvts:[],dropEvts:[],enterEvts:[]};for(var S in this.dragOvers){var d=this.dragOvers[S];if(!this.isTypeOfDD(d)){continue;
}if(!this.isOverTarget(P,d,this.mode,U)){c.outEvts.push(d);}I[S]=true;delete this.dragOvers[S];}for(var R in a.groups){if("string"!=typeof R){continue;}for(S in this.ids[R]){var G=this.ids[R][S];if(!this.isTypeOfDD(G)){continue;}if(G.isTarget&&!G.isLocked()&&G!=a){if(this.isOverTarget(P,G,this.mode,U)){D[R]=true;if(L){c.dropEvts.push(G);}else{if(!I[G.id]){c.enterEvts.push(G);}else{c.overEvts.push(G);}this.dragOvers[G.id]=G;}}}}}this.interactionInfo={out:c.outEvts,enter:c.enterEvts,over:c.overEvts,drop:c.dropEvts,point:P,draggedRegion:U,sourceRegion:this.locationCache[a.id],validDrop:L};for(var C in D){Q.push(C);}if(L&&!c.dropEvts.length){this.interactionInfo.validDrop=false;if(a.events.invalidDrop){a.onInvalidDrop(V);a.fireEvent("invalidDropEvent",{e:V});}}for(S=0;S<E.length;S++){var Y=null;if(c[E[S]+"Evts"]){Y=c[E[S]+"Evts"];}if(Y&&Y.length){var H=E[S].charAt(0).toUpperCase()+E[S].substr(1),X="onDrag"+H,J="b4Drag"+H,O="drag"+H+"Event",W="drag"+H;if(this.mode){if(a.events[J]){a[J](V,Y,Q);a.fireEvent(J+"Event",{event:V,info:Y,group:Q});}if(a.events[W]){a[X](V,Y,Q);a.fireEvent(O,{event:V,info:Y,group:Q});}}else{for(var Z=0,T=Y.length;Z<T;++Z){if(a.events[J]){a[J](V,Y[Z].id,Q[0]);a.fireEvent(J+"Event",{event:V,info:Y[Z].id,group:Q[0]});}if(a.events[W]){a[X](V,Y[Z].id,Q[0]);a.fireEvent(O,{event:V,info:Y[Z].id,group:Q[0]});}}}}}},getBestMatch:function(E){var G=null;var D=E.length;if(D==1){G=E[0];}else{for(var F=0;F<D;++F){var C=E[F];if(this.mode==this.INTERSECT&&C.cursorIsOver){G=C;break;}else{if(!G||!G.overlap||(C.overlap&&G.overlap.getArea()<C.overlap.getArea())){G=C;}}}}return G;},refreshCache:function(D){var F=D||this.ids;for(var C in F){if("string"!=typeof C){continue;}for(var E in this.ids[C]){var G=this.ids[C][E];if(this.isTypeOfDD(G)){var H=this.getLocation(G);if(H){this.locationCache[G.id]=H;}else{delete this.locationCache[G.id];}}}}},verifyEl:function(D){try{if(D){var C=D.offsetParent;if(C){return true;}}}catch(E){}return false;},getLocation:function(H){if(!this.isTypeOfDD(H)){return null;}var F=H.getEl(),K,E,D,M,L,N,C,J,G;try{K=YAHOO.util.Dom.getXY(F);}catch(I){}if(!K){return null;}E=K[0];D=E+F.offsetWidth;M=K[1];L=M+F.offsetHeight;N=M-H.padding[0];C=D+H.padding[1];J=L+H.padding[2];G=E-H.padding[3];return new YAHOO.util.Region(N,C,J,G);},isOverTarget:function(K,C,E,F){var G=this.locationCache[C.id];if(!G||!this.useCache){G=this.getLocation(C);this.locationCache[C.id]=G;}if(!G){return false;}C.cursorIsOver=G.contains(K);var J=this.dragCurrent;if(!J||(!E&&!J.constrainX&&!J.constrainY)){return C.cursorIsOver;}C.overlap=null;if(!F){var H=J.getTargetCoord(K.x,K.y);var D=J.getDragEl();F=new YAHOO.util.Region(H.y,H.x+D.offsetWidth,H.y+D.offsetHeight,H.x);}var I=F.intersect(G);if(I){C.overlap=I;return(E)?true:C.cursorIsOver;}else{return false;}},_onUnload:function(D,C){this.unregAll();},unregAll:function(){if(this.dragCurrent){this.stopDrag();this.dragCurrent=null;}this._execOnAll("unreg",[]);this.ids={};},elementCache:{},getElWrapper:function(D){var C=this.elementCache[D];if(!C||!C.el){C=this.elementCache[D]=new this.ElementWrapper(YAHOO.util.Dom.get(D));}return C;},getElement:function(C){return YAHOO.util.Dom.get(C);},getCss:function(D){var C=YAHOO.util.Dom.get(D);return(C)?C.style:null;},ElementWrapper:function(C){this.el=C||null;this.id=this.el&&C.id;this.css=this.el&&C.style;},getPosX:function(C){return YAHOO.util.Dom.getX(C);},getPosY:function(C){return YAHOO.util.Dom.getY(C);},swapNode:function(E,C){if(E.swapNode){E.swapNode(C);}else{var F=C.parentNode;var D=C.nextSibling;if(D==E){F.insertBefore(E,C);}else{if(C==E.nextSibling){F.insertBefore(C,E);}else{E.parentNode.replaceChild(C,E);F.insertBefore(E,D);}}}},getScroll:function(){var E,C,F=document.documentElement,D=document.body;if(F&&(F.scrollTop||F.scrollLeft)){E=F.scrollTop;C=F.scrollLeft;}else{if(D){E=D.scrollTop;C=D.scrollLeft;}else{}}return{top:E,left:C};},getStyle:function(D,C){return YAHOO.util.Dom.getStyle(D,C);},getScrollTop:function(){return this.getScroll().top;},getScrollLeft:function(){return this.getScroll().left;},moveToEl:function(C,E){var D=YAHOO.util.Dom.getXY(E);YAHOO.util.Dom.setXY(C,D);},getClientHeight:function(){return YAHOO.util.Dom.getViewportHeight();},getClientWidth:function(){return YAHOO.util.Dom.getViewportWidth();},numericSort:function(D,C){return(D-C);},_timeoutCount:0,_addListeners:function(){var C=YAHOO.util.DDM;if(YAHOO.util.Event&&document){C._onLoad();}else{if(C._timeoutCount>2000){}else{setTimeout(C._addListeners,10);if(document&&document.body){C._timeoutCount+=1;}}}},handleWasClicked:function(C,E){if(this.isHandle(E,C.id)){return true;}else{var D=C.parentNode;while(D){if(this.isHandle(E,D.id)){return true;}else{D=D.parentNode;}}}return false;}};}();YAHOO.util.DDM=YAHOO.util.DragDropMgr;YAHOO.util.DDM._addListeners();}(function(){var A=YAHOO.util.Event;var B=YAHOO.util.Dom;YAHOO.util.DragDrop=function(E,C,D){if(E){this.init(E,C,D);}};YAHOO.util.DragDrop.prototype={events:null,on:function(){this.subscribe.apply(this,arguments);},id:null,config:null,dragElId:null,handleElId:null,invalidHandleTypes:null,invalidHandleIds:null,invalidHandleClasses:null,startPageX:0,startPageY:0,groups:null,locked:false,lock:function(){this.locked=true;},unlock:function(){this.locked=false;},isTarget:true,padding:null,dragOnly:false,useShim:false,_domRef:null,__ygDragDrop:true,constrainX:false,constrainY:false,minX:0,maxX:0,minY:0,maxY:0,deltaX:0,deltaY:0,maintainOffset:false,xTicks:null,yTicks:null,primaryButtonOnly:true,available:false,hasOuterHandles:false,cursorIsOver:false,overlap:null,b4StartDrag:function(C,D){},startDrag:function(C,D){},b4Drag:function(C){},onDrag:function(C){},onDragEnter:function(C,D){},b4DragOver:function(C){},onDragOver:function(C,D){},b4DragOut:function(C){},onDragOut:function(C,D){},b4DragDrop:function(C){},onDragDrop:function(C,D){},onInvalidDrop:function(C){},b4EndDrag:function(C){},endDrag:function(C){},b4MouseDown:function(C){},onMouseDown:function(C){},onMouseUp:function(C){},onAvailable:function(){},getEl:function(){if(!this._domRef){this._domRef=B.get(this.id);
}return this._domRef;},getDragEl:function(){return B.get(this.dragElId);},init:function(F,C,D){this.initTarget(F,C,D);A.on(this._domRef||this.id,"mousedown",this.handleMouseDown,this,true);for(var E in this.events){this.createEvent(E+"Event");}},initTarget:function(E,C,D){this.config=D||{};this.events={};this.DDM=YAHOO.util.DDM;this.groups={};if(typeof E!=="string"){this._domRef=E;E=B.generateId(E);}this.id=E;this.addToGroup((C)?C:"default");this.handleElId=E;A.onAvailable(E,this.handleOnAvailable,this,true);this.setDragElId(E);this.invalidHandleTypes={A:"A"};this.invalidHandleIds={};this.invalidHandleClasses=[];this.applyConfig();},applyConfig:function(){this.events={mouseDown:true,b4MouseDown:true,mouseUp:true,b4StartDrag:true,startDrag:true,b4EndDrag:true,endDrag:true,drag:true,b4Drag:true,invalidDrop:true,b4DragOut:true,dragOut:true,dragEnter:true,b4DragOver:true,dragOver:true,b4DragDrop:true,dragDrop:true};if(this.config.events){for(var C in this.config.events){if(this.config.events[C]===false){this.events[C]=false;}}}this.padding=this.config.padding||[0,0,0,0];this.isTarget=(this.config.isTarget!==false);this.maintainOffset=(this.config.maintainOffset);this.primaryButtonOnly=(this.config.primaryButtonOnly!==false);this.dragOnly=((this.config.dragOnly===true)?true:false);this.useShim=((this.config.useShim===true)?true:false);},handleOnAvailable:function(){this.available=true;this.resetConstraints();this.onAvailable();},setPadding:function(E,C,F,D){if(!C&&0!==C){this.padding=[E,E,E,E];}else{if(!F&&0!==F){this.padding=[E,C,E,C];}else{this.padding=[E,C,F,D];}}},setInitPosition:function(F,E){var G=this.getEl();if(!this.DDM.verifyEl(G)){if(G&&G.style&&(G.style.display=="none")){}else{}return;}var D=F||0;var C=E||0;var H=B.getXY(G);this.initPageX=H[0]-D;this.initPageY=H[1]-C;this.lastPageX=H[0];this.lastPageY=H[1];this.setStartPosition(H);},setStartPosition:function(D){var C=D||B.getXY(this.getEl());this.deltaSetXY=null;this.startPageX=C[0];this.startPageY=C[1];},addToGroup:function(C){this.groups[C]=true;this.DDM.regDragDrop(this,C);},removeFromGroup:function(C){if(this.groups[C]){delete this.groups[C];}this.DDM.removeDDFromGroup(this,C);},setDragElId:function(C){this.dragElId=C;},setHandleElId:function(C){if(typeof C!=="string"){C=B.generateId(C);}this.handleElId=C;this.DDM.regHandle(this.id,C);},setOuterHandleElId:function(C){if(typeof C!=="string"){C=B.generateId(C);}A.on(C,"mousedown",this.handleMouseDown,this,true);this.setHandleElId(C);this.hasOuterHandles=true;},unreg:function(){A.removeListener(this.id,"mousedown",this.handleMouseDown);this._domRef=null;this.DDM._remove(this);},isLocked:function(){return(this.DDM.isLocked()||this.locked);},handleMouseDown:function(J,I){var D=J.which||J.button;if(this.primaryButtonOnly&&D>1){return;}if(this.isLocked()){return;}var C=this.b4MouseDown(J),F=true;if(this.events.b4MouseDown){F=this.fireEvent("b4MouseDownEvent",J);}var E=this.onMouseDown(J),H=true;if(this.events.mouseDown){H=this.fireEvent("mouseDownEvent",J);}if((C===false)||(E===false)||(F===false)||(H===false)){return;}this.DDM.refreshCache(this.groups);var G=new YAHOO.util.Point(A.getPageX(J),A.getPageY(J));if(!this.hasOuterHandles&&!this.DDM.isOverTarget(G,this)){}else{if(this.clickValidator(J)){this.setStartPosition();this.DDM.handleMouseDown(J,this);this.DDM.stopEvent(J);}else{}}},clickValidator:function(D){var C=YAHOO.util.Event.getTarget(D);return(this.isValidHandleChild(C)&&(this.id==this.handleElId||this.DDM.handleWasClicked(C,this.id)));},getTargetCoord:function(E,D){var C=E-this.deltaX;var F=D-this.deltaY;if(this.constrainX){if(C<this.minX){C=this.minX;}if(C>this.maxX){C=this.maxX;}}if(this.constrainY){if(F<this.minY){F=this.minY;}if(F>this.maxY){F=this.maxY;}}C=this.getTick(C,this.xTicks);F=this.getTick(F,this.yTicks);return{x:C,y:F};},addInvalidHandleType:function(C){var D=C.toUpperCase();this.invalidHandleTypes[D]=D;},addInvalidHandleId:function(C){if(typeof C!=="string"){C=B.generateId(C);}this.invalidHandleIds[C]=C;},addInvalidHandleClass:function(C){this.invalidHandleClasses.push(C);},removeInvalidHandleType:function(C){var D=C.toUpperCase();delete this.invalidHandleTypes[D];},removeInvalidHandleId:function(C){if(typeof C!=="string"){C=B.generateId(C);}delete this.invalidHandleIds[C];},removeInvalidHandleClass:function(D){for(var E=0,C=this.invalidHandleClasses.length;E<C;++E){if(this.invalidHandleClasses[E]==D){delete this.invalidHandleClasses[E];}}},isValidHandleChild:function(F){var E=true;var H;try{H=F.nodeName.toUpperCase();}catch(G){H=F.nodeName;}E=E&&!this.invalidHandleTypes[H];E=E&&!this.invalidHandleIds[F.id];for(var D=0,C=this.invalidHandleClasses.length;E&&D<C;++D){E=!B.hasClass(F,this.invalidHandleClasses[D]);}return E;},setXTicks:function(F,C){this.xTicks=[];this.xTickSize=C;var E={};for(var D=this.initPageX;D>=this.minX;D=D-C){if(!E[D]){this.xTicks[this.xTicks.length]=D;E[D]=true;}}for(D=this.initPageX;D<=this.maxX;D=D+C){if(!E[D]){this.xTicks[this.xTicks.length]=D;E[D]=true;}}this.xTicks.sort(this.DDM.numericSort);},setYTicks:function(F,C){this.yTicks=[];this.yTickSize=C;var E={};for(var D=this.initPageY;D>=this.minY;D=D-C){if(!E[D]){this.yTicks[this.yTicks.length]=D;E[D]=true;}}for(D=this.initPageY;D<=this.maxY;D=D+C){if(!E[D]){this.yTicks[this.yTicks.length]=D;E[D]=true;}}this.yTicks.sort(this.DDM.numericSort);},setXConstraint:function(E,D,C){this.leftConstraint=parseInt(E,10);this.rightConstraint=parseInt(D,10);this.minX=this.initPageX-this.leftConstraint;this.maxX=this.initPageX+this.rightConstraint;if(C){this.setXTicks(this.initPageX,C);}this.constrainX=true;},clearConstraints:function(){this.constrainX=false;this.constrainY=false;this.clearTicks();},clearTicks:function(){this.xTicks=null;this.yTicks=null;this.xTickSize=0;this.yTickSize=0;},setYConstraint:function(C,E,D){this.topConstraint=parseInt(C,10);this.bottomConstraint=parseInt(E,10);this.minY=this.initPageY-this.topConstraint;this.maxY=this.initPageY+this.bottomConstraint;if(D){this.setYTicks(this.initPageY,D);
}this.constrainY=true;},resetConstraints:function(){if(this.initPageX||this.initPageX===0){var D=(this.maintainOffset)?this.lastPageX-this.initPageX:0;var C=(this.maintainOffset)?this.lastPageY-this.initPageY:0;this.setInitPosition(D,C);}else{this.setInitPosition();}if(this.constrainX){this.setXConstraint(this.leftConstraint,this.rightConstraint,this.xTickSize);}if(this.constrainY){this.setYConstraint(this.topConstraint,this.bottomConstraint,this.yTickSize);}},getTick:function(I,F){if(!F){return I;}else{if(F[0]>=I){return F[0];}else{for(var D=0,C=F.length;D<C;++D){var E=D+1;if(F[E]&&F[E]>=I){var H=I-F[D];var G=F[E]-I;return(G>H)?F[D]:F[E];}}return F[F.length-1];}}},toString:function(){return("DragDrop "+this.id);}};YAHOO.augment(YAHOO.util.DragDrop,YAHOO.util.EventProvider);})();YAHOO.util.DD=function(C,A,B){if(C){this.init(C,A,B);}};YAHOO.extend(YAHOO.util.DD,YAHOO.util.DragDrop,{scroll:true,autoOffset:function(C,B){var A=C-this.startPageX;var D=B-this.startPageY;this.setDelta(A,D);},setDelta:function(B,A){this.deltaX=B;this.deltaY=A;},setDragElPos:function(C,B){var A=this.getDragEl();this.alignElWithMouse(A,C,B);},alignElWithMouse:function(C,G,F){var E=this.getTargetCoord(G,F);if(!this.deltaSetXY){var H=[E.x,E.y];YAHOO.util.Dom.setXY(C,H);var D=parseInt(YAHOO.util.Dom.getStyle(C,"left"),10);var B=parseInt(YAHOO.util.Dom.getStyle(C,"top"),10);this.deltaSetXY=[D-E.x,B-E.y];}else{YAHOO.util.Dom.setStyle(C,"left",(E.x+this.deltaSetXY[0])+"px");YAHOO.util.Dom.setStyle(C,"top",(E.y+this.deltaSetXY[1])+"px");}this.cachePosition(E.x,E.y);var A=this;setTimeout(function(){A.autoScroll.call(A,E.x,E.y,C.offsetHeight,C.offsetWidth);},0);},cachePosition:function(B,A){if(B){this.lastPageX=B;this.lastPageY=A;}else{var C=YAHOO.util.Dom.getXY(this.getEl());this.lastPageX=C[0];this.lastPageY=C[1];}},autoScroll:function(J,I,E,K){if(this.scroll){var L=this.DDM.getClientHeight();var B=this.DDM.getClientWidth();var N=this.DDM.getScrollTop();var D=this.DDM.getScrollLeft();var H=E+I;var M=K+J;var G=(L+N-I-this.deltaY);var F=(B+D-J-this.deltaX);var C=40;var A=(document.all)?80:30;if(H>L&&G<C){window.scrollTo(D,N+A);}if(I<N&&N>0&&I-N<C){window.scrollTo(D,N-A);}if(M>B&&F<C){window.scrollTo(D+A,N);}if(J<D&&D>0&&J-D<C){window.scrollTo(D-A,N);}}},applyConfig:function(){YAHOO.util.DD.superclass.applyConfig.call(this);this.scroll=(this.config.scroll!==false);},b4MouseDown:function(A){this.setStartPosition();this.autoOffset(YAHOO.util.Event.getPageX(A),YAHOO.util.Event.getPageY(A));},b4Drag:function(A){this.setDragElPos(YAHOO.util.Event.getPageX(A),YAHOO.util.Event.getPageY(A));},toString:function(){return("DD "+this.id);}});YAHOO.util.DDProxy=function(C,A,B){if(C){this.init(C,A,B);this.initFrame();}};YAHOO.util.DDProxy.dragElId="ygddfdiv";YAHOO.extend(YAHOO.util.DDProxy,YAHOO.util.DD,{resizeFrame:true,centerFrame:false,createFrame:function(){var B=this,A=document.body;if(!A||!A.firstChild){setTimeout(function(){B.createFrame();},50);return;}var F=this.getDragEl(),E=YAHOO.util.Dom;if(!F){F=document.createElement("div");F.id=this.dragElId;var D=F.style;D.position="absolute";D.visibility="hidden";D.cursor="move";D.border="2px solid #aaa";D.zIndex=999;D.height="25px";D.width="25px";var C=document.createElement("div");E.setStyle(C,"height","100%");E.setStyle(C,"width","100%");E.setStyle(C,"background-color","#ccc");E.setStyle(C,"opacity","0");F.appendChild(C);A.insertBefore(F,A.firstChild);}},initFrame:function(){this.createFrame();},applyConfig:function(){YAHOO.util.DDProxy.superclass.applyConfig.call(this);this.resizeFrame=(this.config.resizeFrame!==false);this.centerFrame=(this.config.centerFrame);this.setDragElId(this.config.dragElId||YAHOO.util.DDProxy.dragElId);},showFrame:function(E,D){var C=this.getEl();var A=this.getDragEl();var B=A.style;this._resizeProxy();if(this.centerFrame){this.setDelta(Math.round(parseInt(B.width,10)/2),Math.round(parseInt(B.height,10)/2));}this.setDragElPos(E,D);YAHOO.util.Dom.setStyle(A,"visibility","visible");},_resizeProxy:function(){if(this.resizeFrame){var H=YAHOO.util.Dom;var B=this.getEl();var C=this.getDragEl();var G=parseInt(H.getStyle(C,"borderTopWidth"),10);var I=parseInt(H.getStyle(C,"borderRightWidth"),10);var F=parseInt(H.getStyle(C,"borderBottomWidth"),10);var D=parseInt(H.getStyle(C,"borderLeftWidth"),10);if(isNaN(G)){G=0;}if(isNaN(I)){I=0;}if(isNaN(F)){F=0;}if(isNaN(D)){D=0;}var E=Math.max(0,B.offsetWidth-I-D);var A=Math.max(0,B.offsetHeight-G-F);H.setStyle(C,"width",E+"px");H.setStyle(C,"height",A+"px");}},b4MouseDown:function(B){this.setStartPosition();var A=YAHOO.util.Event.getPageX(B);var C=YAHOO.util.Event.getPageY(B);this.autoOffset(A,C);},b4StartDrag:function(A,B){this.showFrame(A,B);},b4EndDrag:function(A){YAHOO.util.Dom.setStyle(this.getDragEl(),"visibility","hidden");},endDrag:function(D){var C=YAHOO.util.Dom;var B=this.getEl();var A=this.getDragEl();C.setStyle(A,"visibility","");C.setStyle(B,"visibility","hidden");YAHOO.util.DDM.moveToEl(B,A);C.setStyle(A,"visibility","hidden");C.setStyle(B,"visibility","");},toString:function(){return("DDProxy "+this.id);}});YAHOO.util.DDTarget=function(C,A,B){if(C){this.initTarget(C,A,B);}};YAHOO.extend(YAHOO.util.DDTarget,YAHOO.util.DragDrop,{toString:function(){return("DDTarget "+this.id);}});YAHOO.register("dragdrop",YAHOO.util.DragDropMgr,{version:"2.7.0",build:"1799"});/*
Copyright (c) 2009, Yahoo! Inc. All rights reserved.
Code licensed under the BSD License:
http://developer.yahoo.net/yui/license.txt
version: 2.7.0
*/
YAHOO.util.Attribute=function(B,A){if(A){this.owner=A;this.configure(B,true);}};YAHOO.util.Attribute.prototype={name:undefined,value:null,owner:null,readOnly:false,writeOnce:false,_initialConfig:null,_written:false,method:null,setter:null,getter:null,validator:null,getValue:function(){var A=this.value;if(this.getter){A=this.getter.call(this.owner,this.name);}return A;},setValue:function(F,B){var E,A=this.owner,C=this.name;var D={type:C,prevValue:this.getValue(),newValue:F};if(this.readOnly||(this.writeOnce&&this._written)){return false;}if(this.validator&&!this.validator.call(A,F)){return false;}if(!B){E=A.fireBeforeChangeEvent(D);if(E===false){return false;}}if(this.setter){F=this.setter.call(A,F,this.name);if(F===undefined){}}if(this.method){this.method.call(A,F,this.name);}this.value=F;this._written=true;D.type=C;if(!B){this.owner.fireChangeEvent(D);}return true;},configure:function(B,C){B=B||{};if(C){this._written=false;}this._initialConfig=this._initialConfig||{};for(var A in B){if(B.hasOwnProperty(A)){this[A]=B[A];if(C){this._initialConfig[A]=B[A];}}}},resetValue:function(){return this.setValue(this._initialConfig.value);},resetConfig:function(){this.configure(this._initialConfig,true);},refresh:function(A){this.setValue(this.value,A);}};(function(){var A=YAHOO.util.Lang;YAHOO.util.AttributeProvider=function(){};YAHOO.util.AttributeProvider.prototype={_configs:null,get:function(C){this._configs=this._configs||{};var B=this._configs[C];if(!B||!this._configs.hasOwnProperty(C)){return null;}return B.getValue();},set:function(D,E,B){this._configs=this._configs||{};var C=this._configs[D];if(!C){return false;}return C.setValue(E,B);},getAttributeKeys:function(){this._configs=this._configs;var C=[],B;for(B in this._configs){if(A.hasOwnProperty(this._configs,B)&&!A.isUndefined(this._configs[B])){C[C.length]=B;}}return C;},setAttributes:function(D,B){for(var C in D){if(A.hasOwnProperty(D,C)){this.set(C,D[C],B);}}},resetValue:function(C,B){this._configs=this._configs||{};if(this._configs[C]){this.set(C,this._configs[C]._initialConfig.value,B);return true;}return false;},refresh:function(E,C){this._configs=this._configs||{};var F=this._configs;E=((A.isString(E))?[E]:E)||this.getAttributeKeys();for(var D=0,B=E.length;D<B;++D){if(F.hasOwnProperty(E[D])){this._configs[E[D]].refresh(C);}}},register:function(B,C){this.setAttributeConfig(B,C);},getAttributeConfig:function(C){this._configs=this._configs||{};var B=this._configs[C]||{};var D={};for(C in B){if(A.hasOwnProperty(B,C)){D[C]=B[C];}}return D;},setAttributeConfig:function(B,C,D){this._configs=this._configs||{};C=C||{};if(!this._configs[B]){C.name=B;this._configs[B]=this.createAttribute(C);}else{this._configs[B].configure(C,D);}},configureAttribute:function(B,C,D){this.setAttributeConfig(B,C,D);},resetAttributeConfig:function(B){this._configs=this._configs||{};this._configs[B].resetConfig();},subscribe:function(B,C){this._events=this._events||{};if(!(B in this._events)){this._events[B]=this.createEvent(B);}YAHOO.util.EventProvider.prototype.subscribe.apply(this,arguments);},on:function(){this.subscribe.apply(this,arguments);},addListener:function(){this.subscribe.apply(this,arguments);},fireBeforeChangeEvent:function(C){var B="before";B+=C.type.charAt(0).toUpperCase()+C.type.substr(1)+"Change";C.type=B;return this.fireEvent(C.type,C);},fireChangeEvent:function(B){B.type+="Change";return this.fireEvent(B.type,B);},createAttribute:function(B){return new YAHOO.util.Attribute(B,this);}};YAHOO.augment(YAHOO.util.AttributeProvider,YAHOO.util.EventProvider);})();(function(){var B=YAHOO.util.Dom,C=YAHOO.util.AttributeProvider;var A=function(D,E){this.init.apply(this,arguments);};A.DOM_EVENTS={"click":true,"dblclick":true,"keydown":true,"keypress":true,"keyup":true,"mousedown":true,"mousemove":true,"mouseout":true,"mouseover":true,"mouseup":true,"focus":true,"blur":true,"submit":true,"change":true};A.prototype={DOM_EVENTS:null,DEFAULT_HTML_SETTER:function(F,D){var E=this.get("element");if(E){E[D]=F;}},DEFAULT_HTML_GETTER:function(D){var E=this.get("element"),F;if(E){F=E[D];}return F;},appendChild:function(D){D=D.get?D.get("element"):D;return this.get("element").appendChild(D);},getElementsByTagName:function(D){return this.get("element").getElementsByTagName(D);},hasChildNodes:function(){return this.get("element").hasChildNodes();},insertBefore:function(D,E){D=D.get?D.get("element"):D;E=(E&&E.get)?E.get("element"):E;return this.get("element").insertBefore(D,E);},removeChild:function(D){D=D.get?D.get("element"):D;return this.get("element").removeChild(D);},replaceChild:function(D,E){D=D.get?D.get("element"):D;E=E.get?E.get("element"):E;return this.get("element").replaceChild(D,E);},initAttributes:function(D){},addListener:function(H,G,I,F){var E=this.get("element")||this.get("id");F=F||this;var D=this;if(!this._events[H]){if(E&&this.DOM_EVENTS[H]){YAHOO.util.Event.addListener(E,H,function(J){if(J.srcElement&&!J.target){J.target=J.srcElement;}D.fireEvent(H,J);},I,F);}this.createEvent(H,this);}return YAHOO.util.EventProvider.prototype.subscribe.apply(this,arguments);},on:function(){return this.addListener.apply(this,arguments);},subscribe:function(){return this.addListener.apply(this,arguments);},removeListener:function(E,D){return this.unsubscribe.apply(this,arguments);},addClass:function(D){B.addClass(this.get("element"),D);},getElementsByClassName:function(E,D){return B.getElementsByClassName(E,D,this.get("element"));},hasClass:function(D){return B.hasClass(this.get("element"),D);},removeClass:function(D){return B.removeClass(this.get("element"),D);},replaceClass:function(E,D){return B.replaceClass(this.get("element"),E,D);},setStyle:function(E,D){return B.setStyle(this.get("element"),E,D);},getStyle:function(D){return B.getStyle(this.get("element"),D);},fireQueue:function(){var E=this._queue;for(var F=0,D=E.length;F<D;++F){this[E[F][0]].apply(this,E[F][1]);}},appendTo:function(E,F){E=(E.get)?E.get("element"):B.get(E);this.fireEvent("beforeAppendTo",{type:"beforeAppendTo",target:E});
F=(F&&F.get)?F.get("element"):B.get(F);var D=this.get("element");if(!D){return false;}if(!E){return false;}if(D.parent!=E){if(F){E.insertBefore(D,F);}else{E.appendChild(D);}}this.fireEvent("appendTo",{type:"appendTo",target:E});return D;},get:function(D){var F=this._configs||{},E=F.element;if(E&&!F[D]&&!YAHOO.lang.isUndefined(E.value[D])){this._setHTMLAttrConfig(D);}return C.prototype.get.call(this,D);},setAttributes:function(J,G){var E={},H=this._configOrder;for(var I=0,D=H.length;I<D;++I){if(J[H[I]]!==undefined){E[H[I]]=true;this.set(H[I],J[H[I]],G);}}for(var F in J){if(J.hasOwnProperty(F)&&!E[F]){this.set(F,J[F],G);}}},set:function(E,G,D){var F=this.get("element");if(!F){this._queue[this._queue.length]=["set",arguments];if(this._configs[E]){this._configs[E].value=G;}return;}if(!this._configs[E]&&!YAHOO.lang.isUndefined(F[E])){this._setHTMLAttrConfig(E);}return C.prototype.set.apply(this,arguments);},setAttributeConfig:function(D,E,F){this._configOrder.push(D);C.prototype.setAttributeConfig.apply(this,arguments);},createEvent:function(E,D){this._events[E]=true;return C.prototype.createEvent.apply(this,arguments);},init:function(E,D){this._initElement(E,D);},destroy:function(){var D=this.get("element");YAHOO.util.Event.purgeElement(D,true);this.unsubscribeAll();if(D&&D.parentNode){D.parentNode.removeChild(D);}this._queue=[];this._events={};this._configs={};this._configOrder=[];},_initElement:function(F,E){this._queue=this._queue||[];this._events=this._events||{};this._configs=this._configs||{};this._configOrder=[];E=E||{};E.element=E.element||F||null;var H=false;var D=A.DOM_EVENTS;this.DOM_EVENTS=this.DOM_EVENTS||{};for(var G in D){if(D.hasOwnProperty(G)){this.DOM_EVENTS[G]=D[G];}}if(typeof E.element==="string"){this._setHTMLAttrConfig("id",{value:E.element});}if(B.get(E.element)){H=true;this._initHTMLElement(E);this._initContent(E);}YAHOO.util.Event.onAvailable(E.element,function(){if(!H){this._initHTMLElement(E);}this.fireEvent("available",{type:"available",target:B.get(E.element)});},this,true);YAHOO.util.Event.onContentReady(E.element,function(){if(!H){this._initContent(E);}this.fireEvent("contentReady",{type:"contentReady",target:B.get(E.element)});},this,true);},_initHTMLElement:function(D){this.setAttributeConfig("element",{value:B.get(D.element),readOnly:true});},_initContent:function(D){this.initAttributes(D);this.setAttributes(D,true);this.fireQueue();},_setHTMLAttrConfig:function(D,F){var E=this.get("element");F=F||{};F.name=D;F.setter=F.setter||this.DEFAULT_HTML_SETTER;F.getter=F.getter||this.DEFAULT_HTML_GETTER;F.value=F.value||E[D];this._configs[D]=new YAHOO.util.Attribute(F,this);}};YAHOO.augment(A,C);YAHOO.util.Element=A;})();YAHOO.register("element",YAHOO.util.Element,{version:"2.7.0",build:"1799"});/*
Copyright (c) 2009, Yahoo! Inc. All rights reserved.
Code licensed under the BSD License:
http://developer.yahoo.net/yui/license.txt
version: 2.7.0
*/
(function(){var E=YAHOO.util.Dom,A=YAHOO.util.Event,C=YAHOO.lang;var B=function(F,D){var G={element:F,attributes:D||{}};B.superclass.constructor.call(this,G.element,G.attributes);};B._instances={};B.getResizeById=function(D){if(B._instances[D]){return B._instances[D];}return false;};YAHOO.extend(B,YAHOO.util.Element,{CSS_RESIZE:"yui-resize",CSS_DRAG:"yui-draggable",CSS_HOVER:"yui-resize-hover",CSS_PROXY:"yui-resize-proxy",CSS_WRAP:"yui-resize-wrap",CSS_KNOB:"yui-resize-knob",CSS_HIDDEN:"yui-resize-hidden",CSS_HANDLE:"yui-resize-handle",CSS_STATUS:"yui-resize-status",CSS_GHOST:"yui-resize-ghost",CSS_RESIZING:"yui-resize-resizing",_resizeEvent:null,dd:null,browser:YAHOO.env.ua,_locked:null,_positioned:null,_dds:null,_wrap:null,_proxy:null,_handles:null,_currentHandle:null,_currentDD:null,_cache:null,_active:null,_createProxy:function(){if(this.get("proxy")){this._proxy=document.createElement("div");this._proxy.className=this.CSS_PROXY;this._proxy.style.height=this.get("element").clientHeight+"px";this._proxy.style.width=this.get("element").clientWidth+"px";this._wrap.parentNode.appendChild(this._proxy);}else{this.set("animate",false);}},_createWrap:function(){this._positioned=false;if(this.get("wrap")===false){switch(this.get("element").tagName.toLowerCase()){case"img":case"textarea":case"input":case"iframe":case"select":this.set("wrap",true);break;}}if(this.get("wrap")===true){this._wrap=document.createElement("div");this._wrap.id=this.get("element").id+"_wrap";this._wrap.className=this.CSS_WRAP;if(this.get("element").tagName.toLowerCase()=="textarea"){E.addClass(this._wrap,"yui-resize-textarea");}E.setStyle(this._wrap,"width",this.get("width")+"px");E.setStyle(this._wrap,"height",this.get("height")+"px");E.setStyle(this._wrap,"z-index",this.getStyle("z-index"));this.setStyle("z-index",0);var F=E.getStyle(this.get("element"),"position");E.setStyle(this._wrap,"position",((F=="static")?"relative":F));E.setStyle(this._wrap,"top",E.getStyle(this.get("element"),"top"));E.setStyle(this._wrap,"left",E.getStyle(this.get("element"),"left"));if(E.getStyle(this.get("element"),"position")=="absolute"){this._positioned=true;E.setStyle(this.get("element"),"position","relative");E.setStyle(this.get("element"),"top","0");E.setStyle(this.get("element"),"left","0");}var D=this.get("element").parentNode;D.replaceChild(this._wrap,this.get("element"));this._wrap.appendChild(this.get("element"));}else{this._wrap=this.get("element");if(E.getStyle(this._wrap,"position")=="absolute"){this._positioned=true;}}if(this.get("draggable")){this._setupDragDrop();}if(this.get("hover")){E.addClass(this._wrap,this.CSS_HOVER);}if(this.get("knobHandles")){E.addClass(this._wrap,this.CSS_KNOB);}if(this.get("hiddenHandles")){E.addClass(this._wrap,this.CSS_HIDDEN);}E.addClass(this._wrap,this.CSS_RESIZE);},_setupDragDrop:function(){E.addClass(this._wrap,this.CSS_DRAG);this.dd=new YAHOO.util.DD(this._wrap,this.get("id")+"-resize",{dragOnly:true,useShim:this.get("useShim")});this.dd.on("dragEvent",function(){this.fireEvent("dragEvent",arguments);},this,true);},_createHandles:function(){this._handles={};this._dds={};var G=this.get("handles");for(var F=0;F<G.length;F++){this._handles[G[F]]=document.createElement("div");this._handles[G[F]].id=E.generateId(this._handles[G[F]]);this._handles[G[F]].className=this.CSS_HANDLE+" "+this.CSS_HANDLE+"-"+G[F];var D=document.createElement("div");D.className=this.CSS_HANDLE+"-inner-"+G[F];this._handles[G[F]].appendChild(D);this._wrap.appendChild(this._handles[G[F]]);A.on(this._handles[G[F]],"mouseover",this._handleMouseOver,this,true);A.on(this._handles[G[F]],"mouseout",this._handleMouseOut,this,true);this._dds[G[F]]=new YAHOO.util.DragDrop(this._handles[G[F]],this.get("id")+"-handle-"+G,{useShim:this.get("useShim")});this._dds[G[F]].setPadding(15,15,15,15);this._dds[G[F]].on("startDragEvent",this._handleStartDrag,this._dds[G[F]],this);this._dds[G[F]].on("mouseDownEvent",this._handleMouseDown,this._dds[G[F]],this);}this._status=document.createElement("span");this._status.className=this.CSS_STATUS;document.body.insertBefore(this._status,document.body.firstChild);},_ieSelectFix:function(){return false;},_ieSelectBack:null,_setAutoRatio:function(D){if(this.get("autoRatio")){if(D&&D.shiftKey){this.set("ratio",true);}else{this.set("ratio",this._configs.ratio._initialConfig.value);}}},_handleMouseDown:function(D){if(this._locked){return false;}if(E.getStyle(this._wrap,"position")=="absolute"){this._positioned=true;}if(D){this._setAutoRatio(D);}if(this.browser.ie){this._ieSelectBack=document.body.onselectstart;document.body.onselectstart=this._ieSelectFix;}},_handleMouseOver:function(G){if(this._locked){return false;}E.removeClass(this._wrap,this.CSS_RESIZE);if(this.get("hover")){E.removeClass(this._wrap,this.CSS_HOVER);}var D=A.getTarget(G);if(!E.hasClass(D,this.CSS_HANDLE)){D=D.parentNode;}if(E.hasClass(D,this.CSS_HANDLE)&&!this._active){E.addClass(D,this.CSS_HANDLE+"-active");for(var F in this._handles){if(C.hasOwnProperty(this._handles,F)){if(this._handles[F]==D){E.addClass(D,this.CSS_HANDLE+"-"+F+"-active");break;}}}}E.addClass(this._wrap,this.CSS_RESIZE);},_handleMouseOut:function(G){E.removeClass(this._wrap,this.CSS_RESIZE);if(this.get("hover")&&!this._active){E.addClass(this._wrap,this.CSS_HOVER);}var D=A.getTarget(G);if(!E.hasClass(D,this.CSS_HANDLE)){D=D.parentNode;}if(E.hasClass(D,this.CSS_HANDLE)&&!this._active){E.removeClass(D,this.CSS_HANDLE+"-active");for(var F in this._handles){if(C.hasOwnProperty(this._handles,F)){if(this._handles[F]==D){E.removeClass(D,this.CSS_HANDLE+"-"+F+"-active");break;}}}}E.addClass(this._wrap,this.CSS_RESIZE);},_handleStartDrag:function(G,F){var D=F.getDragEl();if(E.hasClass(D,this.CSS_HANDLE)){if(E.getStyle(this._wrap,"position")=="absolute"){this._positioned=true;}this._active=true;this._currentDD=F;if(this._proxy){this._proxy.style.visibility="visible";this._proxy.style.zIndex="1000";this._proxy.style.height=this.get("element").clientHeight+"px";this._proxy.style.width=this.get("element").clientWidth+"px";
}for(var H in this._handles){if(C.hasOwnProperty(this._handles,H)){if(this._handles[H]==D){this._currentHandle=H;var I="_handle_for_"+H;E.addClass(D,this.CSS_HANDLE+"-"+H+"-active");F.on("dragEvent",this[I],this,true);F.on("mouseUpEvent",this._handleMouseUp,this,true);break;}}}E.addClass(D,this.CSS_HANDLE+"-active");if(this.get("proxy")){var J=E.getXY(this.get("element"));E.setXY(this._proxy,J);if(this.get("ghost")){this.addClass(this.CSS_GHOST);}}E.addClass(this._wrap,this.CSS_RESIZING);this._setCache();this._updateStatus(this._cache.height,this._cache.width,this._cache.top,this._cache.left);this.fireEvent("startResize",{type:"startresize",target:this});}},_setCache:function(){this._cache.xy=E.getXY(this._wrap);E.setXY(this._wrap,this._cache.xy);this._cache.height=this.get("clientHeight");this._cache.width=this.get("clientWidth");this._cache.start.height=this._cache.height;this._cache.start.width=this._cache.width;this._cache.start.top=this._cache.xy[1];this._cache.start.left=this._cache.xy[0];this._cache.top=this._cache.xy[1];this._cache.left=this._cache.xy[0];this.set("height",this._cache.height,true);this.set("width",this._cache.width,true);},_handleMouseUp:function(F){this._active=false;var G="_handle_for_"+this._currentHandle;this._currentDD.unsubscribe("dragEvent",this[G],this,true);this._currentDD.unsubscribe("mouseUpEvent",this._handleMouseUp,this,true);if(this._proxy){this._proxy.style.visibility="hidden";this._proxy.style.zIndex="-1";if(this.get("setSize")){this.resize(F,this._cache.height,this._cache.width,this._cache.top,this._cache.left,true);}else{this.fireEvent("resize",{ev:"resize",target:this,height:this._cache.height,width:this._cache.width,top:this._cache.top,left:this._cache.left});}if(this.get("ghost")){this.removeClass(this.CSS_GHOST);}}if(this.get("hover")){E.addClass(this._wrap,this.CSS_HOVER);}if(this._status){E.setStyle(this._status,"display","none");}if(this.browser.ie){document.body.onselectstart=this._ieSelectBack;}if(this.browser.ie){E.removeClass(this._wrap,this.CSS_RESIZE);}for(var D in this._handles){if(C.hasOwnProperty(this._handles,D)){E.removeClass(this._handles[D],this.CSS_HANDLE+"-active");}}if(this.get("hover")&&!this._active){E.addClass(this._wrap,this.CSS_HOVER);}E.removeClass(this._wrap,this.CSS_RESIZING);E.removeClass(this._handles[this._currentHandle],this.CSS_HANDLE+"-"+this._currentHandle+"-active");E.removeClass(this._handles[this._currentHandle],this.CSS_HANDLE+"-active");if(this.browser.ie){E.addClass(this._wrap,this.CSS_RESIZE);}this._resizeEvent=null;this._currentHandle=null;if(!this.get("animate")){this.set("height",this._cache.height,true);this.set("width",this._cache.width,true);}this.fireEvent("endResize",{ev:"endResize",target:this,height:this._cache.height,width:this._cache.width,top:this._cache.top,left:this._cache.left});},_setRatio:function(K,N,Q,I){var O=K,G=N;if(this.get("ratio")){var P=this._cache.height,H=this._cache.width,F=parseInt(this.get("height"),10),L=parseInt(this.get("width"),10),M=this.get("maxHeight"),R=this.get("minHeight"),D=this.get("maxWidth"),J=this.get("minWidth");switch(this._currentHandle){case"l":K=F*(N/L);K=Math.min(Math.max(R,K),M);N=L*(K/F);Q=(this._cache.start.top-(-((F-K)/2)));I=(this._cache.start.left-(-((L-N))));break;case"r":K=F*(N/L);K=Math.min(Math.max(R,K),M);N=L*(K/F);Q=(this._cache.start.top-(-((F-K)/2)));break;case"t":N=L*(K/F);K=F*(N/L);I=(this._cache.start.left-(-((L-N)/2)));Q=(this._cache.start.top-(-((F-K))));break;case"b":N=L*(K/F);K=F*(N/L);I=(this._cache.start.left-(-((L-N)/2)));break;case"bl":K=F*(N/L);N=L*(K/F);I=(this._cache.start.left-(-((L-N))));break;case"br":K=F*(N/L);N=L*(K/F);break;case"tl":K=F*(N/L);N=L*(K/F);I=(this._cache.start.left-(-((L-N))));Q=(this._cache.start.top-(-((F-K))));break;case"tr":K=F*(N/L);N=L*(K/F);I=(this._cache.start.left);Q=(this._cache.start.top-(-((F-K))));break;}O=this._checkHeight(K);G=this._checkWidth(N);if((O!=K)||(G!=N)){Q=0;I=0;if(O!=K){G=this._cache.width;}if(G!=N){O=this._cache.height;}}}return[O,G,Q,I];},_updateStatus:function(K,G,J,F){if(this._resizeEvent&&(!C.isString(this._resizeEvent))){K=((K===0)?this._cache.start.height:K);G=((G===0)?this._cache.start.width:G);var I=parseInt(this.get("height"),10),D=parseInt(this.get("width"),10);if(isNaN(I)){I=parseInt(K,10);}if(isNaN(D)){D=parseInt(G,10);}var L=(parseInt(K,10)-I);var H=(parseInt(G,10)-D);this._cache.offsetHeight=L;this._cache.offsetWidth=H;if(this.get("status")){E.setStyle(this._status,"display","inline");this._status.innerHTML="<strong>"+parseInt(K,10)+" x "+parseInt(G,10)+"</strong><em>"+((L>0)?"+":"")+L+" x "+((H>0)?"+":"")+H+"</em>";E.setXY(this._status,[A.getPageX(this._resizeEvent)+12,A.getPageY(this._resizeEvent)+12]);}}},lock:function(D){this._locked=true;if(D&&this.dd){E.removeClass(this._wrap,"yui-draggable");this.dd.lock();}return this;},unlock:function(D){this._locked=false;if(D&&this.dd){E.addClass(this._wrap,"yui-draggable");this.dd.unlock();}return this;},isLocked:function(){return this._locked;},reset:function(){this.resize(null,this._cache.start.height,this._cache.start.width,this._cache.start.top,this._cache.start.left,true);return this;},resize:function(M,J,P,Q,H,F,K){if(this._locked){return false;}this._resizeEvent=M;var G=this._wrap,I=this.get("animate"),O=true;if(this._proxy&&!F){G=this._proxy;I=false;}this._setAutoRatio(M);if(this._positioned){if(this._proxy){Q=this._cache.top-Q;H=this._cache.left-H;}}var L=this._setRatio(J,P,Q,H);J=parseInt(L[0],10);P=parseInt(L[1],10);Q=parseInt(L[2],10);H=parseInt(L[3],10);if(Q==0){Q=E.getY(G);}if(H==0){H=E.getX(G);}if(this._positioned){if(this._proxy&&F){if(!I){G.style.top=this._proxy.style.top;G.style.left=this._proxy.style.left;}else{Q=this._proxy.style.top;H=this._proxy.style.left;}}else{if(!this.get("ratio")&&!this._proxy){Q=this._cache.top+-(Q);H=this._cache.left+-(H);}if(Q){if(this.get("minY")){if(Q<this.get("minY")){Q=this.get("minY");}}if(this.get("maxY")){if(Q>this.get("maxY")){Q=this.get("maxY");}}}if(H){if(this.get("minX")){if(H<this.get("minX")){H=this.get("minX");
}}if(this.get("maxX")){if((H+P)>this.get("maxX")){H=(this.get("maxX")-P);}}}}}if(!K){var N=this.fireEvent("beforeResize",{ev:"beforeResize",target:this,height:J,width:P,top:Q,left:H});if(N===false){return false;}}this._updateStatus(J,P,Q,H);if(this._positioned){if(this._proxy&&F){}else{if(Q){E.setY(G,Q);this._cache.top=Q;}if(H){E.setX(G,H);this._cache.left=H;}}}if(J){if(!I){O=true;if(this._proxy&&F){if(!this.get("setSize")){O=false;}}if(O){G.style.height=J+"px";}if((this._proxy&&F)||!this._proxy){if(this._wrap!=this.get("element")){this.get("element").style.height=J+"px";}}}this._cache.height=J;}if(P){this._cache.width=P;if(!I){O=true;if(this._proxy&&F){if(!this.get("setSize")){O=false;}}if(O){G.style.width=P+"px";}if((this._proxy&&F)||!this._proxy){if(this._wrap!=this.get("element")){this.get("element").style.width=P+"px";}}}}if(I){if(YAHOO.util.Anim){var D=new YAHOO.util.Anim(G,{height:{to:this._cache.height},width:{to:this._cache.width}},this.get("animateDuration"),this.get("animateEasing"));if(this._positioned){if(Q){D.attributes.top={to:parseInt(Q,10)};}if(H){D.attributes.left={to:parseInt(H,10)};}}if(this._wrap!=this.get("element")){D.onTween.subscribe(function(){this.get("element").style.height=G.style.height;this.get("element").style.width=G.style.width;},this,true);}D.onComplete.subscribe(function(){this.set("height",J);this.set("width",P);this.fireEvent("resize",{ev:"resize",target:this,height:J,width:P,top:Q,left:H});},this,true);D.animate();}}else{if(this._proxy&&!F){this.fireEvent("proxyResize",{ev:"proxyresize",target:this,height:J,width:P,top:Q,left:H});}else{this.fireEvent("resize",{ev:"resize",target:this,height:J,width:P,top:Q,left:H});}}return this;},_handle_for_br:function(F){var G=this._setWidth(F.e);var D=this._setHeight(F.e);this.resize(F.e,D,G,0,0);},_handle_for_bl:function(G){var H=this._setWidth(G.e,true);var F=this._setHeight(G.e);var D=(H-this._cache.width);this.resize(G.e,F,H,0,D);},_handle_for_tl:function(G){var I=this._setWidth(G.e,true);var F=this._setHeight(G.e,true);var H=(F-this._cache.height);var D=(I-this._cache.width);this.resize(G.e,F,I,H,D);},_handle_for_tr:function(F){var H=this._setWidth(F.e);var D=this._setHeight(F.e,true);var G=(D-this._cache.height);this.resize(F.e,D,H,G,0);},_handle_for_r:function(D){this._dds.r.setYConstraint(0,0);var F=this._setWidth(D.e);this.resize(D.e,0,F,0,0);},_handle_for_l:function(F){this._dds.l.setYConstraint(0,0);var G=this._setWidth(F.e,true);var D=(G-this._cache.width);this.resize(F.e,0,G,0,D);},_handle_for_b:function(F){this._dds.b.setXConstraint(0,0);var D=this._setHeight(F.e);this.resize(F.e,D,0,0,0);},_handle_for_t:function(F){this._dds.t.setXConstraint(0,0);var D=this._setHeight(F.e,true);var G=(D-this._cache.height);this.resize(F.e,D,0,G,0);},_setWidth:function(H,J){var I=this._cache.xy[0],G=this._cache.width,D=A.getPageX(H),F=(D-I);if(J){F=(I-D)+parseInt(this.get("width"),10);}F=this._snapTick(F,this.get("xTicks"));F=this._checkWidth(F);return F;},_checkWidth:function(D){if(this.get("minWidth")){if(D<=this.get("minWidth")){D=this.get("minWidth");}}if(this.get("maxWidth")){if(D>=this.get("maxWidth")){D=this.get("maxWidth");}}return D;},_checkHeight:function(D){if(this.get("minHeight")){if(D<=this.get("minHeight")){D=this.get("minHeight");}}if(this.get("maxHeight")){if(D>=this.get("maxHeight")){D=this.get("maxHeight");}}return D;},_setHeight:function(G,I){var H=this._cache.xy[1],F=this._cache.height,J=A.getPageY(G),D=(J-H);if(I){D=(H-J)+parseInt(this.get("height"),10);}D=this._snapTick(D,this.get("yTicks"));D=this._checkHeight(D);return D;},_snapTick:function(G,F){if(!G||!F){return G;}var H=G;var D=G%F;if(D>0){if(D>(F/2)){H=G+(F-D);}else{H=G-D;}}return H;},init:function(H,F){this._locked=false;this._cache={xy:[],height:0,width:0,top:0,left:0,offsetHeight:0,offsetWidth:0,start:{height:0,width:0,top:0,left:0}};B.superclass.init.call(this,H,F);this.set("setSize",this.get("setSize"));if(F.height){this.set("height",parseInt(F.height,10));}else{var G=this.getStyle("height");if(G=="auto"){this.set("height",parseInt(this.get("element").offsetHeight,10));}}if(F.width){this.set("width",parseInt(F.width,10));}else{var D=this.getStyle("width");if(D=="auto"){this.set("width",parseInt(this.get("element").offsetWidth,10));}}var I=H;if(!C.isString(I)){I=E.generateId(I);}B._instances[I]=this;this._active=false;this._createWrap();this._createProxy();this._createHandles();},getProxyEl:function(){return this._proxy;},getWrapEl:function(){return this._wrap;},getStatusEl:function(){return this._status;},getActiveHandleEl:function(){return this._handles[this._currentHandle];},isActive:function(){return((this._active)?true:false);},initAttributes:function(D){B.superclass.initAttributes.call(this,D);this.setAttributeConfig("useShim",{value:((D.useShim===true)?true:false),validator:YAHOO.lang.isBoolean,method:function(F){for(var G in this._dds){if(C.hasOwnProperty(this._dds,G)){this._dds[G].useShim=F;}}if(this.dd){this.dd.useShim=F;}}});this.setAttributeConfig("setSize",{value:((D.setSize===false)?false:true),validator:YAHOO.lang.isBoolean});this.setAttributeConfig("wrap",{writeOnce:true,validator:YAHOO.lang.isBoolean,value:D.wrap||false});this.setAttributeConfig("handles",{writeOnce:true,value:D.handles||["r","b","br"],validator:function(F){if(C.isString(F)&&F.toLowerCase()=="all"){F=["t","b","r","l","bl","br","tl","tr"];}if(!C.isArray(F)){F=F.replace(/, /g,",");F=F.split(",");}this._configs.handles.value=F;}});this.setAttributeConfig("width",{value:D.width||parseInt(this.getStyle("width"),10),validator:YAHOO.lang.isNumber,method:function(F){F=parseInt(F,10);if(F>0){if(this.get("setSize")){this.setStyle("width",F+"px");}this._cache.width=F;this._configs.width.value=F;}}});this.setAttributeConfig("height",{value:D.height||parseInt(this.getStyle("height"),10),validator:YAHOO.lang.isNumber,method:function(F){F=parseInt(F,10);if(F>0){if(this.get("setSize")){this.setStyle("height",F+"px");}this._cache.height=F;this._configs.height.value=F;
}}});this.setAttributeConfig("minWidth",{value:D.minWidth||15,validator:YAHOO.lang.isNumber});this.setAttributeConfig("minHeight",{value:D.minHeight||15,validator:YAHOO.lang.isNumber});this.setAttributeConfig("maxWidth",{value:D.maxWidth||10000,validator:YAHOO.lang.isNumber});this.setAttributeConfig("maxHeight",{value:D.maxHeight||10000,validator:YAHOO.lang.isNumber});this.setAttributeConfig("minY",{value:D.minY||false});this.setAttributeConfig("minX",{value:D.minX||false});this.setAttributeConfig("maxY",{value:D.maxY||false});this.setAttributeConfig("maxX",{value:D.maxX||false});this.setAttributeConfig("animate",{value:D.animate||false,validator:function(G){var F=true;if(!YAHOO.util.Anim){F=false;}return F;}});this.setAttributeConfig("animateEasing",{value:D.animateEasing||function(){var F=false;if(YAHOO.util.Easing&&YAHOO.util.Easing.easeOut){F=YAHOO.util.Easing.easeOut;}return F;}()});this.setAttributeConfig("animateDuration",{value:D.animateDuration||0.5});this.setAttributeConfig("proxy",{value:D.proxy||false,validator:YAHOO.lang.isBoolean});this.setAttributeConfig("ratio",{value:D.ratio||false,validator:YAHOO.lang.isBoolean});this.setAttributeConfig("ghost",{value:D.ghost||false,validator:YAHOO.lang.isBoolean});this.setAttributeConfig("draggable",{value:D.draggable||false,validator:YAHOO.lang.isBoolean,method:function(F){if(F&&this._wrap){this._setupDragDrop();}else{if(this.dd){E.removeClass(this._wrap,this.CSS_DRAG);this.dd.unreg();}}}});this.setAttributeConfig("hover",{value:D.hover||false,validator:YAHOO.lang.isBoolean});this.setAttributeConfig("hiddenHandles",{value:D.hiddenHandles||false,validator:YAHOO.lang.isBoolean});this.setAttributeConfig("knobHandles",{value:D.knobHandles||false,validator:YAHOO.lang.isBoolean});this.setAttributeConfig("xTicks",{value:D.xTicks||false});this.setAttributeConfig("yTicks",{value:D.yTicks||false});this.setAttributeConfig("status",{value:D.status||false,validator:YAHOO.lang.isBoolean});this.setAttributeConfig("autoRatio",{value:D.autoRatio||false,validator:YAHOO.lang.isBoolean});},destroy:function(){for(var F in this._handles){if(C.hasOwnProperty(this._handles,F)){A.purgeElement(this._handles[F]);this._handles[F].parentNode.removeChild(this._handles[F]);}}if(this._proxy){this._proxy.parentNode.removeChild(this._proxy);}if(this._status){this._status.parentNode.removeChild(this._status);}if(this.dd){this.dd.unreg();E.removeClass(this._wrap,this.CSS_DRAG);}if(this._wrap!=this.get("element")){this.setStyle("position","");this.setStyle("top","");this.setStyle("left","");this._wrap.parentNode.replaceChild(this.get("element"),this._wrap);}this.removeClass(this.CSS_RESIZE);delete YAHOO.util.Resize._instances[this.get("id")];for(var D in this){if(C.hasOwnProperty(this,D)){this[D]=null;delete this[D];}}},toString:function(){if(this.get){return"Resize (#"+this.get("id")+")";}return"Resize Utility";}});YAHOO.util.Resize=B;})();YAHOO.register("resize",YAHOO.util.Resize,{version:"2.7.0",build:"1799"});/*
Copyright (c) 2009, Yahoo! Inc. All rights reserved.
Code licensed under the BSD License:
http://developer.yahoo.net/yui/license.txt
version: 2.7.0
*/
(function(){var C=YAHOO.util.Dom,A=YAHOO.util.Event,D=YAHOO.lang;var B=function(F,E){var G={element:F,attributes:E||{}};B.superclass.constructor.call(this,G.element,G.attributes);};B._instances={};B.getCropperById=function(E){if(B._instances[E]){return B._instances[E];}return false;};YAHOO.extend(B,YAHOO.util.Element,{CSS_MAIN:"yui-crop",CSS_MASK:"yui-crop-mask",CSS_RESIZE_MASK:"yui-crop-resize-mask",_image:null,_active:null,_resize:null,_resizeEl:null,_resizeMaskEl:null,_wrap:null,_mask:null,_createWrap:function(){this._wrap=document.createElement("div");this._wrap.id=this.get("element").id+"_wrap";this._wrap.className=this.CSS_MAIN;var F=this.get("element");this._wrap.style.width=F.width?F.width+"px":C.getStyle(F,"width");this._wrap.style.height=F.height?F.height+"px":C.getStyle(F,"height");var E=this.get("element").parentNode;E.replaceChild(this._wrap,this.get("element"));this._wrap.appendChild(this.get("element"));A.on(this._wrap,"mouseover",this._handleMouseOver,this,true);A.on(this._wrap,"mouseout",this._handleMouseOut,this,true);A.on(this._wrap,"click",function(G){A.stopEvent(G);},this,true);},_createMask:function(){this._mask=document.createElement("div");this._mask.className=this.CSS_MASK;this._wrap.appendChild(this._mask);},_createResize:function(){this._resizeEl=document.createElement("div");this._resizeEl.className=YAHOO.util.Resize.prototype.CSS_RESIZE;this._resizeEl.style.position="absolute";this._resizeEl.innerHTML='<div class="'+this.CSS_RESIZE_MASK+'"></div>';this._resizeMaskEl=this._resizeEl.firstChild;this._wrap.appendChild(this._resizeEl);this._resizeEl.style.top=this.get("initialXY")[1]+"px";this._resizeEl.style.left=this.get("initialXY")[0]+"px";this._resizeMaskEl.style.height=Math.floor(this.get("initHeight"))+"px";this._resizeMaskEl.style.width=Math.floor(this.get("initWidth"))+"px";this._resize=new YAHOO.util.Resize(this._resizeEl,{knobHandles:true,handles:"all",draggable:true,status:this.get("status"),minWidth:this.get("minWidth"),minHeight:this.get("minHeight"),ratio:this.get("ratio"),autoRatio:this.get("autoRatio"),height:this.get("initHeight"),width:this.get("initWidth")});this._setBackgroundImage(this.get("element").getAttribute("src",2));this._setBackgroundPosition(-(this.get("initialXY")[0]),-(this.get("initialXY")[1]));this._resize.on("startResize",this._handleStartResizeEvent,this,true);this._resize.on("endResize",this._handleEndResizeEvent,this,true);this._resize.on("dragEvent",this._handleDragEvent,this,true);this._resize.on("beforeResize",this._handleBeforeResizeEvent,this,true);this._resize.on("resize",this._handleResizeEvent,this,true);this._resize.dd.on("b4StartDragEvent",this._handleB4DragEvent,this,true);},_handleMouseOver:function(F){var E="keydown";if(YAHOO.env.ua.gecko||YAHOO.env.ua.opera){E="keypress";}if(!this._active){this._active=true;if(this.get("useKeys")){A.on(document,E,this._handleKeyPress,this,true);}}},_handleMouseOut:function(F){var E="keydown";if(YAHOO.env.ua.gecko||YAHOO.env.ua.opera){E="keypress";}this._active=false;if(this.get("useKeys")){A.removeListener(document,E,this._handleKeyPress);}},_moveEl:function(G,J){var H=0,E=0,I=this._setConstraints(),F=true;switch(G){case"down":H=-(J);if((I.bottom-J)<0){F=false;this._resizeEl.style.top=(I.top+I.bottom)+"px";}break;case"up":H=(J);if((I.top-J)<0){F=false;this._resizeEl.style.top="0px";}break;case"right":E=-(J);if((I.right-J)<0){F=false;this._resizeEl.style.left=(I.left+I.right)+"px";}break;case"left":E=J;if((I.left-J)<0){F=false;this._resizeEl.style.left="0px";}break;}if(F){this._resizeEl.style.left=(parseInt(this._resizeEl.style.left,10)-E)+"px";this._resizeEl.style.top=(parseInt(this._resizeEl.style.top,10)-H)+"px";this.fireEvent("moveEvent",{target:"keypress"});}else{this._setConstraints();}this._syncBackgroundPosition();},_handleKeyPress:function(G){var E=A.getCharCode(G),F=false,H=((G.shiftKey)?this.get("shiftKeyTick"):this.get("keyTick"));switch(E){case 37:this._moveEl("left",H);F=true;break;case 38:this._moveEl("up",H);F=true;break;case 39:this._moveEl("right",H);F=true;break;case 40:this._moveEl("down",H);F=true;break;default:}if(F){A.preventDefault(G);}},_handleB4DragEvent:function(){this._setConstraints();},_handleDragEvent:function(){this._syncBackgroundPosition();this.fireEvent("dragEvent",arguments);this.fireEvent("moveEvent",{target:"dragevent"});},_handleBeforeResizeEvent:function(F){var I=C.getRegion(this.get("element")),J=this._resize._cache,H=this._resize._currentHandle,G=0,E=0;if(F.top&&(F.top<I.top)){G=(J.height+J.top)-I.top;C.setY(this._resize.getWrapEl(),I.top);this._resize.getWrapEl().style.height=G+"px";this._resize._cache.height=G;this._resize._cache.top=I.top;this._syncBackgroundPosition();return false;}if(F.left&&(F.left<I.left)){E=(J.width+J.left)-I.left;C.setX(this._resize.getWrapEl(),I.left);this._resize._cache.left=I.left;this._resize.getWrapEl().style.width=E+"px";this._resize._cache.width=E;this._syncBackgroundPosition();return false;}if(H!="tl"&&H!="l"&&H!="bl"){if(J.left&&F.width&&((J.left+F.width)>I.right)){E=(I.right-J.left);C.setX(this._resize.getWrapEl(),(I.right-E));this._resize.getWrapEl().style.width=E+"px";this._resize._cache.left=(I.right-E);this._resize._cache.width=E;this._syncBackgroundPosition();return false;}}if(H!="t"&&H!="tr"&&H!="tl"){if(J.top&&F.height&&((J.top+F.height)>I.bottom)){G=(I.bottom-J.top);C.setY(this._resize.getWrapEl(),(I.bottom-G));this._resize.getWrapEl().style.height=G+"px";this._resize._cache.height=G;this._resize._cache.top=(I.bottom-G);this._syncBackgroundPosition();return false;}}},_handleResizeMaskEl:function(){var E=this._resize._cache;this._resizeMaskEl.style.height=Math.floor(E.height)+"px";this._resizeMaskEl.style.width=Math.floor(E.width)+"px";},_handleResizeEvent:function(E){this._setConstraints(true);this._syncBackgroundPosition();this.fireEvent("resizeEvent",arguments);this.fireEvent("moveEvent",{target:"resizeevent"});},_syncBackgroundPosition:function(){this._handleResizeMaskEl();this._setBackgroundPosition(-(parseInt(this._resizeEl.style.left,10)),-(parseInt(this._resizeEl.style.top,10)));
},_setBackgroundPosition:function(F,H){var J=parseInt(C.getStyle(this._resize.get("element"),"borderLeftWidth"),10);var G=parseInt(C.getStyle(this._resize.get("element"),"borderTopWidth"),10);if(isNaN(J)){J=0;}if(isNaN(G)){G=0;}var E=this._resize.getWrapEl().firstChild;var I=(F-J)+"px "+(H-G)+"px";this._resizeMaskEl.style.backgroundPosition=I;},_setBackgroundImage:function(F){var E=this._resize.getWrapEl().firstChild;this._image=F;E.style.backgroundImage="url("+F+"#)";},_handleEndResizeEvent:function(){this._setConstraints(true);},_handleStartResizeEvent:function(){this._setConstraints(true);var I=this._resize._cache.height,F=this._resize._cache.width,H=parseInt(this._resize.getWrapEl().style.top,10),E=parseInt(this._resize.getWrapEl().style.left,10),G=0,J=0;switch(this._resize._currentHandle){case"b":G=(I+this._resize.dd.bottomConstraint);break;case"l":J=(F+this._resize.dd.leftConstraint);break;case"r":G=(I+H);J=(F+this._resize.dd.rightConstraint);break;case"br":G=(I+this._resize.dd.bottomConstraint);J=(F+this._resize.dd.rightConstraint);break;case"tr":G=(I+H);J=(F+this._resize.dd.rightConstraint);break;}if(G){}if(J){}this.fireEvent("startResizeEvent",arguments);},_setConstraints:function(J){var H=this._resize;H.dd.resetConstraints();var N=parseInt(H.get("height"),10),F=parseInt(H.get("width"),10);if(J){N=H._cache.height;F=H._cache.width;}var L=C.getRegion(this.get("element"));var G=H.getWrapEl();var O=C.getXY(G);var I=O[0]-L.left;var M=L.right-O[0]-F;var K=O[1]-L.top;var E=L.bottom-O[1]-N;if(K<0){K=0;}H.dd.setXConstraint(I,M);H.dd.setYConstraint(K,E);return{top:K,right:M,bottom:E,left:I};},getCropCoords:function(){var E={top:parseInt(this._resize.getWrapEl().style.top,10),left:parseInt(this._resize.getWrapEl().style.left,10),height:this._resize._cache.height,width:this._resize._cache.width,image:this._image};return E;},reset:function(){this._resize.resize(null,this.get("initHeight"),this.get("initWidth"),0,0,true);this._resizeEl.style.top=this.get("initialXY")[1]+"px";this._resizeEl.style.left=this.get("initialXY")[0]+"px";this._syncBackgroundPosition();return this;},getEl:function(){return this.get("element");},getResizeEl:function(){return this._resizeEl;},getWrapEl:function(){return this._wrap;},getMaskEl:function(){return this._mask;},getResizeMaskEl:function(){return this._resizeMaskEl;},getResizeObject:function(){return this._resize;},init:function(G,E){B.superclass.init.call(this,G,E);var H=G;if(!D.isString(H)){if(H.tagName&&(H.tagName.toLowerCase()=="img")){H=C.generateId(H);}else{return false;}}else{var F=C.get(H);if(F.tagName&&F.tagName.toLowerCase()=="img"){}else{return false;}}B._instances[H]=this;this._createWrap();this._createMask();this._createResize();this._setConstraints();},initAttributes:function(E){B.superclass.initAttributes.call(this,E);this.setAttributeConfig("initialXY",{writeOnce:true,validator:YAHOO.lang.isArray,value:E.initialXY||[10,10]});this.setAttributeConfig("keyTick",{validator:YAHOO.lang.isNumber,value:E.keyTick||1});this.setAttributeConfig("shiftKeyTick",{validator:YAHOO.lang.isNumber,value:E.shiftKeyTick||10});this.setAttributeConfig("useKeys",{validator:YAHOO.lang.isBoolean,value:((E.useKeys===false)?false:true)});this.setAttributeConfig("status",{validator:YAHOO.lang.isBoolean,value:((E.status===false)?false:true),method:function(F){if(this._resize){this._resize.set("status",F);}}});this.setAttributeConfig("minHeight",{validator:YAHOO.lang.isNumber,value:E.minHeight||50,method:function(F){if(this._resize){this._resize.set("minHeight",F);}}});this.setAttributeConfig("minWidth",{validator:YAHOO.lang.isNumber,value:E.minWidth||50,method:function(F){if(this._resize){this._resize.set("minWidth",F);}}});this.setAttributeConfig("ratio",{validator:YAHOO.lang.isBoolean,value:E.ratio||false,method:function(F){if(this._resize){this._resize.set("ratio",F);}}});this.setAttributeConfig("autoRatio",{validator:YAHOO.lang.isBoolean,value:((E.autoRatio===false)?false:true),method:function(F){if(this._resize){this._resize.set("autoRatio",F);}}});this.setAttributeConfig("initHeight",{writeOnce:true,validator:YAHOO.lang.isNumber,value:E.initHeight||(this.get("element").height/4)});this.setAttributeConfig("initWidth",{validator:YAHOO.lang.isNumber,writeOnce:true,value:E.initWidth||(this.get("element").width/4)});},destroy:function(){this._resize.destroy();this._resizeEl.parentNode.removeChild(this._resizeEl);this._mask.parentNode.removeChild(this._mask);A.purgeElement(this._wrap);this._wrap.parentNode.replaceChild(this.get("element"),this._wrap);for(var E in this){if(D.hasOwnProperty(this,E)){this[E]=null;}}},toString:function(){if(this.get){return"ImageCropper (#"+this.get("id")+")";}return"Image Cropper";}});YAHOO.widget.ImageCropper=B;})();YAHOO.register("imagecropper",YAHOO.widget.ImageCropper,{version:"2.7.0",build:"1799"});Ext.namespace("Flowz");

/**
 * A popup window that allows for changing the crop window of an image
 *
 * @param config
 */
Flowz.FileControl = function(config) {
	Flowz.FileControl.superclass.constructor.call(this, config);
	Ext.apply(this, config);
	this.addEvents(['onDelete', 'onChangeOrder']);
};

Flowz.FileControl = Ext.extend(Ext.Component, {
	duration: .2,
	debounceDuration: 500,
	currentGallery: null,
	control: null,
	controlOpen: false,
	galleries: null,
	context: "",

	onRender: function(container, position) {
		this.descEditor = new Flowz.DescEditor({ renderTo: Ext.getBody().dom });

		this.saveFileOrder = this.saveFileOrder.debounce(this.debounceDuration, false);

		Ext.DomHelper.append(Ext.getBody(), {
			id: "file-control-container", cls: "x-hidden", children: [
				{ cls: "backdrop" },
				{ id: "file-control", children: [
					{ cls: "label" },
					{ cls: "screen" },
					{ cls: "btn-move-left" },
					{ cls: "btn-move-right" },
					{ cls: "btn-desc" },
					{ cls: "btn-crop" },
					{ cls: "btn-delete" }
				]}
			]
		});

		this.control = Ext.get("file-control-container");
		this.control.unselectable();
		this.control.child(".screen").on('click', function() {
			this.hideControl();
		}, this);

		this.cropper = new Flowz.ImageCropper({ renderTo: Ext.getBody().dom, control: this.control, onHide: this.endCrop });

		//=================== MOVE LEFT
		var btnLeft = this.control.child(".btn-move-left");
		btnLeft.on('mouseover', function() {
			this.child(".btn-move-left").setStyle('background-position', '0 -90px');
		}, this.control);

		btnLeft.on('mouseout', function() {
			this.child(".btn-move-left").setStyle('background-position', '0 0px');
		}, this.control);

		btnLeft.on('mousedown', function() {
			this.child(".btn-move-left").setStyle('background-position', '0 -180px');
		}, this.control);

		btnLeft.on('mouseup', function() {
			this.child(".btn-move-left").setStyle('background-position', '0 -90px');
		}, this.control);

		btnLeft.on('click', function() {
			this.moveLeft.call(this);
		}, this);

		//=================== MOVE RIGHT
		var btnRight = this.control.child(".btn-move-right");
		btnRight.on('mouseover', function() {
			this.child(".btn-move-right").setStyle('background-position', '-13px -90px');
		}, this.control);

		btnRight.on('mouseout', function() {
			this.child(".btn-move-right").setStyle('background-position', '-13px 0px');
		}, this.control);

		btnRight.on('mousedown', function() {
			this.child(".btn-move-right").setStyle('background-position', '-13px -180px');
		}, this.control);

		btnRight.on('mouseup', function() {
			this.child(".btn-move-right").setStyle('background-position', '-13px -90px');
		}, this.control);

		btnRight.on('click', function() {
			this.moveRight.call(this);
		}, this);

		//===================== EDIT
		var btnDesc = this.control.child(".btn-desc");
		btnDesc.on('mouseover', function() {
			this.child(".btn-desc").setStyle('background-position', '0 -21px');
		}, this.control);

		btnDesc.on('mouseout', function() {
			this.child(".btn-desc").setStyle('background-position', '0 0');
		}, this.control);

		btnDesc.on('mousedown', function() {
			this.child(".btn-desc").setStyle('background-position', '0 -42px');
		}, this.control);

		btnDesc.on('mouseup', function() {
			this.child(".btn-desc").setStyle('background-position', '0 -21px');
		}, this.control);

		btnDesc.on('click', function() {
			this.openDescEditor();
		}, this);

		//======================= CROP
		var btnCrop =  this.control.child(".btn-crop");
		btnCrop.on('mouseover', function() {
			this.child(".btn-crop").setStyle('background-position', '-40px -21px');
		}, this.control);

		btnCrop.on('mouseout', function() {
			this.child(".btn-crop").setStyle('background-position', '-40px 0');
		}, this.control);

		btnCrop.on('mousedown', function() {
			this.child(".btn-crop").setStyle('background-position', '-40px -42px');
		}, this.control);

		btnCrop.on('mouseup', function() {
			this.child(".btn-crop").setStyle('background-position', '-40px -21px');
		}, this.control);

		btnCrop.on('click', function() {
			this.startCrop();
		}, this);

		//======================= Delete
		var btnDelete = this.control.child(".btn-delete");
		btnDelete.on('mouseover', function() {
			this.child(".btn-delete").setStyle('background-position', '-80px -21px');
		}, this.control);

		btnDelete.on('mouseout', function() {
			this.child(".btn-delete").setStyle('background-position', '-80px 0');
		}, this.control);

		btnDelete.on('mousedown', function() {
			this.child(".btn-delete").setStyle('background-position', '-80px -42px');
		}, this.control);

		btnDelete.on('mouseup', function() {
			this.child(".btn-delete").setStyle('background-position', '-80px -21px');
		}, this.control);

		btnDelete.on('click', function() {
			this.deleteFile(this.control.file);
		}, this);



		for(var i = 0; i < this.galleries.getCount(); i++) {
			var gallery = this.galleries.itemAt(i);
			for(var j = 0; j < gallery.getCount(); j++) {
				var f = gallery.itemAt(j);
				this.setupThumb(f);
			}
		}

		Ext.EventManager.onWindowResize(this.onResize, this);

		//var map = new Ext.KeyMap(Ext.getBody(), [
		var ignore = /input|textarea/i;

		this.map = new Ext.KeyMap(document, [
			{
				key: [10,13],
				fn: function(key, event){
					if(this.descEditor.isOpen && event.getTarget().id == this.descEditor.textareaId) {
						this.descEditor.save();
					}
				},
				scope: this,
				ctrl: true
			}, {
				key: Ext.EventObject.ESC,
				fn: function(key, event){

					/*
					var tag = event.getTarget().tagName;
					if(ignore.test(tag))
						return;
					*/
					if(this.cropper.isOpen) {
						this.cropper.cancel();
						return;
					}
					if(this.descEditor.isOpen) {
						this.descEditor.cancel();
						return;
					}
					if(this.controlOpen) {
						this.hideControl();
					}
				},
				scope: this
			}, {
				key: Ext.EventObject.DELETE,
				fn: function(key, event){
					var tag = event.getTarget().tagName;
					if(ignore.test(tag))
						return;
					if(this.controlOpen && this.control.file) {
						this.deleteFile(this.control.file);
					}
				},
				scope: this

			}, {
				key: "d",
				fn: function(key, event){
					var tag = event.getTarget().tagName;
					if(ignore.test(tag))
						return;

					if(!this.controlOpen)
						return;
					this.openDescEditor();
				},
				scope: this

			}, {
				key: "c",
				fn: function(key, event){
					var tag = event.getTarget().tagName;
					if(ignore.test(tag))
						return;

					if(!this.controlOpen)
						return;
					this.startCrop();
				},
				scope: this

			}, {
				key: "r",
				fn: function(key, event){
					var tag = event.getTarget().tagName;
					if(ignore.test(tag))
						return;
					if(!this.controlOpen)
						return;
					this.moveRight();
				},
				scope: this

			}, {
				key: "q",
				fn: function(key, event){
					var tag = event.getTarget().tagName;
					if(ignore.test(tag))
						return;
					if(!this.controlOpen)
						return;
					this.moveLeft();
				},
				scope: this

			}, {
				key: "f",
				fn: function(key, event){
					var tag = event.getTarget().tagName;
					if(ignore.test(tag))
						return;

					if(!this.currentGallery) {
						this.currentGallery = this.galleries.itemAt(0);
						if(!this.currentGallery)
							return;
					}
					if(this.currentGallery.getCount() == 0)
						return;

					if(!this.controlOpen) {
						var file = this.currentGallery.startNode;
						this.openControl(file);
						return;
					}

					if(this.control.file && this.control.file.next) {
						this.openControl(this.control.file.next);
					}
				},
				scope: this

			}, {
				key: "a",
				fn: function(key, event){

					var tag = event.getTarget().tagName;
					if(ignore.test(tag))
						return;

					if(!this.currentGallery) {
						this.currentGallery = this.galleries.itemAt(0);
						if(!this.currentGallery)
							return;
					}
					if(this.currentGallery.getCount() == 0)
						return;

					if(!this.controlOpen) {
						var file = this.currentGallery.endNode;
						this.openControl(file);
						return;
					}

					if(this.control.file && this.control.file.prev) {
						this.openControl(this.control.file.prev);
					}
				},
				scope: this

			}, {
				key: "\t",
				ctrl:true,
				shift:true,
				fn: function(){  }
			}
		]);
	},

	setupThumb: function(f) {
		var thumb = Ext.get("thumb-" + f.id);
		thumb.unselectable();
		thumb.on('click', this.openControl.createDelegate(this, [f]));
		thumb.clearOpacity();
		thumb.dom.style.visibility = '';
		// we create the proxies at startup because safari chokes when creating them in realtime.
		var thumbContainer = Ext.get("thumb-" + f.id + "-container");
		if(thumbContainer.proxy && thumbContainer.proxy.remove)
			thumbContainer.proxy.remove();
		thumbContainer.proxy = thumb.createProxy("thumb-proxy", Ext.getBody(), true);
		thumbContainer.proxy.update(thumbContainer.dom.innerHTML);
		thumbContainer.proxy.setStyle('display', 'none');

		// refresh the tool if it is open because processing status changed. (show crop button, etc)
		// NOTE: this doesn't work well, so skipping it.  (what happens if it is open while a user is editing desc
		/*
		if(this.controlOpen && this.control.file == f)
			this.openControl(f);
		*/
	},

	onResize: function() {
		if(this.controlOpen) {
			this.openControl(this.control.file);
		}

	},

	deleteFile: function(file) {
		if(confirm("Are you sure wish to delete this file?")) {
			// yoink!
			people.removeFile(file.galleryId, file.id, {
				callback:function(gid, file) {
					var container = Ext.get("thumb-" + file.id + "-container");

					container.parent().remove();

					if(file.next) {
						this.openControl(file.next);
					} else if(file.prev) {
						this.openControl(file.prev);
					} else {
						this.hideControl();
					}

					if(file.prev)
						file.prev.next = file.next;
					else
						this.currentGallery.startNode = file.next;

					if(file.next)
						file.next.prev = file.prev;
					else
						this.currentGallery.endNode = file.prev;

					var now = new Date();
					this.setStatus(gid, 'Deleted file at: ' + hour12(now.getHours()) + ':' + checkTime(now.getMinutes()));

				}.createDelegate(this, [file.galleryId, file]),
				timeout:5000,
				errorHandler:function(message) {
					this.setStatus("Unable to save.");
					alert("There was a problem saving your changes.  This could be a problem with your internet connection, or something we messed up.  Please report this message to support:\n\n" + message);
				}.createDelegate(this)
			});
		}
	},

	swapEm: function(thumb, swap, file, direction) {
		var context =  {
			source: thumb,
			dest: swap,
			file: file,
			direction: direction,
			currentGallery: this.currentGallery,
			module: this
		};

		var start, end;
		if(thumb.getLeft() > swap.getLeft()) {
			start = swap.getLeft();
			end = thumb.getLeft();
		} else {
			start = thumb.getLeft();
			end = swap.getLeft();
		}

		var centerx = ((end - start) / 2) + start;
		var newx = swap.getLeft();
		var newy = swap.getTop();
//		console.log("Swapping: " + thumb.id + " to " + swap.id);
//		console.log("prev <- file -> next:  " + (file.prev ? file.prev.id : " null") + " <- " + file.id + " -> " + (file.next ? file.next.id : " null"));
//		var log = "";
//		var node = currentGallery.startNode;
//		console.log("Start Node: " + node.id);
//		console.log("End Node: " + currentGallery.endNode.id);
//		while(node != null) {
//			log += node.id + " -> ";
//			node = node.next;
//		}
//		log += " null";
//		console.log("Entire List: " + log);
//		var log = "";
//		var node = currentGallery.endNode;
//		var counter = 0;
//		while(node != null) {
//			log = node.id + " <- " + log;
//			node = node.prev;
//			counter++;
//			if(counter > 20)
//				break;
//		}
//		log += " null";
//		console.log("Revers List: " + log);
		swap.proxy.show();
		//swap.setVisibilityMode(Ext.Element.DISPLAY);
		swap.hide();
		swap.proxy.setBox(swap.getBox());
		swap.proxy.setOpacity(1);
		var b = thumb.getBox(false);
		b.duration = this.duration;
		b.easing = 'easeIn';
		b.opacity = 1;
		b.block = true;
		b.control = [[centerx, thumb.getTop() + 100]];
		swap.proxy.customShift(b);

		thumb.proxy.show();
		thumb.hide();
		//thumb.setVisibilityMode(Ext.Element.DISPLAY);		
		thumb.proxy.setBox(thumb.getBox());
		// this is a severe hack to make sure there is no white flicker as the thumb and control move across the screen.
		thumb.proxy.setX(thumb.getX() - 3);
		thumb.proxy.setY(thumb.getY() - 3);
		thumb.proxy.setWidth(thumb.getWidth() + 6);
		thumb.proxy.setHeight(thumb.getHeight() + 6);

		b = swap.getBox(false);
		// same hack above...
		b.x = b.x - 3;
		b.y = b.y - 3;
		b.width = b.width + 6;
		b.height = b.height + 6;
		//b.control = [[centerx, swap.getTop() - 100]];
		b.callback = function() {
			var sourceParent = this.source.parent();
			var destParent = this.dest.parent();
			sourceParent.appendChild(this.dest);
			destParent.appendChild(this.source);

			var oldprev = this.file.prev;
			var oldnext = this.file.next;
			if(this.direction == "forward") {

				this.file.next = oldnext.next;
				if(oldnext.next && oldnext.next.prev)
					oldnext.next.prev = this.file;

				oldnext.prev = this.file.prev;

				this.file.prev = oldnext;
				oldnext.next = this.file;

				if(oldprev) {
					oldprev.next = oldnext;
					oldprev.next.next = this.file;
				} else {
					oldnext.prev = null;
				}

				if(this.file.id == this.currentGallery.startNode.id) {
					this.currentGallery.startNode = oldnext;
				}
			} else {

				this.file.prev = oldprev.prev;
				if(oldprev.prev && oldprev.prev.next)
					oldprev.prev.next = this.file;

				oldprev.next = this.file.next;

				this.file.next = oldprev;
				oldprev.prev = this.file;

				if(oldnext) {
					oldnext.prev = oldprev;
					oldnext.prev.prev = this.file;
				} else {
					oldprev.next = null;
				}

				if(this.file.id == this.currentGallery.endNode.id) {
					this.currentGallery.endNode = oldprev;
				}
			}

			if(this.file.prev == null)
				this.currentGallery.startNode = this.file;
			if(this.file.next == null)
				this.currentGallery.endNode = this.file;

			//console.log("done with switch");

			//console.log("prev <- file -> next:  " + (file.prev?file.prev.id:" null") + " <- " + file.id + " -> " + (file.next?file.next.id:" null"));
			//console.log("prev <- prev <- file:  " + file.prev.prev.id + " <- " + file.prev.id + " <- " + file.id);
			//console.log("file -> next -> next:  " + file.id + " -> " + file.next.id + " -> " + file.next.next.id);

//			var log = "";
//			var node = currentGallery.startNode;
//			console.log("Start Node: " + node.id);
//			console.log("End Node: " + currentGallery.endNode.id);
//			while(node != null) {
//				log += node.id + " -> ";
//				node = node.next;
//			}
//			log += " null";
//			console.log("Entire List: " + log);
//
//
//			log = "";
//			var node = currentGallery.endNode;
//			counter = 0;
//			while(node != null) {
//				log = node.id + " <- " + log;
//				node = node.prev;
//				counter++;
//				if(counter > 20)
//					break;
//			}
//			log += " null";
//			console.log("Revers List: " + log);
//
//			//this.source.proxy.hide();
//			console.log("removing proxies.");


			this.source.show();
			this.source.proxy.hide();
			this.dest.show();
			this.dest.proxy.hide();

			// we have a "quirk": The div surrounding a swapped thumb is marked with visibility: visible.  Setting
			// the parent div to hidden doesn't hide these thumbs.  We have to
			this.source.dom.style.visibility = '';
			this.dest.dom.style.visibility = '';

			this.module.saveFileOrder(this.currentGallery);
			// We need to delete the proxy for our parent gallery container.  Otherwise, it will reflect the incorrect
			// file order when we change the gallery order.
			var section = Ext.get("section-" + this.file.galleryId);
			if(section.proxy) {
				section.proxy.remove();
				section.proxy = null;
			}
		};
		b.scope = context;
		b.duration = this.duration;
		b.easing = 'easeIn';
		b.opacity = 1;
		b.block = true;
		thumb.proxy.customShift(b);

		var offset = 18;
		if(Ext.isIE) {
			offset = 20;
		}
		this.control.moveTo(newx - offset, newy - offset, {anim: true, easing: "easeIn", duration: this.duration});
	},

	openControl: function(file) {
		this.currentGallery = this.galleries.get(file.galleryId);
		var thumb = Ext.get("thumb-" + file.id);
		var desc = Ext.get("desc-" + file.id).dom.innerHTML;
		var label = this.control.child(".label");
		label.update(file.name);
		this.control.file = file;
		var offset = 18;
		if(Ext.isIE) {
			offset = 20;
		}
		var top = thumb.getTop() - offset;
		var left = thumb.getLeft() - offset;

		// we have a problem with some images being off by a pixel or two.  This compensates
		if(thumb.getHeight() != 90) {
			top -= (90 - thumb.getHeight());
		}
		
		if(file.processing || !file.croppable) {
			this.control.child(".btn-crop").hide();
		} else {
			this.control.child(".btn-crop").show();
		}
		if(!this.controlOpen) {
			this.control.removeClass("x-hidden");
			this.control.setTop(top);
			this.control.setLeft(left);
			if(Ext.isIE) {
				//control.show();
				this.control.setVisible(true);
			} else {
				this.control.setVisible(true, { anim: true, duration: .15});
			}
		} else {
			this.control.moveTo(left, top, true);
		}
		this.controlOpen = true;

		if(this.descEditor.isOpen) {
			this.descEditor.change(file.id, desc, left - ((this.descEditor.getWidth() - this.control.getWidth()) / 2), top + this.control.getHeight() + 5);
		}
		if(this.cropper.isOpen) {
			this.cropper.cancel();
		}
	},

	hideControl: function() {
		this.controlOpen = false;
		if(Ext.isIE) {
			this.control.setVisible(false);
			// needed because the div get's toggled visible for some reason
			this.control.child(".btn-crop").hide();
		} else {
			this.control.setVisible(false, { anim: true, duration: .15});
			// needed because the div get's toggled visible for some reason
			this.control.child(".btn-crop").hide();
		}

		if(this.descEditor.isOpen)
			this.descEditor.hide();
		if(this.cropper.isOpen)
			this.cropper.hide();
	},

	moveLeft: function() {
		if(this.control.file.prev == null) {
			return;
		}
		if(this.descEditor.isOpen) {
			this.descEditor.hide();
		}
		// grab container
		var swap = Ext.get("thumb-" + this.control.file.prev.id + "-container");
		var thumb = Ext.get("thumb-" + this.control.file.id + "-container");

		if(!swap.proxy) {
			swap.proxy = swap.createProxy("thumb-proxy", Ext.getBody(), true);
			swap.proxy.update(swap.dom.innerHTML);
			swap.proxy.setStyle('display', 'none');
		}
		if(!thumb.proxy) {
			thumb.proxy = thumb.createProxy("thumb-proxy", Ext.getBody(), true);
			thumb.proxy.update(thumb.dom.innerHTML);
			thumb.proxy.setStyle('display', 'none');
		}
		swap.proxy.setStyle('z-index', 19000);
		swap.proxy.replaceClass("thumb-proxy", "swap-proxy");
		thumb.proxy.setStyle('z-index', 19001);
		thumb.proxy.replaceClass("swap-proxy", "thumb-proxy");

		this.swapEm(thumb, swap, this.control.file, "backward");
	},

	moveRight: function() {
		if(this.control.file.next == null) {
			return;
		}

		if(this.descEditor.isOpen) {
			this.descEditor.hide();
		}
		// grab container
		var swap = Ext.get("thumb-" + this.control.file.next.id + "-container");
		var thumb = Ext.get("thumb-" + this.control.file.id + "-container");

		if(!swap.proxy) {
			swap.proxy = swap.createProxy("thumb-proxy", Ext.getBody(), true);
			swap.proxy.update(swap.dom.innerHTML);
			swap.proxy.setStyle('display', 'none');
		}
		if(!thumb.proxy) {
			thumb.proxy = thumb.createProxy("thumb-proxy", Ext.getBody(), true);
			thumb.proxy.update(thumb.dom.innerHTML);
			thumb.proxy.setStyle('display', 'none');
		}
		swap.proxy.setStyle('z-index', 19000);
		swap.proxy.replaceClass("thumb-proxy", "swap-proxy");
		thumb.proxy.setStyle('z-index', 19001);
		thumb.proxy.replaceClass("swap-proxy", "thumb-proxy");

		this.swapEm(thumb, swap, this.control.file, "forward");
	},

	openDescEditor: function() {
		var desc = Ext.get("desc-" + this.control.file.id).dom.innerHTML;
		var btn = this.control.child(".btn-desc");
		this.descEditor.setLeft(this.control.getLeft() - ((this.descEditor.getWidth() - this.control.getWidth()) / 2));
		this.descEditor.setTop(this.control.getBottom() + 5);
		this.descEditor.show(btn, this.control.file.id, desc, function(id, newDescription) {
			//alert("Have new description for file " + id + ": " + newDescription);
			files.setDescription(id, newDescription, {
				callback:function(id, desc) { Ext.get("desc-" + id).update(desc); }.createDelegate(this, [id, newDescription]),
				timeout:5000,
				errorHandler:function(message) { alert("Oops: " + message); }
			});
		});
	},

	startCrop: function() {
		var file = this.control.file;
		var btn = this.control.child(".btn-desc");
		var thumb = Ext.get("thumb-" + file.id);
		var section = Ext.get("section-" + file.galleryId);
		//section.select("div.vertical-shim").setHeight(600, { duration: .75 });
		section.select("div.vertical-shim").setHeight(600);
		//Ext.getBody().animate({scroll: { to: [0, thumb.getTop() - 30] }}, .5, null, 'easeOut', "scrollWindow");
		Ext.getBody().animate({scroll: { to: [0, thumb.getTop() - 30] }}, .1, null, 'easeOut', "scrollWindow");

		this.cropper.newCrop(file, Ext.get("thumb-" + file.id), btn, function(file, crop) {
			this.setStatus(file.galleryId, "Saving crop...");
			files.setCropping(file.id, Math.round(crop.left), Math.round(crop.top), Math.round(crop.width), Math.round(crop.height), {
				callback:function(file) {
					//var container = Ext.get("thumb-" + file.id + "-container");
					// mark file as processing...
					var thumb = Ext.get("thumb-" + file.id);
					thumb.dom.src = this.context + "images/icons/simple/thumb-generating.png";
					var now = new Date();
					this.setStatus(file.galleryId, 'Last saved at: ' + hour12(now.getHours()) + ':' + checkTime(now.getMinutes()));
				}.createDelegate(this, [file]),
				//},
				scope: this,
				timeout:10000,
				errorHandler:function(message) {
					//this.setStatus(this.control.file.galleryId, "Unable to save crop.");
					alert("There was a problem saving your changes.  This could be a problem with your internet connection, or something we messed up.  Please report this message to support:\n\n" + message);
				}
			});
		}, this);
	},

	endCrop: function(file) {
		var section = Ext.get("section-" + file.galleryId);
		//section.select("div.vertical-shim").setHeight(0, { duration: .75 });
		section.select("div.vertical-shim").setHeight(0);
	},

	saveFileOrder: function(currentGallery) {
		var ids = new Array();
		var node = currentGallery.startNode;
		while(node != null) {
			ids[ids.length] = node.id;
			node = node.next;
		}
		if(ids.length > 0) {
			if(this.setStatus) {
				this.setStatus(currentGallery.id, "Saving order...");
			}
			people.changeFileOrder(currentGallery.id, ids, {
					callback:function(id, ids) {
						var now = new Date();
						if(this.setStatus)
							this.setStatus(id, 'Last saved at: ' + hour12(now.getHours()) + ':' + checkTime(now.getMinutes()));
					}.createDelegate(this, [currentGallery.id, ids]),
					timeout:5000,
					errorHandler:function(message) {
						if(this.setStatus)
							this.setStatus("Unable to save.");
						alert("There was a problem saving your changes.  This could be a problem with your internet connection, or something we messed up.  Please report this message to support:\n\n" + message); }
				});
		}
	}
});


Ext.namespace("Flowz");

/**
 * A popup window that allows for changing the crop window of an image
 *
 * @param config
 */
Flowz.ImageCropper = function(config) {
	Flowz.ImageCropper.superclass.constructor.call(this, config);
	Ext.apply(this, config);
};

Flowz.ImageCropper = Ext.extend(Ext.Component, {
	cls: 'image-cropper',
	textareaId: "image-cropper",
	sprite: '',
	width: 400,
	height: 300,

	initComponent: function() {
	},

	/**
	 * Starts a new crop (in addition to showing the crop window)
	 * @param file object with required fields: url, cropWidth, cropHeight, cropLeft, cropTop
	 * @param updateImg the image element that should receive live updating.
	 */
	newCrop: function(file, updateImage, fromControl, callback, scope) {
		this.scope = scope;
		if(this.crop) {
			this.crop.destroy();
			this.crop = null;
			this.imageEl.dom.src = "/images/blank.gif";
			Ext.get("result-image").dom.src = "/images/blank.gif";
			this.width = 400;
			this.height = 300;
		}
		this.file = file;
		this.toggleLoading(true);
        this.preloader = new Image();
        this.preloader.onload = function() {
            this.file.height = this.preloader.height;
			this.file.width = this.preloader.width;
			this.ready = true;
			// clean up to prevent memory leak in IE
            this.preloader.onload = '';

			/*
			if(Ext.isIE || Ext.isOpera)
				this.onLoad.defer(500, this);
			else
				this.onLoad();
			*/
			// It turns out that the problems loading can be caused by network speeds and effects all browsers
			//this.onLoad.defer(1000, this);
			this.onLoad();
        }.createDelegate(this);
		this.preloader.src = this.file.url;

		this.position(false);
		this.results.setBox(updateImage.getBox());
		this.show(fromControl, callback);
	},

	position: function(animate) {
		if(this.control) {
			this.el.setSize(this.width, this.height, animate);
//			this.el.setSize(this.width, this.height, { anim: true, duration: .5 });
//			this.el.setWidth(this.width, { anim: true, duration: .1 });
//			this.el.setHeight(this.height, { anim: true, duration: .1 });
			//this.el.setWidth(this.width);
			//this.el.setHeight(this.height);
			//Ext.get("image-cropper").setSize(this.width, this.height);
			var left = this.control.getLeft() - ((this.width - this.control.getWidth()) / 2);
			if(left < 5)
				left = 5;

			var view = Ext.getBody().getViewSize();
			if(left + this.width > view.width - 5)
				left = view.width - this.width - 5;

			this.el.setLeft(left);
			this.el.setTop(this.control.getBottom() + 5);
		}
	},

	onLoad: function() {
		this.width = this.preloader.width + 25;
		this.height = this.preloader.height + 60;
		//this.position(false);
		this.position({
			anim: true,
			duration: .5,
			callback: function() {
				this.preloader = null;
				var results = Ext.get("result-image");
				results.dom.src = this.file.url;
				this.imageEl.dom.src = this.file.url;
				if(this.file.cropWidth == 0)
					this.file.cropWidth = this.file.width;
				if(this.file.cropHeight == 0)
					this.file.cropHeight = this.file.height;

				this.toggleLoading(false);
				this.toolbar.show();
				this.createCrop.defer(100, this);
			},
			scope: this
		});
	},


	createCrop: function() {
		var actual = {
			width: this.file.fullResWidth,
			height: this.file.fullResHeight
		};
		var desired = {
			width: this.file.width,
			height: this.file.height
		};


		var scale = this.getScaleFactor(actual, desired);

		var tempcrop = {
			width: this.file.cropWidth,
			height: this.file.cropHeight,
			top: this.file.cropTop,
			left: this.file.cropLeft
		};
//		console.log("crop scale factor: " + scale);
//		console.log("actual crop: " + tempcrop.width + " x " + tempcrop.height + " " + tempcrop.left + ", " + tempcrop.top);
		var adjustedCrop = this.scale(scale, tempcrop);
//		console.log("scaled crop: " + adjustedCrop.width + " x " + adjustedCrop.height + " " + adjustedCrop.left + ", " + adjustedCrop.top);
		
		this.crop = new YAHOO.widget.ImageCropper(this.imageEl.id, {
            initialXY: [adjustedCrop.left, adjustedCrop.top],
			initWidth: adjustedCrop.width,
			initHeight: adjustedCrop.height,
			minWidth: 120,
			minHeight: 90,
			ratio: true,
			status: false,
            keyTick: 5,
            shiftKeyTick: 50
        });

		this.updateResults();

		this.crop.on('moveEvent', function() {
			this.updateResults();
		}.createDelegate(this));
	},

	updateResults: function() {
		var region = this.crop.getCropCoords();
		var image = Ext.get("result-image");
		var ratio = 1;

		if((this.file.width * 90) > (this.file.height * 120)) {
			// width will be used as criterion for resize to low resolution image
			ratio = 120 / region.width;

		} else {
			ratio = 90 / region.height;
			// Height will be used as criterion for resize to low resolution image

		}

//		ratio = 120 / region.width;

		image.setTop('-' + (region.top * ratio));
		image.setLeft('-' + (region.left * ratio));

		image.setWidth(this.file.width * ratio);
		image.setHeight(this.file.height * ratio);
		
//		this.actualCrop();
	},

	getScaleFactor: function(actual, desired) {
		if(actual.width == desired.width && actual.height == desired.height)
			return 1;

		if(actual.width + actual.height > desired.width + desired.height) {
			// scale down
			if((actual.width * desired.height) > (actual.height * desired.width)) {
				ratio = desired.width / actual.width;
			} else {
				ratio = desired.height / actual.height;
			}

		} else {
			// scale up
			if((actual.width * desired.height) > (actual.height * desired.width)) {
				ratio = actual.width / desired.width;
			} else {
				ratio = actual.height / desired.height;
			}
		}
		return ratio;
	},

	scale: function(ratio, dimensions) {
		var d = {
			width: dimensions.width * ratio,
			height: dimensions.height * ratio,
			top: dimensions.top * ratio,
			left: dimensions.left * ratio
		};
		return d;
	},

	actualCrop: function() {

		var region = this.crop.getCropCoords();
		var ratio = 1;

		if(this.file.width == this.file.fullResWidth && this.file.height == this.file.fullResHeight)
			return region;

		if((this.file.width * this.file.fullResHeight) > (this.file.height * this.file.fullResWidth)) {
			ratio = this.file.fullResWidth / this.file.width;

		} else {
			ratio = this.file.fullResHeight / this.file.height;
			// Height will be used as criterion for resize to low resolution image
		}

//		console.log("Full Res dimensions: " + this.file.fullResWidth + " x " + this.file.fullResHeight);
//		console.log("Crop Res dimensions: " + this.file.width + " x " + this.file.height);
//		console.log("Ratio is: " + ratio);

//		console.log("Actual Crop size: " + region.width + " x " + region.height + " (" + region.left + " x " + region.top + ")");
		var width = region.width * ratio;
		var height = region.height * ratio;
		var left = region.left * ratio;
		var top = region.top * ratio;
//		console.log("Scaled Crop size: " + width + " x " + height + " (" + left + " x " + top + ")");

		return { width: width, height: height, left: left, top: top };
	},

	toggleLoading: function(onoff, cb) {
		//var div = Ext.get("image-cropper");
		//var loading = Ext.DomQuery.selectNode('div.image-loading', this.el);
		if(!this.loading) {
			this.loading = Ext.DomHelper.append(this.el, { cls: 'image-loading', children: [
				{ cls: 'image-loading-indicator' }
				]}, true);
		}
		if(onoff) {
			this.loading.setVisible(true);
			if(typeof cb == 'function') cb();
		} else {
			var fn = function() {
				this.loading.clearOpacity();
				if(typeof cb == 'function') cb();
			}.createDelegate(this);

//			this.loading.setVisible(false, { anim: true, cb: fn });
			this.loading.setVisible(false);
		}
	},

	onRender: function(container, position) {
		Flowz.ImageCropper.superclass.onRender.call(this, container, position);

		this.el = Ext.DomHelper.append(Ext.getBody(), { id: 'image-cropper', cls: 'image-cropper yui-skin-sam x-hidden', children:[
			{ tag: 'div', cls: 'image-container', children: [
				{ tag: 'img', cls: 'image-cropper-image'  }
			]},

			{ tag: 'div', cls: 'image-cropper-toolbar' }
		]}, true);
		//div.center();

		this.results = Ext.DomHelper.append(Ext.getBody(), { tag: 'div', id: 'results-container', cls: 'x-hidden', children: [
			{ tag: 'div', id: 'results', children: [
				{ tag: 'img', id: 'result-image' }
			]}
		]}, true);

		this.imageEl = this.el.child("img");

		this.toolbar = this.el.child("div.image-cropper-toolbar");
		this.toolbar.hide();
		//var ok = new Ext.tek.MiniButton({ renderTo: toolbar, sprite:	 '/scripts/extjs/resources/images/default/tek/btn-yes-small-sprite.png'});
		var ok = new Flowz.MiniButton({ renderTo: this.toolbar, sprite:	 '/images/file-control/btn-save-sprite.png',
												width: 51, height: 26, posLeft: -51});
		//var cancel = new Ext.tek.MiniButton({ renderTo: toolbar, sprite: '/scripts/extjs/resources/images/default/tek/btn-no-small-sprite.png'});
		var cancel = new Flowz.MiniButton({ renderTo: this.toolbar, sprite: '/images/file-control/btn-save-sprite.png',
												width: 51, height: 26, posLeft: 0});

		//Ext.DomHelper.append(toolbar, { tag: 'div', style: 'clear: both;'});
		cancel.on('click', function() {
			this.cancel();
		}, this);

		ok.on('click', function() {
			this.save();
		}, this);

		this.proxy = this.el.createProxy();
		this.proxy.setStyle('display', 'none');
		this.proxy.enableDisplayMode('block');
		this.isOpen = false;
	},

	save: function() {
		if(this.callback) {
			// top, left, height, width and image url
			this.callback.call(this.scope, this.file, this.actualCrop(), this.crop.getCropCoords());
		}
		this.hide(this.curTarget);
	},

	cancel: function() {
		if(this.onHide) {
			this.onHide(this.file);
		}
		if(this.isOpen) {
			//this.el.puff({useDisplay: true});
			this.el.setVisibilityMode(Ext.Element.DISPLAY);
			this.el.hide();
			this.isOpen = false;
			this.results.hide();
		}
	},

	show: function(target, callback) {
		this.results.show();
		if(this.isOpen) {
			return;
		}

		this.el.removeClass("x-hidden");
		this.results.removeClass("x-hidden");

		if(callback)
			this.callback = callback;

		if(target) {
			// push down the page in case we are at the bottom
			this.curTarget = target;
			this.proxy.show();
			this.proxy.setBox(target.getBox());
			this.proxy.setOpacity(0);
			var b = this.el.getBox(false);
			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);
		}
		this.isOpen = true;
	},

	hide: function(target, anim) {
		this.cancel();
		/*
		if(this.onHide) {
			this.onHide(this.file);
		}
		this.isOpen = false;
		this.proxy.hide();
		this.results.hide();
		if(target) {
			this.proxy.show();
			this.proxy.setBox(this.el.getBox());
			this.proxy.setOpacity(1);
			var b = target.getBox(false);
			b.scope = this;
			b.duration = .25;
			b.easing = 'easeNone';
			b.opacity = 0;
			b.block = true;
			b.callback = this.afterHide;
			b.useDisplay = true;
			this.proxy.shift(b);
			this.el.hide();
		} else {
			this.el.hide({anim: true, duration: .15});
		}
		*/
	},

	afterShow: function() {
		this.proxy.hide();
		this.el.setStyle('display', 'block');
		//this.el.setWidth(400);
		//this.el.setHeight(300);
		this.el.show();
	},

	afterHide: function() {
		this.proxy.hide();
	},

	frame: function() {
		this.el.frame(arguments);
	},

	getWidth: function() {
		return this.el.getWidth();
	},

	getHeight: function() {
		return this.el.getHeight();
	},

	getTop: function() {
		return this.el.getTop();
	},

	getLeft: function() {
		return this.el.getLeft();
	},

	setTop: function(top) {
		this.el.setTop(top);
	},

	setLeft: function(left) {
		this.el.setLeft(left);
	},

	moveTo: function(left, top, animate) {
		this.el.moveTo(left, top, animate);
	}

});
Ext.namespace("Flowz");

/**
 * Class that will check asynchronously for the processing of a file to be finished.
 *
 * Note: For this to work correctly, the image being swapped out needs to have a parent container div that
 * will match the size of the image.  (Otherwise, the progress graphic is messed up and everything collapses on swap)
 *
 * @param config
 *  - id (id of the file to check)
 *  - imageId (id of the image node on the page that should be updated with status.)
 *  - type (the type of preview to check for (FACE, THUMB, etc.) empty to specify raw file)
 *  - onComplete (a function that will be called with the processing is complete)
 *  - scope (the scope to execute onComplete with)
 *  - interval (amount of time between checks to the server, defaults to 3 seconds)
 */
Flowz.FileStatus = function(config) {
    Ext.apply(this, config);
    Flowz.FileStatus.superclass.constructor.call(this, config);

	if(this.type != "")
		this.checkUrl = "/files/" + this.id + "/1/" + this.type + "/view/preview.jpg?bypassDefault=true";
	else
		this.checkUrl = "/files/" + this.id + "/1/view/preview.jpg?bypassDefault=true";

	var el = Ext.get(this.imageId);
	if(el == null) {
		alert("Can't find image to monitor: " + this.imageId);
		return;
	}

	this.container = Ext.DomHelper.insertFirst(el.parent(), { cls: 'info-container'}, true);
	//Ext.DomHelper.overwrite(this.container, { tag: 'span', html: ' Generating previews...'});

	Ext.DomHelper.overwrite(this.container, [{ tag: 'img', src: "/images/icon-loading-thumb.gif", width: 16, height: 16 },
						{ tag: 'span', html: ' Processing File...' }]);

//	this.run.defer(100, this, [0]);
	this.run.defer(2000, this, [0]);
};

Flowz.FileStatus = Ext.extend(Flowz.FileStatus, Ext.util.Observable, {
	interval: 3000,
	max: 20,
	width: 120,
	height: 90,

	run: function(count) {
		if(count == undefined)
			count = 0;
		if(count > this.max)
			return;
		count++;
		Ext.Ajax.request({
			url: this.checkUrl,
			success: this.swapForThumb.createDelegate(this),
			failure: function() {
				this.run.defer(this.interval, this, [ count ]);
			},
			scope: this

		});
	},

	swapForThumb: function() {
		//var container = Ext.DomQuery.selectNode("div.x-file-preview:first-child", file.cell.dom);
		var image = Ext.get(this.imageId);
		var newEl;
		
		if(!image) {
			//console.log("could not find image!");
		} else {
			//console.log("updating div");
			if(this.container) {
				//this.container.hide({ anim: true, callback: this.container.remove.createDelegate(this.container)});
				this.container.remove();
			}
			newEl = this.crossFade(image, { tag: 'img', id: 'thumb-' + this.id, src: this.checkUrl, cls: 'x-hidden', width: this.width, height: this.height });
		}


	},

	crossFade: function(elout, elin, permanent) {
		elout = Ext.get(elout);
		var parent = elout.parent();
		elout.remove();
		elin = Ext.DomHelper.insertFirst(parent, elin, true);
		elin.removeClass("x-hidden");
		elin.show({
			callback: this.complete.createDelegate(this, [elin, permanent]),
			anim: true
		});
		return elin;
	},

	complete: function(elin, permanent) {
		if(this.onComplete) {
			this.onComplete({ id: this.id, el: elin });
		}
	}
});
