function skipFormValidation(elem){
	elem=$(elem);
	var frm=elem.form;
	frm.skipValidation=true;
	return true;
}

function validateFormFields(frm){
	frm=$(frm);
	if(frm.skipValidation){
		return true;
	}
	var fields=frm.select("input,textarea,select");
	var msg="";
	fields.each(function(field){
		if(!field.validation){
			return; //from this iteration
		}
		var fieldValue=field.value.strip();
		var v=field.validation;
		if(v.required && ""==fieldValue){
			msg+="\n* "+v.alias+" is required";
		}
		if(v.notFuture){
			v.date=true;
		}
		if(v.minimum || v.maximum || v.wholeNumber){
			v.numeric=true;
		}
		if(0<fieldValue.length){
			if(v.length && fieldValue.length!=v.length){
				msg+="\n* "+v.alias+" must be "+v.length+" characters long";
			} else if(v.minlength && fieldValue.length < v.minlength){
				msg+="\n* "+v.alias+" cannot be less than "+v.minlength+" characters long";
			} else if(v.maxlength && fieldValue.length > v.maxlength){
				msg+="\n* "+v.alias+" cannot be more than "+v.maxlength+" characters long";
			} else if(v.date){
				dateError=validDate(fieldValue);
				if(""!=dateError){
					msg+="\n* "+v.alias+": "+dateError;
				} else if(v.notFuture && dateIsInFuture(fieldValue)){
					msg+="\n* "+v.alias+": Date cannot be in the future";
				}
			} else if(v.numeric){
				if(isNaN(parseFloat(fieldValue)) || !isFinite(fieldValue)){
					msg+="\n* "+v.alias+" must be numeric";
				} else if(v.wholeNumber && parseInt(fieldValue)!=fieldValue-0){
					msg+="\n* "+v.alias+" must be a whole number";
				} else if(v.minimum && v.maximum && (fieldValue-0 < v.minimum || fieldValue-0 > v.maximum)){
					msg+="\n* "+v.alias+" must be between "+v.minimum+" and "+v.maximum;
				} else if(v.minimum && fieldValue-0 < v.minimum){
					msg+="\n* "+v.alias+" must be greater than "+v.minimum;
				} else if(v.maximum && fieldValue-0 < v.maximum){
					msg+="\n* "+v.alias+" must be less than "+v.maximum;
				}
			}
		}
	});
	if(""!=msg){
		alert("Please correct the following:\n"+msg);
		return false;
	}
	return true;
}

function validDate(dateStr){
	//check format with regex
	if(!dateStr.match(/^[0-9]{1,2}-[0-9]{1,2}-[0-9]{4}$/)){
		return "Dates must be in the format MM-DD-YYYY";
	}
	return "";
}

//DOES NOT validate date. Call validDate first. Date must be MM-DD-YYYY format.
function dateIsInFuture(dateStr){
	
}

function handleAircraftTypeOnchange(sel){
	sel=$(sel);
	//TODO test for ajax availability, bail on fail
	if('aircraft_type'==sel.name){
		//swap name with hidden field aircraft_type_hidden
	}
	var frm=sel.up("form");
	fetchChildAircraftTypes(sel,sel.value);
}

function fetchChildAircraftTypes(selectField,parentId){
	selectField=$(selectField);
	var hiddenInputField=selectField.up(".aircraft_type_fields").down('input[name="aircraft_type"]');
	var nxt = selectField.next();
	if(nxt && nxt.hasClassName("subselect")){
		nxt.remove();
	}
	if(""==selectField.value){
		if(undefined==selectField.up("div.subselect")){
			//top select was changed. Empty value = not even a manufacturer.
			hiddenInputField.value="";
		} else {
			var parentSelect=selectField.up("div.subselect").up("div").down("select");
			if(0==parentSelect.value){
				hiddenInputField.value="";
			} else {
				hiddenInputField.value=parentSelect.value;
			}
		}
		return;
	} else if(0==selectField.value){
		hiddenInputField.value="";
	} else {
		hiddenInputField.value=selectField.value;
	}
	selectField.up("div").insert('<div class="subselect" style="margin-left:1em"><select onchange="handleAircraftTypeOnchange(this)"><option>Fetching types...</option></select></div>');
	new Ajax.Request('/common/ajax_getaircrafttypes.php?parent='+parentId,{
		method:'get',
		onSuccess:function(response){fetchChildAircraftTypes_onSuccess(response, selectField);},
		onFailure:default_onFailure
	});
}
function fetchChildAircraftTypes_onSuccess(transport,selectField){
		selectField=$(selectField);
		parentType=selectField.options[selectField.selectedIndex].text;
		var typesData=transport.responseText.evalJSON();
		var nxt = selectField.next();
		if(!nxt || !nxt.hasClassName("subselect")){
			alert("Sorry, there was a problem.");
		}
		var childSelect=nxt.down("select");
		if(0==typesData['types'].length){
//			childSelect.replace("All "+parentType);
			childSelect.replace("(No sub-types)");
		} else {
			newOptions='<option value="">All '+parentType+'</option>';
			typesData['types'].each(function(t){
				newOptions+='<option value="'+t["id"]+'">'+t["name"]+'</option>';
			});
			childSelect.update(newOptions);
			if(1==typesData['types'].length){
				childSelect.selectedIndex=1;
				childSelect.onchange();
			}
		}
}





function handlePartsCategoryOnchange(sel){
	sel=$(sel);
	if(!sel.level){
		sel.level=1; //used to restrict to three levels (ATA)
	}
	//TODO test for ajax availability, bail on fail
	if('parts_category'==sel.name){
		//swap name with hidden field aircraft_type_hidden
	}
	var frm=sel.up("form");
//	if(sel.level &&sel.level < 3){
		fetchChildPartsCategories(sel,sel.value);
//	}
}

function fetchChildPartsCategories(selectField,parentId){
	selectField=$(selectField);
	var hiddenInputField=selectField.up(".parts_category_fields").down('input[name="parts_category"]');
	var nxt = selectField.next();
	if(nxt && nxt.hasClassName("subselect")){
		nxt.remove();
	}
	if(""==selectField.value){
		if(undefined==selectField.up("div.subselect")){
			//top select was changed.
			hiddenInputField.value="";
		} else {
			var parentSelect=selectField.up("div.subselect").up("div").down("select");
			if(0==parentSelect.value){
				hiddenInputField.value="";
			} else {
				hiddenInputField.value=parentSelect.value;
			}
		}
		return;
	} else if(0==selectField.value){
		hiddenInputField.value="";
	} else {
		hiddenInputField.value=selectField.value;
	}
	selectField.up("div").insert('<div class="subselect" style="margin-left:1em"><select onchange="handlePartsCategoryOnchange(this)"><option>Fetching sub-categories...</option></select></div>');
	new Ajax.Request('/common/ajax_getpartscategories.php?parent='+parentId,{
		method:'get',
		onSuccess:function(response){fetchChildPartsCategories_onSuccess(response, selectField);},
		onFailure:default_onFailure
	});
}
function fetchChildPartsCategories_onSuccess(transport,selectField){
		selectField=$(selectField);
		parentCat=selectField.options[selectField.selectedIndex].text;
		var catsData=transport.responseText.evalJSON();
		var nxt = selectField.next();
		if(!nxt || !nxt.hasClassName("subselect")){
			alert("Sorry, there was a problem.");
		}
		var childSelect=nxt.down("select");
		childSelect.level = 1+selectField.level;
		if(0==catsData['categories'].length){
			childSelect.replace("(No sub-categories)");
		} else {
			newOptions='<option value="">All</option>';
			catsData['categories'].each(function(c){
				newOptions+='<option value="'+c["id"]+'">'+c["name"]+'</option>';
			});
			childSelect.update(newOptions);
			if(1==catsData['categories'].length){
				childSelect.selectedIndex=1;
				childSelect.onchange();
			}
		}
}



function default_onFailure(transport){
	alert("Sorry, there was a problem.");
}

function showMiniProfile(profileLink,userid){
	return true;
//	alert(profileLink.href+" "+userid);
	//append "&mode=mini" to URL
	//do AJAX GET
	//if result not JSON (try-catch on parse?) show "Can't view profiles if not logged in" (or return true)
	//else show box with mini-profile
	//return false to cancel default username link action (navigate to profile)
}

function processAvatars(){
	if(typeof(Element.absolutize)==="undefined" || document.body==null){
		//Prototype not loaded yet, try again in a while
		setTimeout(processAvatars,500);
		return false;
	}
	avatarsToProcess=Element.extend(document.body).select(".setavatarandonline");
	avatarsToProcess.each(function(ava){
		processAvatar(ava);
	});
}

function processAvatar(elem){
	elem=$(elem);
	if(elem.up(".suppressavatarfetch")){
		elem.addClassName("done");
	}
	if(elem.hasClassName("done")){
		return;
	}
	//find parent button, if none, parent glass bar, if none, is in plain text, go to next(return)
	var parentGlass=elem.up(".userbutton");
	if(null!=parentGlass){
		if("online"==parentGlass.down(".isonline").innerHTML){
			parentGlass.addClassName("ub_online");
		}
	} else {
		parentGlass=elem.up(".glassbar");
		if(null!=parentGlass){
			parentGlass.down(".rightimage").down("img").src=themePath+"/images/endcap_"+parentGlass.down(".isonline").innerHTML+".png";
		}else{
			return;
		}
	}
	var avatarPath=parentGlass.down(".avatarstring");
	if(null!=avatarPath && ""!=avatarPath.innerHTML){
		parentGlass.down("img").src=avatarPath.innerHTML;
	}
	elem.addClassName("done");
}


/**
* phpBB3 forum functions
*/

/**
* Window popup
*/
function popup(url, width, height, name)
{
	if (!name)
	{
		name = '_popup';
	}

	window.open(url.replace(/&amp;/g, '&'), name, 'height=' + height + ',resizable=yes,scrollbars=yes, width=' + width);
	return false;
}

/**
* Jump to page
*/
function jumpto()
{
	var page = prompt(jump_page, on_page);

	if (page !== null && !isNaN(page) && page == Math.floor(page) && page > 0)
	{
		if (base_url.indexOf('?') == -1)
		{
			document.location.href = base_url + '?start=' + ((page - 1) * per_page);
		}
		else
		{
			document.location.href = base_url.replace(/&amp;/g, '&') + '&start=' + ((page - 1) * per_page);
		}
	}
}

/**
* Mark/unmark checklist
* id = ID of parent container, name = name prefix, state = state [true/false]
*/
function marklist(id, name, state)
{
	var parent = document.getElementById(id);
	if (!parent)
	{
		eval('parent = document.' + id);
	}

	if (!parent)
	{
		return;
	}

	var rb = parent.getElementsByTagName('input');
	
	for (var r = 0; r < rb.length; r++)
	{	
		if (rb[r].name.substr(0, name.length) == name)
		{
			rb[r].checked = state;
		}
	}
}

/**
* Resize viewable area for attached image or topic review panel (possibly others to come)
* e = element
*/
function viewableArea(e, itself)
{
	if (!e) return;
	if (!itself)
	{
		e = e.parentNode;
	}
	
	if (!e.vaHeight)
	{
		// Store viewable area height before changing style to auto
		e.vaHeight = e.offsetHeight;
		e.vaMaxHeight = e.style.maxHeight;
		e.style.height = 'auto';
		e.style.maxHeight = 'none';
		e.style.overflow = 'visible';
	}
	else
	{
		// Restore viewable area height to the default
		e.style.height = e.vaHeight + 'px';
		e.style.overflow = 'auto';
		e.style.maxHeight = e.vaMaxHeight;
		e.vaHeight = false;
	}
}

/**
* Set display of page element
* s[-1,0,1] = hide,toggle display,show
*/
function dE(n, s)
{
	var e = document.getElementById(n);

	if (!s)
	{
		s = (e.style.display == '' || e.style.display == 'block') ? -1 : 1;
	}
	e.style.display = (s == 1) ? 'block' : 'none';
}

/**
* Alternate display of subPanels
*/
function subPanels(p)
{
	var i, e, t;

	if (typeof(p) == 'string')
	{
		show_panel = p;
	}

	for (i = 0; i < panels.length; i++)
	{
		e = document.getElementById(panels[i]);
		t = document.getElementById(panels[i] + '-tab');

		if (e)
		{
			if (panels[i] == show_panel)
			{
				e.style.display = 'block';
				if (t)
				{
					t.className = 'activetab';
				}
			}
			else
			{
				e.style.display = 'none';
				if (t)
				{
					t.className = '';
				}
			}
		}
	}
}

/**
* Call print preview
*/
function printPage()
{
	if (is_ie)
	{
		printPreview();
	}
	else
	{
		window.print();
	}
}

/**
* Show/hide groups of blocks
* c = CSS style name
* e = checkbox element
* t = toggle dispay state (used to show 'grip-show' image in the profile block when hiding the profiles) 
*/
function displayBlocks(c, e, t)
{
	var s = (e.checked == true) ?  1 : -1;

	if (t)
	{
		s *= -1;
	}

	var divs = document.getElementsByTagName("DIV");

	for (var d = 0; d < divs.length; d++)
	{
		if (divs[d].className.indexOf(c) == 0)
		{
			divs[d].style.display = (s == 1) ? 'none' : 'block';
		}
	}
}

function selectCode(a)
{
	// Get ID of code block
	var e = a.parentNode.parentNode.getElementsByTagName('CODE')[0];

	// Not IE
	if (window.getSelection)
	{
		var s = window.getSelection();
		// Safari
		if (s.setBaseAndExtent)
		{
			s.setBaseAndExtent(e, 0, e, e.innerText.length - 1);
		}
		// Firefox and Opera
		else
		{
			// workaround for bug # 42885
			if (window.opera && e.innerHTML.substring(e.innerHTML.length - 4) == '<BR>')
			{
				e.innerHTML = e.innerHTML + '&nbsp;';
			}

			var r = document.createRange();
			r.selectNodeContents(e);
			s.removeAllRanges();
			s.addRange(r);
		}
	}
	// Some older browsers
	else if (document.getSelection)
	{
		var s = document.getSelection();
		var r = document.createRange();
		r.selectNodeContents(e);
		s.removeAllRanges();
		s.addRange(r);
	}
	// IE
	else if (document.selection)
	{
		var r = document.body.createTextRange();
		r.moveToElementText(e);
		r.select();
	}
}

/**
* Play quicktime file by determining it's width/height
* from the displayed rectangle area
*/
function play_qt_file(obj)
{
	var rectangle = obj.GetRectangle();

	if (rectangle)
	{
		rectangle = rectangle.split(',');
		var x1 = parseInt(rectangle[0]);
		var x2 = parseInt(rectangle[2]);
		var y1 = parseInt(rectangle[1]);
		var y2 = parseInt(rectangle[3]);

		var width = (x1 < 0) ? (x1 * -1) + x2 : x2 - x1;
		var height = (y1 < 0) ? (y1 * -1) + y2 : y2 - y1;
	}
	else
	{
		var width = 200;
		var height = 0;
	}

	obj.width = width;
	obj.height = height + 16;

	obj.SetControllerVisible(true);
	obj.Play();
}

