function removeAllOptions(selectbox) {
	var i;
	for(i=selectbox.options.length-1;i>=0;i--) {
		var o = selectbox.options[i];
		selectbox.removeChild(o);
	}
}

NodeList.prototype.toHash = function() {
	var obj = {};
	for(var i = 0;i<this.getLength();i++) {
		try {
			el = this.item(i);
			if (el.firstChild.nodeType == Node.TEXT_NODE) {
				var t = '';
				for(var j = 0; j < el.getChildNodes().getLength() ; j++) {
					switch(el.getChildNodes().item(j).nodeType) {
						case Node.ENTITY_REFERENCE_NODE:
							t += el.getChildNodes().item(j).nodeName;
							break;
						default:
							t += el.getChildNodes().item(j).nodeValue;
					}
				}
				obj[el.nodeName] = t;
			} else {
				obj[el.nodeName] = 'NodeType: '+el.firstChild.nodeType;
			}
		} catch (e) {};
	}
	return $H(obj);
}

function getLinkByName(name) {
	var list = document.getElementsByName(name);
	var link = undefined;
	$A(list).each(function(el) {

		if (el.tagName.toLowerCase() == 'a') {
			link = el;
		}

	});

	return link;
}
var _a = {

	postForm: function(form, msgTarget, callBack) {

		var params = Form.serialize(form, true);
		params['_ajax'] = '1';

		Form.disable(form);

		try {
			if (msgTarget) $(msgTarget).innerHTML = ' Working ... ';
		} catch (e) {
			alert(e);
			return false;
		}

		this._doCall(form.action, params, function(r) {

			setTimeout(function() {

				if (msgTarget) $(msgTarget).innerHTML = r.responseText;
				Form.enable(form);

				try {
					if (msgTarget) Element.scrollTo($(msgTarget));
				} catch (e) {};
				
				if (callBack) return callBack(form, r);
			}, 500);

		});
			
		return true;
	},

	submitUploadForm: function(form, msgTarget, required) {
		var ok = true;
		try {
			for(var i = 0; i < required.length; i++) {
				if (required[i].value == "") ok = false;
			}
		} catch (e) { 
			alert(e); 
		};

		if (ok) {
			//$(msgTarget).innerHTML = 'Uploading ...';
			$(msgTarget).innerHTML = 'Busy...';
			// cannot submit disabled form, but disabled looks good :[
			setTimeout(function() {
				Form.disable(form);
			}, 1000);
			return true;
		} else {
			$(msgTarget).innerHTML = 'Please select a file';
		}

		return false;
	},

	_doCall: function(target, params, cb) {
		
		var r = new Ajax.Request(target, {

			parameters: $H(params).toQueryString(),

			on200: function(req) {

				var parser = new XMLParser();
				var doc = null;
				var children;
				var root;

				try {

					parser.parse(req.responseText);
					doc = parser.doc;

					root 		= doc.getDocumentElement();
					children	= root.getChildNodes().toHash();

				} catch (e) {};

				if (cb) {

					return cb(req, children, root, doc);

				} else {

					try {
						_a['_result_' + root.getTagName()](children, doc);
					} catch(e) { alert('compl: ' + e); }

				}
			},
			on500: function(r) {
				alert('Error 500: ' + t.statusText + "\n\n" + t.responseText);
			},
			on404: function(t) {
				alert('Error 404: location "' + t.statusText + '" was not found.');
			},
			onFailure: function(t) {
				alert('Error ' + t.status + ' -- ' + t.statusText);
			}
		});

	},

	call: function(target, method, params, cb) {
	
		params['_ajaxCall'] = method;
		this._doCall(target, params, cb);

	},

	goFormAction: function(form) {
		Form.disable(form);

		document.location.href = form.action;
		
		return false;
	},

	mpChangeForm: function(method, target, cb) {
		if (cb == undefined) $(target).innerHTML = 'Loading ..';

		try {
			this.call('/mypage/main', 'loadForm', { form: method }, function(r) {
				$(target).innerHTML = r.responseText;
				if (cb != undefined) {
					cb(r);
				}
			});
		} catch(e) {
			alert(e);
		}
		return true;
	},

	mpLoadAllBlogEntries: function(targetId) {

		$(targetId).innerHTML = 'Loading ..';
		_a.call('/mypage/wblog', 'loadAllWeblogEntries', {}, function(r) {

			setTimeout(function() {
				$(targetId).innerHTML = r.responseText;
			}, 200);

		});
	},
	mpAddBlogFriend: function(form, msgs) {
		_a.postForm(form, msgs, function(form, r) {

			var msg = r.responseText;
			if (r.responseText == '1') {
				try {
					$(msgs).update('Friend added.');
					window.location.replace(unescape(window.location.pathname));
				} catch(e) { };
			}
		});
	},
	mpSendBlogUpdate: function(form, msgs) {

		// init vars
		var idField = $('friendIdList');
		var ids		= new Array();

		// gather selected friend ids
		$$('input.send_invitation_box').each(function(el) {
			try {
				if (el.checked) ids.push($F(el));
			} catch(e) {};
		});
		idField.value = ids.join(',');


		_a.postForm(form, msgs, function(form, r) {

		});
	},
	saveChildren: function(form, msgs) {
		_a.postForm(form, msgs, function(form, r) {

			var msg = r.responseText;
			_a.mpChangeForm('children', 'profile_form', function() {
				$(msgs).innerHTML = msg;
			});

		});
	},

	saveJobHistory: function(form, msgs) {

		_a.postForm(form, msgs, function(from, r) {

			var msg = r.responseText;
			if (msg == 'Deleted' || msg == 'Job Added') {

				_a.mpChangeForm('jobHistory', 'profile_form', function() {
					$(msgs).innerHTML = msg;
				});

			}

		});
	},

	saveExpatHistory: function(form, msgs) {
		_a.postForm(form, msgs, function(form, r) {
			var msg = r.responseText;
			_a.mpChangeForm('expatHistory', 'profile_form', function() {
				$(msgs).innerHTML = msg;
			});
		});
	},

	deleteBlogEntry: function(id, liId) {
		if(confirm('Are you sure you whish to delete this weblog entry?')) {
			
			_a.call('/mypage/blog', 'deleteBlogEntry', {id: id}, function(r) {
				$(liId).innerHTML = '<span class="deleted"> - ' + r.responseText + '</span>';
			});

		}
	},

	deleteAnnouncement: function(id, liId) {
		if(confirm('Are you sure you whish to delete this announcement?')) {
			
			_a.call('/mypage/blog', 'deleteAnnouncement', {id: id}, function(r) {
				$(liId).innerHTML = '<span class="deleted"> - ' + r.responseText + '</span>';
			});

		}
	},

	deleteAdvertisement: function(id, liId) {
		if(confirm('Are you sure you whish to delete this marketplace item?')) {
			
			_a.call('/mypage/blog', 'deleteAdvertisement', {id: id}, function(r) {
				$(liId).innerHTML = '<span class="deleted"> - ' + r.responseText + '</span>';
			});

		}

	},

	deletePoll: function(id) {
	
		if (!confirm('Are you sure you wish to delete this poll?')) return false;

		var el = $('admin_poll_' + id);
		el.innerHTML = 'Working ..';

		_a.call('/admin/poll/delete', 'delete', { ID: id }, function(r) {
			setTimeout(function() {
				el.innerHTML = r.responseText;
			}, 300);
		});


	},

	createCountryCategory: function(form, msgs) {
		return _a.postForm(form, msgs, function() {
			Form.reset(form);
		});
	},

	deleteCityWelcomeCategory: function(cat, city, id, liId) {

		if(confirm('Are you sure you whish to delete this city page content?')) {
			
			_a.call('/mypage/main', 'delete_city_category', {category: cat, city: city, item: id}, function(r) {
				$(liId).innerHTML = '<span class="deleted"> - ' + r.responseText + '</span>';
			});

		}
	},

	_result_error: function(c, doc) {

	}
};

_a['toggleAfterSelect'] = function(sel, div, val) {
	try {

		if ($F(sel) == val) $(div).style.display = 'block';
		else $(div).style.display = 'none';

	} catch(e) {
		alert(e);
	}
}


_a['expatCitySelect'] = function(countryElement, cityID, stateID) {
	
	var selBox 	= $(cityID);
	//var stateSelBox = $(stateID);
	//alert(selBox);
	selBox.disabled = false;
	//stateSelBox.style.display = "none";
	// clear all options
	removeAllOptions(selBox);
	//removeAllOptions(stateSelBox);
	//alert(selBox);	
	
	/*
	// GETSTATES
	_a.call(countryElement.form.action, 'getStates', { country: $F(countryElement) }, function(r) {
		if (r.responseText == '0') {
			stateSelBox.style.display = "none";
			return false;
		}
		
		var txt 	= r.responseText.split("\n");

		stateSelBox.style.display = "block";

		try {
			for(var i = 0; i<txt.length; i++) {

				var val = txt[i].split("|");

				if (val[1] != undefined) {

					var no = document.createElement("OPTION");

					Try.these(
						function() { stateSelBox.add(no); },
						function() { stateSelBox.options.add(no); }
					);

					no.innerHTML 	= val[1];
					no.innerText 	= val[1];
					no.value 		= val[0];

				};

			}
		} catch(e) {
			alert('this one?' + e);
		}
	});
	*/
	// GETCITIES
	_a.call(countryElement.form.action, 'getExpatCities', { country: $F(countryElement) }, function(r) {

		if (r.responseText == '0') {

			//selBox.disabled = true;
			
			var no = document.createElement("OPTION");
			Try.these(
				function() { selBox.add(no); },
				function() { selBox.options.add(no); }
			);

			var display 	= countryElement.selectedIndex > 1 
								? " - No cities found for country " + countryElement[countryElement.selectedIndex].innerHTML + " - "
								: " - all cities - ";
			
			if ($('select_other_city')) {
				$('select_other_city').style.display = 'block';
			}
			
			no.innerHTML 	= display;
			no.innerText 	= display;
			no.value 		= "other";

			return false;
		};

		
		var txt 	= r.responseText.split("\n");

		selBox.disabled = false;

			selBox.style.display = "block";

		try {
			for(var i = 0; i<txt.length; i++) {

				var val = txt[i].split("|");

				if (val[1] != undefined) {

					var no = document.createElement("OPTION");

					Try.these(
						function() { selBox.add(no); },
						function() { selBox.options.add(no); }
					);

					no.innerHTML 	= val[1];
					no.innerText 	= val[1];
					no.value 		= val[0];

				};

			}
		} catch(e) {
			alert('this one?' + e);
		}

	});

}

_a['updateCitySelect'] = function(countryElement, cityID, stateID) {
	
	var selBox 	= $(cityID);
	var stateSelBox = $(stateID);
	selBox.disabled = false;
	stateSelBox.style.display = "none";
	// clear all options
	removeAllOptions(selBox);
	removeAllOptions(stateSelBox);
	//alert(selBox);	
	if ($('select_other_city')) {
		$('select_other_city').down('input').value = '';
		$('select_other_city').style.display = 'none';
	}
	
	// GETSTATES
	_a.call(countryElement.form.action, 'getStates', { country: $F(countryElement) }, function(r) {
		if (r.responseText == '0') {
			stateSelBox.style.display = "none";
			return false;
		}
		
		var txt 	= r.responseText.split("\n");

		stateSelBox.style.display = "block";

		try {
			for(var i = 0; i<txt.length; i++) {

				var val = txt[i].split("|");

				if (val[1] != undefined) {

					var no = document.createElement("OPTION");

					Try.these(
						function() { stateSelBox.add(no); },
						function() { stateSelBox.options.add(no); }
					);

					no.innerHTML 	= val[1];
					no.innerText 	= val[1];
					no.value 		= val[0];

				};

			}
		} catch(e) {
			alert('this one?' + e);
		}
	});

	// GETCITIES
	_a.call(countryElement.form.action, 'getCities', { country: $F(countryElement) }, function(r) {

		if (r.responseText == '0') {

			//selBox.disabled = true;

			var no = document.createElement("OPTION");
			Try.these(
				function() { selBox.add(no); },
				function() { selBox.options.add(no); }
			);

			var display 	= countryElement.selectedIndex > 0 
								? " - No cities found for country " + countryElement[countryElement.selectedIndex].innerHTML + " - "
								: " - all cities - ";
			
			if ($('select_other_city')) {
				$('select_other_city').style.display = 'block';
			}
			
			no.innerHTML 	= display;
			no.innerText 	= display;
			no.value 		= "other";

			return false;
		};

		
		var txt 	= r.responseText.split("\n");

		selBox.disabled = false;

		try {
			for(var i = 0; i<txt.length; i++) {

				var val = txt[i].split("|");

				if (val[1] != undefined) {

					var no = document.createElement("OPTION");

					Try.these(
						function() { selBox.add(no); },
						function() { selBox.options.add(no); }
					);

					no.innerHTML 	= val[1];
					no.innerText 	= val[1];
					no.value 		= val[0];

				};

			}
		} catch(e) {
			alert('this one?' + e);
		}

	});

}

_a['updateAfterStateSelect'] = function(stateElement, countryElement, cityID) {

	var selBox 	= $(cityID);
	selBox.disabled = false;
	// clear all options
	removeAllOptions(selBox);

	if ($('select_other_city')) {
		$('select_other_city').down('input').value = '';
		$('select_other_city').style.display = 'none';
	}
	
	_a.call(stateElement.form.action, 'getStateCities', { country: $F(countryElement), state: $F(stateElement) }, function(r) {

		if (r.responseText == '0') {

			selBox.disabled = true;

			var no = document.createElement("OPTION");
			Try.these(
				function() { selBox.add(no); },
				function() { selBox.options.add(no); }
			);

			var display 	= stateElement.selectedIndex > 1 
								? " - No cities found for state " + stateElement[stateElement.selectedIndex].innerHTML + " - "
								: " - all cities - ";
								
			if ($('select_other_city')) {
				$('select_other_city').style.display = 'block';
			}
			
			no.innerHTML 	= display;
			no.innerText 	= display;
			no.value 		= "";

			return false;
		};

		
		var txt 	= r.responseText.split("\n");

		selBox.disabled = false;

		try {
			for(var i = 0; i<txt.length; i++) {

				var val = txt[i].split("|");

				if (val[1] != undefined) {

					var no = document.createElement("OPTION");

					Try.these(
						function() { selBox.add(no); },
						function() { selBox.options.add(no); }
					);

					no.innerHTML 	= val[1];
					no.innerText 	= val[1];
					no.value 		= val[0];

				};

			}
		} catch(e) {
			alert('this one?' + e);
		}

	});

}


_a['updateStateSelect'] = function(countryElement, stateID) {

	var stateSelBox = $(stateID);
	stateSelBox.style.display = "none";
	// clear all options
	removeAllOptions(stateSelBox);
	
	// GETSTATES
	_a.call(countryElement.form.action, 'getStates', { country: $F(countryElement) }, function(r) {
		if (r.responseText == '0') {
			stateSelBox.style.display = "none";
			return false;
		}
		
		var txt 	= r.responseText.split("\n");

		stateSelBox.style.display = "block";

		try {
			for(var i = 0; i<txt.length; i++) {

				var val = txt[i].split("|");

				if (val[1] != undefined) {

					var no = document.createElement("OPTION");

					Try.these(
						function() { stateSelBox.add(no); },
						function() { stateSelBox.options.add(no); }
					);

					no.innerHTML 	= val[1];
					no.innerText 	= val[1];
					no.value 		= val[0];

				};

			}
		} catch(e) {
			alert('this one?' + e);
		}
	});

}

_a['updateJobCitySelect'] = function(countryElement, cityID) {

	var selBox 	= $(cityID);
	selBox.disabled = false;
	// clear all options
	removeAllOptions(selBox);

	_a.call(countryElement.form.action, 'getCities', { country: $F(countryElement) }, function(r) {

		if (r.responseText == '0') {

			selBox.disabled = true;

			var no = document.createElement("OPTION");
			Try.these(
				function() { selBox.add(no); },
				function() { selBox.options.add(no); }
			);

			var display 	= countryElement.selectedIndex > 1 
								? " - No cities found for country " + countryElement[countryElement.selectedIndex].innerHTML + " - "
								: " - all cities - ";
			no.innerHTML 	= display;
			no.innerText 	= display;
			no.value 		= "";

			return false;
		};

		
		var txt 	= r.responseText.split("\n");

		selBox.disabled = false;

		try {
			for(var i = 0; i<txt.length; i++) {

				var val = txt[i].split("|");

				if (val[1] != undefined) {

					var no = document.createElement("OPTION");

					Try.these(
						function() { selBox.add(no); },
						function() { selBox.options.add(no); }
					);

					no.innerHTML 	= val[1];
					no.innerText 	= val[1];
					no.value 		= val[0];

				};

			}
		} catch(e) {
			alert('this one?' + e);
		}

	});

}

_a['resetSearchForm'] = function(el) {
	var els = document.getElementsBySelector('form.member_search_form tr.advanced');

	for(var i = 0; i<els.length;i++) {
		try {
			els[i].style.visibility = 'hidden';
			els[i].style.display 	= 'none';
		} catch(e) {
			els[i].style.display 	= 'block';
		}
	}

		var form = document.getElementsBySelector('form.member_search_form').shift();
		var formElements = Form.getElements(form);
		for(var i = 0; i < formElements.length; i++) {
			try {
				var el = formElements[i];
				switch(el.name) {

					case 'gender':
					case 'search_all':
						el.checked = false;
						break;

					case 'nationality':
						el.selectedIndex = 0;
						break;

					case 'country':
						el.selectedIndex = 0;
						el.onchange();
						break;

					case 'city':
						el.disabled = true;
					case '_submit':
						break;

					default:
						el.value = "";
						break;
				}

			} catch(e) { alert(e); };
		}


	try {
		$('qms_go_advanced').style.display 	= 'inline';
		$('qms_go_advanced_field').value = 0;
		$('ms_content_block').style.display = 'none';
	} catch(e) {};
}
_a['goMemberSearchAdvanced'] = function(el) {
	var els = document.getElementsBySelector('form.member_search_form tr.advanced');

	for(var i = 0; i<els.length;i++) {
		try {
			els[i].style.visibility = 'visible';
			els[i].style.display 	= 'table-row';
		} catch(e) {
			els[i].style.display 	= 'block';
		}
	}

	el.style.display = 'none';
	$('qms_go_advanced_field').value = 1;
}
_a['showEventRegisterForm'] = function(id) {

	_a.call('/event/main', 'getRegisterForm', { event: id }, function(r) {

		$('register_form_' + id).innerHTML = r.responseText;

	});
}
_a['deleteInsert'] = function(id) {
	if (!confirm('Are you sure?')) return false;

	try {
		_a.call('/admin/insert/delete', 'delete', { id: id }, function(r) {
			$('insert_id_' + id).innerHTML = '<div>' + r.responseText + '</div>';
		});
	} catch (e) {
		alert(e);
	}
}
_a['pollSubmitted'] = function(form, r) {
	Form.disable(form);
}


var pop_count = 0;
function openPopup(a, width, height) {

	target = target = a.target ? a.target : 'new_popup' + pop_count++;
	var newWin = window.open(a.href, target, 'height='+height+', width='+width+', menubar=no, scrollbars=yes, location=no, resizable=yes, status=no, titlebar=yes');
	newWin.focus();
	return newWin;

}

function detector_checkQuestions(form, alertId) {
	var result = false;
	var els = form.elements;
	var nmold = "start";
	var elold = 0;
	for (i=0; i<els.length; i++) {
		var el = els[i];
		var nm = el.name;
		if (nm.indexOf("vraag") >= 0) {
			if (nm.indexOf(nmold) == -1) {
				if (nmold.indexOf("start") == -1) {
					if (result == false) {
						alert ($(alertId).innerHTML);
						elold.focus();
						return false;
					}
				}
				nmold = nm;
				elold = el;
				result = false;
			}
			if (el.checked) {
				result = true;
			}
		}
	}
	return true;
}

/* Flashmap Interface */
function icon_clicked(url) {
	document.location.href = url;
}
function setCoords(pid, x, y) {

	try {
		$$('input.map_coord_x').each(function(e) { e.value = x; });
	} catch(e) {};
	try {
		$$('input.map_coord_y').each(function(e) { e.value = y; });
	} catch(e) {};
	try {
		$$('input.map_pid').each(function(e) { e.value = pid; });
	} catch(e) {};

}
/**
 * Replacement for Form.disable - although 
 * that one might work better, it does funny
 * things to the page position in some cases
*/
function disableForm(frm) {
	$(frm).getElements().each(function(elm) {
		try {
			elm.disabled = true;
		} catch(e) { };
	});

}



