/**
*	This file represents the common Javascript functionality
*	for the data form manager.
*/

	/**
	*	This function is used to automatically 
	*	display an IFRAME when a user selects "New" on a dropdown
	*	box.  This will set the CSS to display the 'elem_id' and 
	*	set the src on the iframe_id to iframe_src.  If new is not
	*	selected in the dropdown then it will attempt to execute
	*	the code passed to post_eval.
	*	
	*	@param sel object -the <Select> box in question
	*	@param elem_id string -the id of the element to be hidden/shown
	*	@param iframe_id string -the id of the IFRAME in question
	*	@param iframe_src string -the url of what should be loaded into the IFRAME.
	*	@param post_eval string -javascript code to execute if '_new' is not selected.
	*	@param force boolean - true force the 'new' value
	*/
	function dfm_showNewIframe( sel, elem_id, iframe_id, iframe_src, post_eval,force)
	{
		
		if (force == null)
			force = false;
		
		// get the element and iframe in question
		elem = document.getElementById(elem_id);
		iframe = document.getElementById(iframe_id);
		
		if (elem == null || iframe == null)
		{
			alert('JavaScript Error.  Please upgrade to a supported browser.');
			return;
		}
		
		// determine if new was selected ------------
		if (force)
		{
			sel.selectedIndex = 0;
			new_sel = true;
		}
		else
		{
			new_sel = false;
			for (i = 0; i < sel.options.length; ++i)
			{
				if (i == sel.selectedIndex && sel.options[i].value == '_new')
				{
					new_sel = true;
					break;
				}
			}
		}
		
		if (new_sel)
		{
			// new was selected
			elem.style.display = dfm_displayType(elem);
			iframe.src = iframe_src;
			return true;
		}
		else
		{
			// new not selected
			elem.style.display = 'none';
			eval(post_eval);	
			return false;
		}
	}
	
	/**
	*	This function will foricibly select the '_new' field from the
	*	specified field and then proceed to show the iframe in question.
	*	
	*	@param form_name string -name of the form
	*	@param field_name string -name of the <select> box
	*	@param elem_id string -the id of the element to be hidden/shown
	*	@param iframe_id string -the id of the IFRAME in question
	*	@param iframe_src string -the url of what should be loaded into the IFRAME.
	*	@param post_eval string -javascript code to execute if '_new' is not selected.
	*	@param force boolean - true set the value to empty and force it
	*/
	function dfm_force_showNewIframe(form_name,field_name,elem_id, iframe_id, iframe_src, post_eval, force)
	{
		frm = document.forms[form_name];
		sel = frm[field_name];
		
		if (!force)
		{
			for (i = 0; i < sel.options.length; ++i)
			{
				if (sel.options[i].value == '_new')
				{
					sel.selectedIndex = i;
					break;
				}
			}
		}
		
		dfm_showNewIframe(sel,elem_id, iframe_id, iframe_src, post_eval,force);
	}
	
	/**
	*	This function will clear the input field
	*	if its current value is the default value
	*	
	*	@param inp -the input text box in question
	*	@param default_val -the default value that appears in the box
	*/
	function dfm_onFocusClear(inp,default_val)
	{
		if (inp.value == default_val)
			inp.value = '';	
	}
	
	/**
	*	This function will reset the input field
	*	to its default value if it is empty.
	*	
	*	@param inp -the input text box in question
	*	@param default_val -the default value that appears in the box
	*/
	function dfm_onBlurReset(inp,default_val)
	{
		if (inp.value == '')
			inp.value = default_val;	
	}
	
	/**
	*	This function will resubmit the form
	*	using an 'actn' of 'refresh'.  The actual page
	*	must be able to handle this type of refresh.
	*
	*	@param form_name -the name of the form from the page to actually refresh
	*/
	function dfm_refreshForm(form_name)
	{
		frm = document.forms[form_name];
		actn = frm.actn;
		
		if (actn == null)
		{
			alert("Application Error: This form (" +form_name+ ") does not allow for refreshing.");
			return;
		}
		
		actn.value = 'refresh';
		frm.submit();
	}
	
	/**
	*	This function will add a new <OPTION> to the select box
	*	in question, and select it if necessary.
	*	
	*	@param form_name -the name of the form for which this field belongs.
	*	@param field_name - the field name of the select box
	*	@param add_id	- the value that will be sent be the form upon submission
	*	@param add_txt - the value that will appear to the user
	*	@param doSelect - boolean (true = select the new option, false = do not select)
	*/
	function dfm_addOption(form_name,field_name,add_id,add_text,doSelect)
	{
		frm = document.forms[form_name];
		sel = frm[field_name];
		
		if (sel.type.indexOf('select') >= 0)
		{
			cnt = sel.options.length;
			sel.options[cnt] = new Option(add_text,add_id,false,doSelect);
			
			if (doSelect)
			{
				sel.selectedIndex[cnt];
				
				if (sel.onchange != '')
					sel.onchange();
			}
		}
		else
		{
			alert("Application Error: This type (" +sel.type+ ") is not supported by this function.");
			return;
		}
	}
	
	/**
	*	This function will abort an inline iframe that is
	*	generated to solicit input when a certain select box 
	*	item is selected.
	*	
	*	@param form_name -the name of the form for which this field belongs.
	*	@param field_name - the field name of the select box
	*	@param elem_id string -the id of the element to be hidden/shown
	*	@param orig_id	- the value to select from the dropdown
	*/
	function dfm_abortIframe(form_name,field_name,elem_id,orig_id)
	{
		frm = document.forms[form_name];
		sel = frm[field_name];
		elem = document.getElementById(elem_id);
		
		if (elem == null)
		{
			alert('JavaScript Error.  Element not found.');
			return;
		}
		
		for (i = 0; i < sel.options.length; ++i)
		{
			if (sel.options[i].value == orig_id)
			{
				sel.selectedIndex = i;
				break;
			}
		}
		
		elem.style.display = 'none';
	}
	
	/**
	*	This function will determine the type of CSS 'display'
	*	value that should be set for the element to be made visibie.
	*	
	*	@param elem object - node in the DOM to be displayed
	*/
	function dfm_displayType(elem)
	{
		tag_type = elem.nodeName.toUpperCase();
			
		if (tag_type == 'TR' && !document.all)
			return 'table-row';
		else
			return 'block';
	}
	
	/**
		todo ...
	*/
	function dfm_listProcess(sel,form_name,parnt_info,new_info,other_info,orig_js)
	{
		frm = sel.form;
		
		// has children to show/hide -------
		if (parnt_info != null)
		{
			dfm_parentShowHide(sel,form_name,parnt_info,false);
		}
		
		if (other_info != null)
		{
			qt = df_enter_other(sel,other_info[0],other_info[1]);
			if (qt)
				return;
		}
		
		if (new_info != null)
		{
			qt = dfm_showNewIframe( sel, new_info[0], new_info[1], new_info[2], '', false);
			if (qt)
				return;
		}
		
		if (orig_js != '')
			eval(orig_js);
	}
	
	/**
		This function will show or hide a row in the form depending
		on if the value of the parent is selected.
	*/
	function dfm_parentShowHide(sel,form_name,parnt_info,force_hide, recursing)
	{
		var frm = sel.form;
		var seld_value = [];
		
		// get selected value -----------
		if (sel.type.indexOf('select') >= 0)
			seld_value = [sel.options[sel.selectedIndex].value];
		else if (sel.type.indexOf('radio') >= 0)
			seld_value = [sel.value];
		else if (sel.type.indexOf('checkbox') >= 0)
		{
			var junk = sel.form[sel.name];
			var j = 0;
			for (var i = 0; i < junk.length; ++i)
			{
				if (junk[i].checked)
					seld_value[j++] = junk[i].value;
			}
		}
					
		var elem = null;
		
		for (var field_name in parnt_info)
		{
			var row_id = "df." +form_name+ "." +field_name;
			elem = document.getElementById(row_id);
			
			if (elem == null)
				continue;
			
			var seld = false;
			if (! force_hide)
			{
				for (var i = 0; i < parnt_info[field_name].length; ++i)
				{
					for (var j = 0; j <seld_value.length; ++j)
					{
						if (parnt_info[field_name][i] == seld_value[j])
						{
							seld = true;
							break;
						}
					}
					
					if (seld)
						break;
				}
			}
			
			var tryn = new Array();
			tryn[0] = form_name+'['+field_name+'][values]';
			tryn[1] = tryn[0]+ '[]';
			
			for (var i = 0; i < tryn.length; ++i)
			{
				sel2 = frm[tryn[i]];
				if (sel2 != null)
					break;
			}
			
			// catch the case of a radio button --------
			if (sel2 != null && sel2.type == null)
			{
				for (var i; i < sel2.length; ++i)
				{
					if (sel2[i].type == 'radio' && sel2[i].checked)
					{
						sel2 = sel2[i];
						break;
					}
				}
			}
			
			if (seld)
			{
				elem.style.display = dfm_displayType(elem);
				
				// special case ... catch when something is on its own row --
				elem2 = document.getElementById(row_id+ '.own');
				if(elem2 != null)
					elem2.style.display = dfm_displayType(elem2);
					
				if (sel2 != null && sel2.onchange != null)
					sel2.onchange();
			}
			else
			{
				elem.style.display = 'none';
				
				// special case ... catch when something is on its own row --
				elem2 = document.getElementById(row_id+ '.own');
				if(elem2 != null)
					elem2.style.display = 'none';
					
				if (df_prnt_map[field_name] != null)		// auto hide children --
				{
					if (sel2 == null)
						sel2 = sel;
						
					dfm_parentShowHide(sel,form_name,df_prnt_map[field_name],true, true);
				}
			}
		}

		if ((typeof recursing) == 'undefined' || !recursing) {
			if ((typeof openLightbox) == 'object' 
				 && (typeof resizeLightbox) == 'function') {
				resizeLightbox();
			}
		}
	}

	function df_onoff_input(inp,tog_fld)
	{
		frm = inp.form;
		cb = frm[tog_fld];
		
		if (inp.value != '' && !cb.checked)
			cb.checked = true;
				
	}
	
	function df_other_input(inp,tog_fld)
	{
		frm = inp.form;
		cb = frm[tog_fld];
		
		if (inp.value != '')
		{
			for (var i = 0; i < cb.length; ++i)
			{
				if (cb[i].value == '__OTHER__')
					cb[i].checked = true;
			}
		}
	}
	
	function df_enter_other(sel, div_name, field_name)
	{
		frm = sel.form;
		inp = frm[field_name];
		elem = document.getElementById(div_name);
		
		if (elem == null)
			return;
			
		val = sel.options[sel.selectedIndex].value;
		
		if (val == "__OTHER__")
		{
			elem.style.display = 'block';
			if (inp != null)
				inp.focus();
			return true;
		}
		else
		{
			elem.style.display = 'none';
			return false;
		}
	}
	
	
	/** For the phone/fax  -----------------------------------------*/
	
	var nbr_just_jumped = false;
	var nbr_jumped_to = '';
	var nbr_orig_value = '';
	
	function df_phne_auto_jump(from_fld,to_fld,size,dew)
	{
		if (dew)
		{
			if ( ((from_fld.value.length == 0) || (from_fld.value == nbr_orig_value)) && (size > 0))
				return false;
				
			if (from_fld.value.length >= size)
			{
				if (size >= 0)
				{
					nbr_just_jumped = true;
					nbr_jumped_to = to_fld;
				}
				
				frm = from_fld.form;
				frm[to_fld].focus();
				frm[to_fld].select();
			}
			else
				nbr_just_jumped = false;
		}
		else
		{
			nbr_orig_value = from_fld.value;
			old_fld = 'document.forms.' +from_fld.form.name+ '[\"' +from_fld.name+ '\"]';
			var s = 'df_phne_auto_jump(' +old_fld+ ',\"' +to_fld+ '\",' +size+ ',true);';
			setTimeout(s,100);
			
			return true;
		}
	}
	
	function df_phne_undo_jump(from_fld,to_fld)
	{
		if ((nbr_just_jumped) && (df_phne_fld_order(to_fld.name) > df_phne_fld_order(nbr_jumped_to)))
		{
			nbr_just_jumped = false;
			
			old_fld = 'document.forms.' +to_fld.form.name+ '[\"' +to_fld.name+ '\"]';
			setTimeout('df_phne_auto_jump(' +old_fld+ ',\"' +from_fld+ '\",-1,true);',100);
		}
	}
	
	function df_phne_fld_order(fld)
	{
		if (fld.indexOf('areacode') > 0)
			return 1;
		if (fld.indexOf('number1') > 0)
			return 2;
		if (fld.indexOf('number2') > 0)
			return 3;
		
		return 4;
	}
	
	function df_verifyDollars(fld,whole)
	{
		if (fld.value == '')
			return;
			
		var val = fld.value.replace(/,/g,'');
		
		if (!whole)
			val = parseFloat(val);
		else
		{
			val = parseInt(val);
		}
				
		if (isNaN(val))
		{
			alert('Please enter a valid dollar amount');
			setTimeout("fld = document.forms['" +fld.form.name+ "']['" +fld.name+ "'];fld.focus();fld.select();",100);
			return;
		}
		
		var out = '';
		var start = 0;
		if (!whole)
		{
			val = new String(Math.round(val*100)/100);
		
			if (val.indexOf(".") == -1)
				val = val+ ".00";
				
			out = val.substring(val.length-3);
			start = val.length-4;
		}
		else
		{
			val = new String(val);
			start = val.length-1;
		}
			
		var d = 0;
		for (var i = start; i >= 0; --i)
		{
			if (d == 3)
			{
				out = ',' +out;
				d = 0;
			}
			
			out = val.charAt(i)+out;
			d++;
		}
		
		fld.value = out;
		
	}
	

	function df_verifyNumber(fld, whole, pos_only)
	{
		if (fld.value == '')
			return;
			
		var val = fld.value.replace(/,/g,'');
		
		if (!whole)
			val = parseFloat(val);
		else
		{
			val = parseInt(val);
		}
				
		if (isNaN(val))
		{
			alert('Please enter a number');
			setTimeout("fld = document.forms['" +fld.form.name+ "']['" +fld.name+ "'];fld.focus();fld.select();",100);
			return;
		}

		if (pos_only && val < 0 ) 
		{
			alert('Please enter a positive number');
			setTimeout("fld = document.forms['" +fld.form.name+ "']['" +fld.name+ "'];fld.focus();fld.select();",100);
			return;
		}
		
		//var out = '';
		//var start = 0;
		/*
		if (!whole)
		{
			val = new String(Math.round(val*100)/100);
		
			if (val.indexOf(".") == -1)
				val = val+ ".00";
				
			out = val.substring(val.length-3);
			start = val.length-4;
		}
		else
		{
			val = new String(val);
			start = val.length-1;
		}
		*/
			
		/*
		var d = 0;
		for (var i = start; i >= 0; --i)
		{
			if (d == 3)
			{
				out = ',' +out;
				d = 0;
			}
			
			out = val.charAt(i)+out;
			d++;

		}
		*/
		
		fld.value = val;	
	}



	function df_hideCommas(fld)
	{
		var val = fld.value.replace(/,/g,'');
		fld.value = val;
	}
	
	function df_changePwd(fld,change_fld_name,div_id,required)
	{
		var frm = fld.form;
		var change_fld = frm[change_fld_name];
		var elem = document.getElementById(div_id);
		
		if (elem == null)
			return;
			
		if (fld.value == '')
		{
			if (required != 'Y')
			{
				elem.style.display = 'none';
				change_fld.value = 'N';	
			}
		}
		else
		{
			elem.style.display = 'block';
			change_fld.value = 'Y';
			setTimeout("fld = document.forms['" +frm.name+ "']['" +div_id+ "'];fld.focus();fld.select();",100);
			
		}
	}
	
	function df_helpText_reset(div_id)
	{
		df_helpText(null,div_id,null,null);
	}
	
	function df_helpText(obj,div_id,content_id,url)
	{
		var elem = document.getElementById(div_id);
		if (elem == null)
			return false;
		
		// reset/hide the help window ----	
		if (obj == null)
		{
			elem.style.display = 'none';
			document.onclick = '';
			
			// ie-only
			df_helpText_hideDropdowns(false);
			return false;
		}
		
		// set a default value ------
		var celem = document.getElementById(content_id);
		celem.innerHTML = 'Acquiring Help Text <blink>...</blink>';
		
		// invoke the AJAX
		var err = 'Error: Unable to retrieve the help information.';
		var supported = ajax_sendRequest('ajax_simpleDynamicContent',new Array(content_id,err),'GET',url+"&xml=true");
		
		if (!supported)
		{
			// open new window ---
			helpwin = window.open(url,"helpwin","directories=no, dependant=yes, location=no, menubar=no, status=no, titlebar=no, toolbar=no, scrollbars=yes, resizable=yes",true);
			helpwin.resizeTo(250,400);
			helpwin.focus();
			
			return false;
		}
		
		// don't close when clicking on another help icon --
		document.onclick = '';
		
		var pos = js_getPosition(obj,true);
		
		var left = pos.x + pos.w + 1;
		var top = pos.y;
		var scroll_height = js_scrollHeight();
		
		elem.style.left = left+ "px";
		elem.style.top = top+ "px";
		elem.style.display = "block";
		elem.className = 'df_helpDiv';
		
		var right = left + elem.clientWidth;
		var bottom = top + elem.clientHeight;
		
		// see if we need to move up or scroll ---------------
		var real_bottom = js_getPosition(elem,false);
		var diff =  real_bottom.b - scroll_height;
		if (diff > 0)
		{
			elem.className = 'df_helpDiv2';
			up = elem.clientHeight;
			top = top - up;
			bottom = bottom - up;
		}
		else
		{	
			// see if we need to scroll ---------
			var screen_bottom = js_scrollTop() + js_clientHeight();
			diff = real_bottom.b - screen_bottom + 10;
			if (diff > 0)
				window.scrollBy(0,diff);
		}
		
		// don't close when clicking on the div directly ----
		s = "document.onclick = ''; setTimeout(\"document.onclick = new Function(\\\"df_helpText_reset('" +div_id+ "'); \\\"); \"); ";
		elem.onclick = new Function(s);
		
		// hide window when clicking anywhere else ----
		setTimeout("document.onclick = new Function(\"df_helpText_reset('" +div_id+ "');\"); ", 100);
		
		// IE-specific: hide <select> boxes -----------
		var elem_pos = {'x':left,'y':top,'r':right,'b':bottom};
		df_helpText_hideDropdowns(true,elem_pos);
		
		return false;
	}
	
	function df_upper_first(txt)
	{
		var arr = txt.value.split(" ");
		var out = '';
		for (var i = 0; i < arr.length; ++i)
		{
			if (i > 0)
				out = out+ " ";
			
			out = out+ arr[i].substring(0,1).toUpperCase()+ arr[i].substring(1);
		}
			
		txt.value = out;
	}
	
	/**
	*	This is IE-specific that will hide all the <SELECT> boxes
	*	when they are being masked by a help text div.
	*	
	*	This is to fix an IE bug that they always show through.
	*/
	function df_helpText_hideDropdowns(hide,pos)
	{
		// for IE only -------
		if (! document.all)
			return;
		
		// re-display all hidden boxes --------------------
		if (! hide)
		{
			if (typeof df_helpDropdowns	== 'object')
			{
				for(fn in df_helpDropdowns)
				{
					for(nme in df_helpDropdowns[fn])
					{
						dd = document.forms[fn][nme];
						dd.style.visibility = "visible";	
					}	
				}
			}
			
			df_helpDropdowns = new Object();
			return;
		}
		
		 if (typeof df_helpDropdowns	!= 'object')
		 	df_helpDropdowns = new Object();
		 	
		var dropdowns = document.getElementsByTagName("SELECT");
		var fudge_factor = 20;
		pos.y -= fudge_factor;
		pos.b += fudge_factor;
		
		for (var i = 0; i < dropdowns.length; ++i)
		{
			var dd = dropdowns[i];
			var dd_pos = js_getPosition(dd,true);
			
			var in_x = (dd_pos.x >= pos.x && dd_pos.x < pos.r);
			in_x = in_x || (dd_pos.r >= pos.x && dd_pos.r < pos.r);
			var in_y = (dd_pos.y >= pos.y && dd_pos.y < pos.b);
			in_y = in_y || (dd_pos.b >= pos.y && dd_pos.b < pos.b);
			
			if (in_x && in_y)
			{
				if (typeof df_helpDropdowns[dd.form.name] != 'object')
					df_helpDropdowns[dd.form.name] = new Object();
					
				df_helpDropdowns[dd.form.name][dd.name] = true;
				dd.style.visibility = "hidden";
			}
		}
	}
	


/**
 *
 * Used to limit a textarea/text input to a certain number of chars.
 * set this as part of onKeyUp event
 *
 *
 * limitField - the field to limit the number of chars
 * limitNum - number of chars
 * displayField - id of a span or paragraph to display message in (optional)
 * startWarning - optional - at how many chars should warning message be displayed.
 *
 *
 */

	function df_limitText(limitField, limitNum, displayField, startWarning) {
		if (limitField.value.length > limitNum) {
			limitField.value = limitField.value.substring(0, limitNum);
		}

		if (displayField) {
			field = document.getElementById(displayField);

			if (field && (!startWarning || limitField.value.length >= startWarning) ) {
				var numLeft = limitNum - limitField.value.length;
				field.innerHTML = "Please limit your entry to "+limitNum+" characters. "+numLeft+" characters left.";
			}
			else if (field) {
				field.innerHTML = "";
			}
		}
	}







	/**
		Get the top and left position of the object.
	*/
	function js_getPosition(obj,relative)
	{
		var o = new Object();
		o.x = js_getPosition_R(obj,'offsetLeft',relative);
		o.y = js_getPosition_R(obj,'offsetTop',relative);
		o.w = obj.clientWidth;
		o.h = obj.clientHeight;
		
		if (js_check_browser(['safari','konq']))
			o.w += 10;
			
		o.r = o.x + o.w;
		o.b = o.y + o.h;
		return o;
	}
	
	function js_getPosition_R(obj,offset_dir,relative)
	{
		var curleft = 0;
		if (obj.offsetParent)
		{
			while (1)
			{
				if (relative && obj['offsetLeft'] <= 0 && obj['offsetTop'] <= 0)
					break;
					
				curleft += obj[offset_dir];
				if (!obj.offsetParent)
					break;
				obj = obj.offsetParent;
			}
		}
		else if (offset_dir == 'offsetLeft' && obj.x)
			curleft += obj.x;
		else if (offset_dir == 'offsetTop' && obj.y)
			curleft += obj.y;
			
		return curleft;
		
	}
	
	function js_scrollTop()
	{
		return document.body.scrollTop;	
	}
	
	function js_scrollHeight()
	{
		return document.body.scrollHeight;	
	}
	
	function js_clientHeight()
	{
		var myHeight = 0;
		if( typeof( window.innerWidth ) == 'number' ) {
		//Non-IE
		myHeight = window.innerHeight;
		} else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
		//IE 6+ in 'standards compliant mode'
		myHeight = document.documentElement.clientHeight;
		} else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
		//IE 4 compatible
		myHeight = document.body.clientHeight;
		}
	
		return myHeight;
	}
	
	function js_check_browser(str)
	{
		detect = navigator.userAgent.toLowerCase();
		if (typeof str == 'object')
		{
			for (var i in str)
			{
				place = detect.indexOf(str[i])+1;
				if (place)
					return 1;
			}
			return 0;
		}
		
		place = detect.indexOf(str)+1;
		return place;
	}















//==============================
// Javascript for swfupload upload
// field and progress bar
//==============================


var swfu_phpsessid;
var swfu_app_form_id;
var swfu_edit = new Array();
var swfu_ready = new Array();



// must call this before user can upload
// call on load of window
function df_swfu_initialize(sessid, form_id, field_id)
{
	$('swf_field_'+ field_id).style.display= 'block';
	$('swf_js_on_' + field_id).value= '1';

	swfu_phpsessid = sessid;
	swfu_app_form_id = form_id;
	
	swfu_edit[field_id] =  get_swfu_object(field_id)


	df_swfuToggleDelete(field_id);
}

function df_swfuToggleDelete(field_id)
{
	var delete_file;
	// delete field may not be there,
	// if required field
	if (! $('swf_delete_span_'+field_id)) {
		return;
	}

	// required fields don't have a delete option
	if (!$('swf_delete_file_'+field_id))
		return;

	if ( ($('swf_upload_id_'+field_id).value == '')  && 
			($('swf_filename_hidden_'+field_id).value == '') ) {
			// nothing to delete
			$('swf_delete_file_'+field_id).checked = false;
			$('swf_delete_span_'+field_id).style.display = 'none';
	}
	else {
		$('swf_delete_span_'+field_id).style.display = 'inline';
	}



	delete_file = $('swf_delete_file_'+field_id).checked;

	if (delete_file) {
		$('swf_status_'+field_id).className = 'swf_deleted';
	}
	else {
		$('swf_status_'+field_id).className='';
	}

	if (swfu_ready[field_id]) {
		try {
			swfu_edit[field_id].setButtonDisabled(delete_file);
		} catch (ex) {}
	}
}


function df_fileQueueError(file, errorCode, message) {

	try {
		if (errorCode === SWFUpload.QUEUE_ERROR.QUEUE_LIMIT_EXCEEDED) {
			alert("You have attempted to queue too many files.\n" + (message === 0 ? "You have reached the upload limit." : "You may select " + (message > 1 ? "up to " + message + " files." : "one file.")));
			return;
		}

		var progress = new FileProgress(file, this.customSettings.progressTarget);
		progress.setError();
		progress.toggleCancel(false);

		switch (errorCode) {
		case SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT:
			progress.setStatus("File is too big.");
			this.debug("Error Code: File too big, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
			break;
		case SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE:
			progress.setStatus("Cannot upload Zero Byte files.");
			this.debug("Error Code: Zero byte file, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
			break;
		case SWFUpload.QUEUE_ERROR.INVALID_FILETYPE:
			progress.setStatus("Invalid File Type.");
			this.debug("Error Code: Invalid File Type, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
			break;
		default:
			if (file !== null) {
				progress.setStatus("Unhandled Error");
			}
			this.debug("Error Code: " + errorCode + ", File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
			break;
		}
	} catch (ex) {
        this.debug(ex);
    }

	field_id = this.customSettings.field_id;
	//$('swf_field_'+field_id).setAttribute('class','swf_complete');
	$('swf_field_'+field_id).className='swf_complete';
	df_swfuToggleDelete(field_id);
}




function df_fileQueued(file)
{


	field_id = this.customSettings.field_id 
	//$('swf_field_'+field_id).setAttribute('class','swf_loading');
	$('swf_field_'+field_id).className = 'swf_loading';

	try {
		var progress = new FileProgress(file, this.customSettings.progressTarget);
		progress.setStatus("Pending...");
		progress.toggleCancel(true, this);

	} catch (ex) {
		this.debug(ex);
	}

}




function df_fileDialogComplete(selected, queued, total)
{


   this.startUpload();
   //return true;
}


function df_uploadError(file, errorCode, message)
{

	try {
		var progress = new FileProgress(file, this.customSettings.progressTarget);
		progress.setError();
		progress.toggleCancel(false);

		switch (errorCode) {
		case SWFUpload.UPLOAD_ERROR.HTTP_ERROR:
			if (message == 510)
				message = 'you must be logged in';

			if (message == 511)
				message = '511 configuration errror, contact admin';

			if (message == 512)
				message = '512 configuration errror, contact admin';

			progress.setStatus("Upload Error: " + message);
			this.debug("Error Code: HTTP Error, File name: " + file.name + ", Message: " + message);
			break;
		case SWFUpload.UPLOAD_ERROR.UPLOAD_FAILED:
			progress.setStatus("Upload Failed.");
			this.debug("Error Code: Upload Failed, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
			break;
		case SWFUpload.UPLOAD_ERROR.IO_ERROR:
			progress.setStatus("Server (IO) Error");
			this.debug("Error Code: IO Error, File name: " + file.name + ", Message: " + message);
			break;
		case SWFUpload.UPLOAD_ERROR.SECURITY_ERROR:
			progress.setStatus("Security Error");
			this.debug("Error Code: Security Error, File name: " + file.name + ", Message: " + message);
			break;
		case SWFUpload.UPLOAD_ERROR.UPLOAD_LIMIT_EXCEEDED:
			progress.setStatus("Upload limit exceeded.");
			this.debug("Error Code: Upload Limit Exceeded, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
			break;
		case SWFUpload.UPLOAD_ERROR.FILE_VALIDATION_FAILED:
			progress.setStatus("Failed Validation.  Upload skipped.");
			this.debug("Error Code: File Validation Failed, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
			break;
		case SWFUpload.UPLOAD_ERROR.FILE_CANCELLED:
			// If there aren't any files left (they were all cancelled) disable the cancel button
			//if (this.getStats().files_queued === 0) {
				//document.getElementById(this.customSettings.cancelButtonId).disabled = true;
			//}
			progress.setStatus("Cancelled");
			progress.setCancelled();
			break;
		case SWFUpload.UPLOAD_ERROR.UPLOAD_STOPPED:
			progress.setStatus("Stopped");
			break;
		default:
			progress.setStatus("Error: " + errorCode);
			this.debug("Error Code: " + errorCode + ", File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
			break;
		}
	} catch (ex) {
        this.debug(ex);
    }

	$('swf_upload_id_'+field_id).value = '';

	field_id = this.customSettings.field_id;
	//$('swf_field_'+field_id).setAttribute('class','swf_complete');
	$('swf_field_'+field_id).className = 'swf_complete';
	df_swfuToggleDelete(field_id);
}



function df_uploadSuccess(file, serverData) 
{
	// server gives us back OK <id> <url>

	parts = serverData.split(" ");
	field_id = this.customSettings.field_id;

	if (parts[0] == 'OK' ) {
		$('swf_filename_hidden_'+field_id).value = file.name;
		$('swf_upload_id_'+field_id).value = parts[1];
		filename_span = $('swf_filename_'+field_id);

		filename_span.removeChild(filename_span.childNodes[0]);
		filename_span.appendChild(document.createTextNode(file.name));
		//$('swf_field_'+field_id).setAttribute('class','swf_complete');
		$('swf_field_'+field_id).className='swf_complete';


		try {
			var progress = new FileProgress(file, this.customSettings.progressTarget);
			progress.setComplete();
			progress.setStatus("Complete.");
			progress.toggleCancel(false);

			// fire prototype event on document
			document.fire("swfupload:success", { file: file });
			
		} catch (ex) {
			this.debug(ex);
		}


	}

	df_swfuToggleDelete(field_id);
}

function handle_debug(message)
{
	win = $('swf_debug_win');
	if (win != null) {
		win.value += "\n----------------Next Message----------------------\n"+ message
	}
}


function df_uploadProgress(file, bytesLoaded, bytesTotal) {

	//var percent = Math.ceil((bytesLoaded / bytesTotal) * 100);
	field_id = this.customSettings.field_id;
	//myJsProgressBarHandler.setPercentage('pbar_'+field_id, 100 - percent);


	try {
		var percent = Math.ceil((bytesLoaded / bytesTotal) * 100);

		var progress = new FileProgress(file, this.customSettings.progressTarget);
		progress.setProgress(percent);
		progress.setStatus("Uploading...");
	} catch (ex) {
		this.debug(ex);
	}
}


function df_uploadStart(file) {
	return true;
}

function df_swfUploadLoaded()
{
	swfu_ready[this.customSettings.field_id] = true;
}


function get_swfu_object(field_id_param)
{
		
	var in_lightbox = false;

	try {
		if (typeof openLightbox == 'object' && openLightbox != null) {
			in_lightbox = true;
		}
	}
	catch (err){}

			var settings = {
				file_post_name: "filedata",	
				flash_url : "/system/modules/swfupload/flash/swfupload.swf",
				upload_url: "/system/modules/swfupload/upload.php",	// Relative to the SWF file
				post_params: {"PHPSESSID" : swfu_phpsessid,  'app_form': swfu_app_form_id},
				file_size_limit : "100 MB",
				file_types : "*.*",
				file_types_description : "All Files",
				file_upload_limit : 100,
				file_queue_limit : 0,
				
				custom_settings : {
					field_id : field_id_param,
					progressTarget : 'pbar_'+field_id_param,
					inLightbox: in_lightbox
				},
				debug: true,
				debug_handler: handle_debug,

				// Button settings
				button_image_url: "/system/images/xpupload61x22.png",	// Relative to the Flash file
				button_width: 61,
				button_height: 22,
				button_placeholder_id: 'swf_upload_button_' + field_id_param,


				file_queued_handler : df_fileQueued,
				file_queue_error_handler : df_fileQueueError,
				file_dialog_complete_handler : df_fileDialogComplete,
				upload_start_handler : df_uploadStart,
				upload_progress_handler : df_uploadProgress,
				upload_error_handler : df_uploadError,
				upload_success_handler : df_uploadSuccess,
				swfupload_loaded_handler : df_swfUploadLoaded
				//upload_complete_handler : uploadComplete,
				//queue_complete_handler : queueComplete	// Queue plugin event
			};


			var swfu =  new SWFUpload(settings);

			return swfu;

}




// from swfupload demo.

// Constructor
// file is a SWFUpload file object
// targetID is the HTML element id attribute that the FileProgress HTML structure will be added to.
// Instantiating a new FileProgress object with an existing file will reuse/update the existing DOM elements

function FileProgress(file, targetID) {
	//this.fileProgressID = file.id;
	
	//CHANGED:
	// Only one file progress bar on page
	
	this.fileProgressID = 'SWFU_Progress' ;
	this.file_id = file.id ;

	this.opacity = 100;
	this.height = 0;

	this.fileProgressWrapper = document.getElementById(this.fileProgressID);
	if (!this.fileProgressWrapper) {
		this.fileProgressWrapper = document.createElement("div");
		this.fileProgressWrapper.className = "progressWrapper";
		this.fileProgressWrapper.id = this.fileProgressID;

		this.fileProgressElement = document.createElement("div");
		this.fileProgressElement.className = "progressContainer";

		var progressCancel = document.createElement("a");
		progressCancel.className = "progressCancel";
		progressCancel.href = "#";
		progressCancel.style.visibility = "hidden";
		progressCancel.appendChild(document.createTextNode(" "));

		var progressText = document.createElement("div");
		progressText.className = "progressName";
		progressText.id= 'pb_file_name';
		progressText.appendChild(document.createTextNode(file.name));

		var progressBar = document.createElement("div");
		progressBar.className = "progressBarInProgress";

		var progressStatus = document.createElement("div");
		progressStatus.className = "progressBarStatus";
		progressStatus.innerHTML = "&nbsp;";

		this.fileProgressElement.appendChild(progressCancel);
		this.fileProgressElement.appendChild(progressText);
		this.fileProgressElement.appendChild(progressStatus);
		this.fileProgressElement.appendChild(progressBar);

		this.fileProgressWrapper.appendChild(this.fileProgressElement);

		document.getElementById(targetID).appendChild(this.fileProgressWrapper);
	} else {
		this.fileProgressElement = this.fileProgressWrapper.firstChild;
		$('pb_file_name').innerHTML = file.name;
	}

	this.height = this.fileProgressWrapper.offsetHeight;

}
FileProgress.prototype.setProgress = function (percentage) {
	this.fileProgressElement.className = "progressContainer green";
	this.fileProgressElement.childNodes[3].className = "progressBarInProgress";
	this.fileProgressElement.childNodes[3].style.width = percentage + "%";
};
FileProgress.prototype.setComplete = function () {
	this.fileProgressElement.className = "progressContainer blue";
	this.fileProgressElement.childNodes[3].className = "progressBarComplete";
	this.fileProgressElement.childNodes[3].style.width = "";
};

FileProgress.prototype.setError = function () {
	this.fileProgressElement.className = "progressContainer red";
	this.fileProgressElement.childNodes[3].className = "progressBarError";
	this.fileProgressElement.childNodes[3].style.width = "";

	var oSelf = this;
};

FileProgress.prototype.setCancelled = function () {
	this.fileProgressElement.className = "progressContainer";
	this.fileProgressElement.childNodes[3].className = "progressBarError";
	this.fileProgressElement.childNodes[3].style.width = "";

	var oSelf = this;
};

FileProgress.prototype.setStatus = function (status) {
	this.fileProgressElement.childNodes[2].innerHTML = status;
};

// Show/Hide the cancel button
FileProgress.prototype.toggleCancel = function (show, swfUploadInstance) {
	this.fileProgressElement.childNodes[0].style.visibility = show ? "visible" : "hidden";
	if (swfUploadInstance) {
		var fileID = this.file_id;
		this.fileProgressElement.childNodes[0].onclick = function () {
			swfUploadInstance.cancelUpload(fileID);
			return false;
		};
	}
};


		



