function onpageshow()
{
	var i,theForm,j;
	for (i=0;i<document.forms.length;i++)
	{
		theForm=document.forms[i];
		for (j=0;j<theForm.elements.length;j++)
		{
			if (theForm.elements[j].restoreOnShow) theForm.elements[j].disabled=false;
		}
	}
}

function checkFieldForBlankness(field)
{
	var value;
	if (field.nodeName.toLowerCase()=='select')
	{
		value=field.options[field.selectedIndex].value;
	} else
	{
		value=field.value;
	}

	if ((value=='') || (value=='****') || (value=="Make your post civil and relevant"))
	{
		window.alert("You did not fill in all fields on the form correctly");
		return false;
	}

	if ((!window.is_opera) || (!is_opera()))
	{
		var j;
		for (j=0;j<field.form.elements.length;j++)
		{
			if (field.form.elements[j].type=='submit')
			{
				/*addEventListenerAbstract(window,'pageshow',onpageshow,false); Causes problems in some situations
				field.form.elements[j].setAttribute('disabled',true);
				field.form.elements[j].restoreOnShow=true;*/
			}
		}
	}

	return true;
}

function confirmDelete()
{
	return window.confirm("Are you sure you want to delete this?");
}

function setFieldError(theElement,errorMsg)
{
	var errorElement=null;
	if (theElement.name)
	{
		var id=theElement.name;
		errorElement=document.getElementById('error_'+id);
		if (!errorElement)
		{
			errorElement=document.getElementById('error_'+id.replace(/\_day$/,'').replace(/\_month$/,'').replace(/\_year$/,'').replace(/\_hour$/,'').replace(/\_minute$/,''));
		}
		if (errorElement)
		{
			errorElement.style.display=(errorMsg=='')?'none':'block';
			setInnerHTML(errorElement,'');
			if (errorMsg!='')
			{
				var msgNode=document.createTextNode(errorMsg);
				errorElement.appendChild(msgNode);
			}
		}
	}
	if (errorMsg!='') theElement.className=theElement.className+' input_erroneous';
}

function try_to_simplify_iframe_form()
{
	var form_cat_selector=document.getElementById('form_cat_selector'),i,element,count=0,found,foundButton;
	for (i=0;i<form_cat_selector.elements.length;i++)
	{
		element=form_cat_selector.elements[i];
		if (((element.nodeName.toLowerCase()=='input') && (element.getAttribute('type')!='hidden') && (element.getAttribute('type')!='button') && (element.getAttribute('type')!='image') && (element.getAttribute('type')!='submit')) || (element.nodeName.toLowerCase()=='select') || (element.nodeName.toLowerCase()=='textarea'))
		{
			found=element;
			count++;
		}
		if (((element.nodeName.toLowerCase()=='input') && ((element.getAttribute('type')=='button') || (element.getAttribute('type')=='image') || (element.getAttribute('type')=='submit'))) || (element.nodeName.toLowerCase()=='button'))
		{
			foundButton=element;
		}
	}

	if ((count==1) && (found.nodeName.toLowerCase()=='select'))
	{
		found.onclick=function() {
			var iframe=document.getElementById('iframe_under');
			
			if ((iframe.contentDocument) && (iframe.contentDocument.getElementsByTagName('form').length!=0))
			{
				if (!window.confirm('Are you sure you want to switch to editing a different one? You will lose any unsaved changes you have made.')) return false;
			}
			
			if (checkForm(form_cat_selector))
			{
				animateFrameLoad(iframe,'iframe_under');
				form_cat_selector.submit();
			}
			
			return true;
		}
		foundButton.style.display='none';
	}
}

function do_form_submit(form)
{
	if (!checkForm(form)) return false;

	if (form.old_action) form.setAttribute('action',form.old_action);
	if (form.old_target) form.setAttribute('target',form.old_target);
	if (!form.getAttribute('target')) form.setAttribute('target','_top');

	
	if (form.getAttribute('method').toLowerCase()=='get')
	{
   	var i=0,name,elements=[];
   	for (i=0;i<form.elements.length;i++)
   	{
   		elements.push(form.elements[i]);
   	}
   	for (i=0;i<elements.length;i++)
   	{
   		name=elements[i].name;
   		if ((name.substr(0,11)=='label_for__') || (name.substr(0,14)=='tick_on_form__') || (name.substr(0,9)=='comcode__') || (name.substr(0,9)=='require__'))
   		{
   			elements[i].parentNode.removeChild(elements[i]);
   		}
   	}
	}

	if (form.onsubmit)
	{
		var ret=form.onsubmit();
		if (!ret) return false;
	}
	form.submit();
	
	return true;
}

function do_form_preview(form,preview_url)
{
	if ((window.checkForm) && (!checkForm(form))) return false;

	var old_action=form.getAttribute('action');

	if (window.has_separate_preview)
	{
		form.setAttribute('action',old_action+'&preview=1');
		return true;
	}

	if (!form.old_action) form.old_action=old_action;
	form.setAttribute('action',preview_url+((form.old_action.indexOf('&uploading=1')!=-1)?'&uploading=1':''));
	var old_target=form.getAttribute('target');
	if (!old_target) old_target='_top'; 
	if (!form.old_target) form.old_target=old_target;
	form.setAttribute('target','preview_iframe');
	document.getElementById('submit_button').style.display='inline';
	//window.setInterval('resizeFrame(\'preview_iframe\','+(window.top.scrollY+window.top.getWindowHeight())+')',1500);
	var pf=document.getElementById('preview_iframe');

	
	window.setInterval(trigger_resize,500);  
	animateFrameLoad(pf,'preview_iframe',50);

	var inputs=form.elements,input;
	for (var i=0;i<inputs.length-1;i++)
	{
		input=inputs[i];
		if ((input.type=='file') && (!input.name.match(/file\d*/)) && (!input.disabled) && (input.value!=''))
		{
			input.disabled=true;
			window.setTimeout('document.getElementById(\''+input.id+'\').disabled=false;',500);
		}
	}

	return true;
}

function checkForm(theForm)
{
	var i,j,theClass,theElement,required,myValue,erroneous=false,errorMsg,regexp,totalFileSize=0,alerted=false;
	for (j=0;j<theForm.elements.length;j++)
	{
		if (!theForm.elements[j]) continue;

		theElement=theForm.elements[j];
		errorMsg='';

		if (((theElement.type=='hidden') || (theElement.style.display=='none')) && ((!theElement.className) || (theElement.className.indexOf('hidden_but_needed')==-1)))
		{
			continue;
		}

		// Test file sizes
		if ((theElement.type=='file') && (theElement.files) && (theElement.files.item) && (theElement.files.item(0)) && (theElement.files.item(0).fileSize))
			totalFileSize+=theElement.files.item(0).fileSize;
			
		// Test file types
		if ((theElement.type=='file') && (theElement.value))
		{
			var valid_types='asf,avi,bmp,doc,docx,flv,gif,gz,jpeg,jpg,mov,mp3,mpeg,mpg,ods,odt,ogg,pdf,php,png,ppt,pptx,ps,psd,pub,qt,ra,ram,rar,rm,sql,tar,tga,tif,torrent,txt,wav,wmv,xls,xlsx,zip'.split(/,/);
			var type_ok=false;
			var theFileType=theElement.value.indexOf('.')?theElement.value.substr(theElement.value.lastIndexOf('.')+1):'None';
			for (var k=0;k<valid_types.length;k++)
			{
				if (valid_types[k].toLowerCase()==theFileType.toLowerCase()) type_ok=true;
			}
			if (!type_ok)
			{
				errorMsg="Sorry, but &lsquo;xx1xx&rsquo; files are not enabled for this website.\n<br />The following file types are enabled: asf,avi,bmp,doc,docx,flv,gif,gz,jpeg,jpg,mov,mp3,mpeg,mpg,ods,odt,ogg,pdf,php,png,ppt,pptx,ps,psd,pub,qt,ra,ram,rar,rm,sql,tar,tga,tif,torrent,txt,wav,wmv,xls,xlsx,zip.".replace(/xx1xx/g,theFileType).replace(/<[^>]*>/g,'').replace(/&[lr][sd]quo;/g,"'").replace(/,/g,', ');
				if (!alerted) window.alert(errorMsg);
				alerted=true;
			}
		}

		// Fix up bad characters
		if ((browser_matches('ie')) && (theElement.value))
		{
			bad_word_chars=[8216,8217,8220,8221];
			fixed_word_chars=["'","'",'"','"'];
			for (i=0;i<bad_word_chars.length;i++)
			{
				regexp=new RegExp(String.fromCharCode(bad_word_chars[i]),'gm');
				theElement.value=theElement.value.replace(regexp,fixed_word_chars[i]);
			}
		}

		theClass=firstClassName(theElement.className);

		if ((theElement.name=='delete') && (theClass=='input_tick') && (theElement.checked)) return confirmDelete(); // Because we're deleting, errors do not matter

		// Find whether field is required and value of it
		required=theClass.indexOf('_required');
		myValue=theElement.value;
		if (!myValue) myValue='';
		if ((window.areaedit_editors) && (theElement.style.display=='none') && (areaedit_editors[theElement.id]))
		{
			myValue=areaedit_editors[theElement.id].getHTML();
			if (myValue=="\n") myValue="";
		}
		if (theElement.getAttribute('type')=='radio')
		{
			myValue='';
			for (i=0;i<=theForm.elements.length;i++)
			{
				if (!theForm.elements[i]) continue;

				if ((theForm.elements[i].checked) && (theForm.elements[i].name==theElement.name))
					myValue=theForm.elements[i].value;
			}
		}
		if ((theElement.nodeName.toLowerCase()=='select') && (theElement.selectedIndex>=0))
		{
			myValue=theElement.options[theElement.selectedIndex].value;
		}

		if ((required!=-1) && ((myValue=='') || (myValue=='****')))
		{
			errorMsg="This is a required field and must therefore be filled in";
		} else
		{
			if (((theClass=='input_email') || (theClass=='input_email_required')) && (myValue!='') && (myValue!='****') && (!myValue.match(/^[a-zA-Z0-9\._\-]+@[a-zA-Z0-9\._\-]+$/)))
			{
				errorMsg="You specified a non-valid e-mail address (e-mail addresses contain \"@\")";
			}
			if (((theClass=='input_username') || (theClass=='input_username_required')) && (myValue!='') && (myValue!='****') && (window.do_ajax_field_test) && (!do_ajax_field_test('/data/username_exists.php?username='+encodeURIComponent(myValue))))
			{
				errorMsg="A field that was supposed to be a username specified a non-existent one";
			}
			if (((theClass=='input_integer') || (theClass=='input_integer_required')) && (myValue!='') && (myValue!='****') && (parseInt(myValue)!=myValue-0))
			{
				errorMsg="A field that was supposed to be an integer (whole number) was not";
			}
			if (((theClass=='input_float') || (theClass=='input_float_required')) && (myValue!='') && (myValue!='****') && (parseFloat(myValue)!=myValue-0))
			{
				errorMsg="A field that was supposed to be a float (decimal number) was not";
			}
		}

		setFieldError(theElement,errorMsg);
		if ((errorMsg!='') && (!erroneous))
		{
			theElement.focus();
			erroneous=true;
		}
	}
	
	if ((totalFileSize>0) && (theForm.elements['MAX_FILE_SIZE']))
	{
		if (totalFileSize>theForm.elements['MAX_FILE_SIZE'].value)
		{
			erroneous=true;
			if (!alerted)
			{
				window.alert("The maximum upload limit is {2}KB, but you are trying to upload {1}KB.".replace(new RegExp('\\\{'+'1'+'\\\}','g'),Math.round(totalFileSize/1024)).replace(new RegExp('\\\{'+'2'+'\\\}','g'),Math.round(theForm.elements['MAX_FILE_SIZE'].value/1024)));
			}
			alerted=true;
		}
	}

	/*if (((!window.is_opera) || (!is_opera())) && (!erroneous) && ((!theForm.getAttribute('target')) || (theForm.getAttribute('target')=='_top')))
	{
		for (j=0;j<theForm.elements.length;j++)
		{
			if (theForm.elements[j].type=='submit')
			{
				addEventListenerAbstract(window,'pageshow',onpageshow,false);
				theForm.elements[j].setAttribute('disabled',true);
				theForm.elements[j].restoreOnShow=true;
			}
		}
	}*/

	if (erroneous)
	{
		window.scrollTo(0,0);
		if (!alerted) window.alert("You did not fill in all fields on the form correctly");
	}

	return !erroneous;
}

// Do dynamic setLocked/setRequired such that one of these must be set, but only one may be
function standardAlternateFields(_a,_b,_c,non_actually_required)
{
	if (!non_actually_required) non_actually_required=false; // Just to make sure it's a nice boolean

	// Set up listening if not already...
	var a=_standardAlternateFieldsGet(_a);
	var b=_standardAlternateFieldsGet(_b);
	var c;
	if (_c) c=_standardAlternateFieldsGet(_c); // Third alternate is optional
	if (((a) && (!a.alternating)) || ((b) && (!b.alternating)) || ((c) && (!c.alternating))) // It is actually allowed for a single alternator, if circumstances have made the other one non-present (such as having GD support meaning a thumbnail isn't needed)
	{
		var selfFunction=function (e) { standardAlternateFields(_a,_b,_c,non_actually_required); } ; // We'll recall ourself to do any fiddling

		_standardAlternateFieldEventSet(a,selfFunction);
		_standardAlternateFieldEventSet(b,selfFunction);
		_standardAlternateFieldEventSet(c,selfFunction);
	}

	// Now, look at what is set, and disable/enable/require/non-require appropriately
	if ((a) && (a.value!='') && (a.value!='-1')) return _standardAlternateFieldsSet(a,b,c,non_actually_required);
	if ((b) && (b.value!='') && (b.value!='-1')) return _standardAlternateFieldsSet(b,a,c,non_actually_required);
	if ((c) && (c.value!='') && (c.value!='-1')) return _standardAlternateFieldsSet(c,a,b,non_actually_required);
	// Nothing set...
	if (a) _standardAlternateFieldSet(a,false,true,non_actually_required);
	if (b) _standardAlternateFieldSet(b,false,true,non_actually_required);
	if (c) _standardAlternateFieldSet(c,false,true,non_actually_required);
	return null;
}

function _standardAlternateFieldEventSet(a,selfFunction)
{
	if (a)
	{
		if (a.name)
		{
			addEventListenerAbstract(a,"keyup",selfFunction);
			addEventListenerAbstract(a,"change",selfFunction);
			a.fakeonchange=selfFunction;
			a.alternating=true;
		} else
		{
			var i;
			for (i=0;i<a.length;i++)
			{
				addEventListenerAbstract(a[i],"keyup",selfFunction);
				addEventListenerAbstract(a[i],"change",selfFunction);
				a[i].fakeonchange=selfFunction;
				a[i].alternating=true;
			}
		}
	}
	return null;
}

function _standardAlternateFieldsGet(x)
{
	if (x.indexOf('*')==-1)
	{
		return document.getElementById(x);
	}
	x=x.substr(0,x.length-1);
	var _x=[],i,j,c=0,e;
	_x['value']='';
	for (i=0;i<document.forms.length;i++)
	{
		for (j=0;j<document.forms[i].elements.length;j++)
		{
			e=document.forms[i].elements[j];
			if (e.name==x)
			{
				_x[c]=e;
				if (e.checked)
				{
					_x['value']=e.value;
				}
				if (e.alternating) _x.alternating=true;
				c++;
			}
		}
	}

	return _x;
}

function _standardAlternateFieldsSet(a,b,c,non_actually_required)
{
	if (a) _standardAlternateFieldSet(a,false,true,non_actually_required);
	if (b) _standardAlternateFieldSet(b,true,false,non_actually_required);
	if (c) _standardAlternateFieldSet(c,true,false,non_actually_required);
}

function _standardAlternateFieldSet(a,locked,required,non_actually_required)
{
	if (a.name)
	{
		setLocked(a.name,locked);
		if (!non_actually_required) setRequired(a.name,required);
	} else
	{
		if (a[0])
		{
			if (!non_actually_required) setRequired(a[0].name,required);
		}

		var i;
		for (i=0;i<a.length;i++)
		{
			if (a[i].id) // If it is an object, as opposed to some string in the collection
			{
				setLocked(a[i].id,locked);
				if (!non_actually_required) setRequired(a[i].id,required);
			}
		}
	}
}

function setLocked(name,locked)
{
	// For All-and-not,Line-multi,Compound-Tick,Radio-List,Date/Time: setLocked assumes that the calling code is clever
	// special input types are coded to observe their master input field readonly status)
	var element=document.getElementById(name);
	if (element)
	{
		if (locked)
		{
			setFieldError(element,'Blank out the competing field (or set to N/A) if you wish to use this one instead');
		} else
		{
			setFieldError(element,'');
		}
		element.disabled=locked;
	}
}

function setRequired(name,required)
{
	var element=document.getElementById(name);
	var required_a=document.getElementById('requirea__'+name);
	var required_b=document.getElementById('requireb__'+name);
	var required_c=document.getElementById('requirec__'+name);
	var required_d=document.getElementById('required__'+name);
	if (element) element.className=element.className.replace(/(input\_[a-z\_]+)_required/g,'$1');
	if (required)
	{
		if (element) element.className=element.className.replace(/(input\_[a-z\_]+)/g,'$1_required');
		if (required_a) required_a.className='de_th dottedborder_barrier_a_required';
		if (required_d) required_d.className='dottedborder_barrier_b_required';
		if (required_b) required_b.style.display='inline';
		if (required_c) required_c.value=1;
	} else
	{
		var error=document.getElementById('error__'+name);
		if (error) error.style.display='none';
		if (required_a) required_a.className='de_th dottedborder_barrier_a_nonrequired';
		if (required_d) required_d.className='dottedborder_barrier_b_nonrequired';
		if (required_b) required_b.style.display='none';
		if (required_c) required_c.value=0;
	}
}

function toggleSubordinateFields(pic)
{
	var new_state;
	var tr=pic.parentNode.parentNode.parentNode;
	
	var next=tr.nextSibling;
	if (!next) return;
	while (next.nodeName.toLowerCase()!='tr') { next=next.nextSibling; }

	if (next.style.display=='none') 
	{
		pic.src=(pic.src.indexOf("themewizard.php")!=-1)?pic.src.replace("expand","contract"):"http://propertytoyou.co.uk/themes/Property_to_you/images/contract.png";
		new_state=browser_matches('ie')?'block':'table-row';
	} else 
	{
		pic.src=(pic.src.indexOf("themewizard.php")!=-1)?pic.src.replace("contract","expand"):"http://propertytoyou.co.uk/themes/Property_to_you/images/expand.png";
		new_state='none';
	}
	
	while (tr.nextSibling)
	{
		tr=tr.nextSibling;
		if (tr.nodeName.toLowerCase()!='tr') continue;

		
		if (tr.className=='form_screen_field_spacer') break;
		
		
		tr.style.display=new_state;
	}
	
	var help=document.getElementById(pic.parentNode.id+'_help');
	if (help) help.style.display=new_state;
	
	trigger_resize();
}

function choose_picture(id,ob,name)
{
	var r=document.getElementById(id);
	if (!r) return;
	var e=r.form.elements[name];
	for (var i=0;i<e.length;i++)
	{
		var img=e[i].parentNode.parentNode.getElementsByTagName('img')[0];
		if ((img) && (img!=ob))
		{
			img.style.outline='0';
			setOpacity(img.parentNode,0.5);
		}
	}
	r.checked=true;
	if (r.onclick) r.onclick();
	if (r.fakeonchange) r.fakeonchange();
	setOpacity(ob.parentNode,1.0);
	ob.style.outline='1px dotted';
}
