Dictionary = {
	// Query Event Handler
	Query: function(e){
		if(e){
			if(e.preventDefault) e.preventDefault();
		}
		//query = dojo.objectToQuery(dijit.byId("DictionaryQueryForm").getValues());
		var query = ["isSearch=true"];
		dojo.query(".Controls", dojo.byId("Dictionary")).forEach(function(controls){
			dojo.query(".dijitTitlePane, .dijitTabPane", controls).forEach(function(controlPanel){
				if(dijit.byNode(controlPanel).open || dijit.byNode(controlPanel).selected){
					dojo.query("form", controlPanel).forEach(function(control){
						query.push(dojo.objectToQuery(dijit.byNode(control).getValues()));
					});
				}
			});
		});
		query = query.join("&");;
		dojo.query(".WordList", dojo.byId("Dictionary")).forEach(function(node){
			dijit.byNode(node).setHref("/Dictionary/WordList.php?" + query);
		});
	},
	SpecialQuery: function(type, targetPane, fromLang, toLang, minimalMode, jumpFunc){
		var query = ["isSearch=true"];
		if(minimalMode) query.push("minimalMode=true");
		if(jumpFunc) query.push("jumpFunc=" + jumpFunc);
		if(fromLang) query.push("translateFrom=" + fromLang);
		else query.push("translateFrom=" + dijit.byId("baseLang").value);	
		if(toLang) query.push("translateTo=" + toLang);
		else query.push("translateTo=" + dijit.byId("transLang").value);
		switch(type){
			case('top'): query.push("ordering=top");	break;
			case('random'): query.push("ordering=random"); break;
			case('randompictures'):	query.push("ordering=randompictures"); break;
			case('randomneedspoken'):	query.push("ordering=randomneedspoken"); break;
			case('randomhasspoken'):	query.push("ordering=randomhasspoken"); break;
			case('randomneeddefinition'):	query.push("ordering=randomneeddefinition"); break;
			case('randomhasdefinition'):	query.push("ordering=randomhasdefinition"); break;
		}
		if(targetPane) query.push("ref=" + targetPane.id);
		query = query.join("&");
		if(targetPane){
			
			targetPane.setHref("/Dictionary/WordList.php?" + query);
		} else {
			dojo.query(".WordList", dojo.byId("Dictionary")).forEach(function(node){
				dijit.byNode(node).setHref("/Dictionary/WordList.php?" + query);
			});
		}
	},

	TagSearch: function(tag, lang, toLang){
		var query = [
			"isSearch=true",
			lang ? "translateFrom=" + lang : "",
			toLang && toLang != "---" ? "translateTo=" + toLang : "",
			"theme[]=" + tag
		];
		dijit.byId("Main").selectChild(dijit.byId("Dictionary"));
		dojo.query(".WordList", dojo.byId("Dictionary")).forEach(function(node){
			dijit.byNode(node).setHref("/Dictionary/WordList.php?" + query.join("&"));
		});
	},

	// Select Word Static
	SelectWord: function(wordId){
		var query = dojo.objectToQuery({w: wordId});
		dojo.query(".WordDisplay", dojo.byId("Dictionary")).forEach(function(node){
			dijit.byNode(node).setHref("/Dictionary/WordDisplay.php?" + query);
		});
		dojo.xhrGet({
			url: "/Dictionary/wordBackConv.php?" + dojo.objectToQuery({w:wordId}),
			handleAs: "text",
			load: dojo.hitch({wordId: wordId}, function(data){
			})
		});
		window.location.hash = "Dictionary/" + wordId;
	},
	SelectWordByName: function(word, culture){
		dojo.xhrGet({
			url: "/Dictionary/wordConv.php?" + dojo.objectToQuery({w:word, c:culture}),
			handleAs: "text",
			load: function(wordId){
				if(wordId){
					Dictionary.SelectWord(wordId);
				} else {
					alert("Sorry, word not in dictionary.");
				}
			}
		});
		

	},
	LoadModules: function(){
		dojo.require("dojo.parser");
		dojo.require("dijit.layout.TabContainer");
		dojo.require("dojox.form.BusyButton");
		dojo.require("dijit.layout.AccordionContainer");
		dojo.require("dojo.fx");
		dojo.require("dijit.Dialog");
		dojo.require("dijit.form.Button");
		dojo.require("dijit.form.ValidationTextBox");
		dojo.require("dojox.form.PasswordValidator");
		dojo.require("dijit.form.DateTextBox");
		dojo.require("dojox.form.Rating");
		dojo.require("dijit.form.Textarea");
		dojo.require("dojo.data.ItemFileWriteStore");
		dojo.require("dojox.form.FileInput");
		dojo.require("dijit.Toolbar");
		dojo.require("dijit.layout.ContentPane")
		dojo.require("dijit.layout.BorderContainer");
		dojo.require("dijit.form.Form");
		dojo.require("dijit.form.TextBox");
		dojo.require("dijit.form.CheckBox");
		dojo.require("dijit.Tooltip");
		dojo.require("dijit.TitlePane");
		dojo.require("dojox.form.DropDownSelect");
		dojo.require("dijit.layout.StackContainer");
		dojo.require("dojox.form.DropDownStack");
		dojo.require("dojox.form.CheckedMultiSelect");
		dojo.require("dijit.form.FilteringSelect");
		dojo.require("dojox.image.Lightbox");
		dojo.require("dojox.image.Badge");
		dojo.require("dojo.cookie");
		// dojo.require("SM2.SoundManager");

		Dictionary.Player = null;
		
		soundManager.debugMode = false; // disable or enable debug output

		soundManager.url = "/js/SM2/"; // path to directory containing SM2 SWF
		soundManager.onload = function() {
			// Should be eventually totaly stripped.
		}

		dojo.addOnLoad(function(){

/*
			// BETA NOTICE
			switch(dojo.cookie('elovivo.hasran')){
				case("reset"): dojo.cookie('elovivo.hasran', "false", {expires: -1}); break;
				default: Dictionary.openDialog("ElovivoBetaNotice", "Elovivo Beta Notice", "betanotice.php");
				case("true"): dojo.cookie('elovivo.hasran', "true", {expires: 30}); break;
			}
*/


			Dictionary.onDownloadStartDefaultAction = dijit.layout.ContentPane.prototype.onDownloadStart;

			dijit.layout.ContentPane.prototype.onDownloadStart = function() {
				return [
					"<div style='text-align: center; font-size: larger; margin-top: 2em;'>",
					"<img src='frw8at_ajaxldr_6.gif' alt='Loading...' />",
					"</div>"
				].join("\n");
			}

			if(dojo.isIE == 7) dojo.query(".WordDisplay", dojo.byId("Dictionary")).forEach(function(node){
				dojo.connect(dijit.byNode(node), "onLoad", function(){
					setTimeout(dojo.hitch({domNode: this.domNode}, function(){
						dojo.query(".dijitTitlePane", this.domNode).forEach(function(n){
							var tpane = dijit.byNode(n);
							if(tpane.open) tpane.toggle();
						});
					}), 200);
				});
			});

			for(var i = 500; i < 5000; i += 1000){ 
				setTimeout("dijit.byId('TopContainer').resize()", i);
			}
		});
	}
}



			Dictionary.LoadModules();
			google.load("language", "1");
			google.load('search', '1.0');


			dojo.addOnLoad(function(){

				setTimeout(function(){
					dojo.connect(dijit.byId("Home"), "onShow", function(){
						dijit.byId("MainFeed").refresh();
					});
				}, 10000);

				Dictionary.MessageChecker = function(){
					dojo.xhrGet({
						url: "numUnseenMessages.php",
						handleAs: "json",
						load: function(resp){
							if(resp.ok && resp.messages){
								dijit.byId("ToolBar.Messages").setLabel("Messages <strong>(" + resp.messages + " new)</strong>");
								if(Dictionary.NumUnseenMessages < resp.messages){
									alert("You have new messages");
								}
								Dictionary.NumUnseenMessages = resp.messages;
								MessageCenter.refreshCurrent();
							}	else {
								dijit.byId("ToolBar.Messages").setLabel("Messages");
							}
						}
					});
				}
				Dictionary.NumUnseenMessages = 0;
				Dictionary.MessageChecker();
				setInterval(Dictionary.MessageChecker, 180000);

// 				if(dojo.isFF) dojo.style("TwitterFollow", {
// 					position: "relative", top: "3px"
// 				});

				var options = new google.search.SearcherOptions();
				options.setExpandMode(google.search.SearchControl.EXPAND_MODE_OPEN);
				google.search.Search.getBranding(dojo.byId("GoogleBranding"));

				Dictionary.GoogleSearch = new google.search.SearchControl();
				Dictionary.GoogleSearch.addSearcher(new google.search.WebSearch(), options);
				Dictionary.GoogleSearch.draw(dojo.byId("GoogleSearchResults"));

				Dictionary.Languages.Store = new dojo.data.ItemFileWriteStore({
					data: {identifier: 'id', label: 'label', items: []}
				});
				var c = 0;
				dojo.forEach(Dictionary.Languages.All, function(lang){
					Dictionary.Languages.Store.newItem({"id": lang.id, "label": lang.label, "code": lang.code}, null);
					c ++;
				});
			});

			function translate() {
				var source = dojo.byId("translateIn").value;
				var srclang = dijit.byId("translateFrom").value;
				var destlang = dijit.byId("translateTo").value;
				var len = source.length;
				// Google Language API accepts 500 characters per request
				var words = 500;
				// This is for English pages, you can change the
				// sourcelang variable for other languages
				dijit.byId("translateOut").setContent("");
				for(i=0; i<=(len/words); i++) {
					setTimeout(
						dojo.hitch({
							src: srclang,
							dest: destlang,
							text: source.substr(i*words, words)
						}, function(){
							google.language.translate (this.text, this.src, this.dest, function(result){
								if (!result.error) {
									dijit.byId("translateOut").setContent(
										dojo.byId("translateOut").innerHTML + result.translation
									);
								} else {
									dijit.byId("translateOut").setContent(result.error.message);
								}
							});
					}), i*words);
				}
			}
			function resizeTranslateBox(){
				if(dijit.byId("translateBox")._contentBox){
					dojo.byId("translateIn").style.width = (dijit.byId("translateBox")._contentBox.w - 15) + "px";
					dojo.byId("translateIn").style.height = (dijit.byId("translateBox")._contentBox.h - 15) + "px";
				}
			}
			dojo.addOnLoad(function(){
				dijit.byId("Main").getChildren().forEach(function(tab){
					if(dojo.attr(tab.domNode, 'urlhash')) tab.urlhash = dojo.attr(tab.domNode, 'urlhash');
				});
				// setTimeout(function(){ homeRandom('en', 'en'); }, 50);
				setTimeout(function(){
					var doneLoadAnim = dojo.fadeOut({node: dojo.byId("LoaderOverlay"), duration: 2000});
					dojo.connect(doneLoadAnim, "onEnd", function(){
						dojo.body().removeChild(dojo.byId("LoaderOverlay"));
						if(window.location.hash){
							var q = { w: window.location.hash.substring(1) };

							if(q.w){
								var switchedTab = false;
								dijit.byId("Main").getChildren().forEach(function(tab){
									if(tab.urlhash == q.w){
										dijit.byId("Main").selectChild(tab);
										switchedTab = true;
									}
								});
								if(!switchedTab){
									if(q.w.match('Dictionary')){
										q.parts = q.w.split("/");
										if(q.parts.length){
											q.wordId = q.parts[1] || false;
										}
										if(q.wordId) setTimeout(dojo.hitch(q, function(){ GotoWord(this.wordId)}), 500);
									} else if (q.w.match('Help')){
										setTimeout(Dictionary.openHelpCenter, 100);
									} else if (q.w.match('Members')){
										setTimeout(Dictionary.MemberSearch, 100);
									} else if (q.w.match('Register')){
										setTimeout(initRegister, 100);
									} else if (q.w.match('Lesson-Lesson')){
										setTimeout(openLessons, 100);
									} else if (q.w.match('Games')){
										setTimeout(openGames, 100);
									} else if (q.w.match('Contributors')){
										setTimeout(openContributors, 100);
									}else if (q.w.match('Profile')) {
										q.parts = q.w.split("/");
										if(q.parts[1]) Dictionary.Profile.View(q.parts[1]);
									} else {
										dijit.byId("Main").selectChild(dijit.byId(q.w));
									}
								}
							}
						}
					});
					doneLoadAnim.play(1000);
				}, 100);

				//setInterval(resizeTranslateBox, 1000);

				dojo.subscribe("Main-selectChild", dijit.byId("Main"), function(tab){
					if(tab.urlhash) window.location.hash = tab.urlhash;
					else window.location.hash = tab.id;
				});



			});


			function homeRandom(params){
				var toLang = (typeof params.toLang == 'undefined' ? 'en' : params.toLang);
				var fromLang = (typeof params.fromLang == 'undefined' ? toLang : params.fromLang);

				Dictionary.SpecialQuery('random', dijit.byId("home_rand_words"), fromLang, toLang, true, "GotoWord");
			}

			function homeTopSearch(params){
				var toLang = (typeof params.toLang == 'undefined' ? 'en' : params.toLang);
				dijit.byId("homeTopSearch").setHref("topWord.php?c="+toLang);
			}

			function initRegister(){
				dojo.require("dojox.form.DateTextBox");
				var main = dijit.byId("Main");
				if(dijit.byId("registerForm")){
					dijit.byId("Main").getChildren().forEach(function(tab){
						console.dir([tab.attr("title")]);
						if(tab.attr("title") == "Register"){
							dijit.byId("Main").selectChild(tab);
						}
					});
				} else {
					var register = new dijit.layout.ContentPane({
						title: "Register",
						id: "Register",
						closable: true,
						href: "register.php"
					});
					main.addChild(register)
					//dijit.byId("loginDlg").onCancel();
					main.selectChild(register);
				}
			}

			function tryRegister(args){
				var form = dijit.byId("registerForm");
				dojo.stopEvent(args[0]);
				if(form.isValid()){
					var vals = form.getValues();
					vals.doRegister = true;
					dojo.xhrPost({
						url: "register.php",
						content: vals,
						handleAs: "json",
						sync: true,
						load: function(data){
							if(data.result == 'OK'){
								if(confirm("You have been successfully registered.\n Click Ok to log in.")){
									window.location.hash = "Home";
									dojo.hitch({
										getValues: dojo.hitch(vals, function(){
											return {
												email: this.email,
												password: this.password
											}
										})
									}, tryLogin)();
								}
							} else {
								alert(data.result);
							}
						}
					});
				} else {
					alert("Please make sure that all required fields are filled and valid.");
				}
			}

			function tryLogin(){
				var vals = this.getValues();
				dojo.xhrPost({
					url: "login.php",
					content: vals,
					handleAs: "json",
					sync: true,
					load: function(data){
						if(data.result == 'OK'){
							window.location.reload(true);
						} else {
							alert(data.result);
						}
					}
				});
			}


			function highlight(query){
				dojo.query(query).forEach(function(n){
					var curColor = dojo.style(n, "backgroundColor");
					dojo.anim(n, {backgroundColor: "#F0CA72"}, 1000, dojo.fx.easing.expoInOut, dojo.hitch({query: query, oldColor: curColor}, function(){
						dojo.query(this.query).forEach(function(n){
							dojo.anim(n, {backgroundColor: this.oldColor}, 1000, dojo.fx.easing.expoInOut, null, 1000);
						});
					}));
				});
			}

			function GotoWord(WordId){
				dijit.byId("Main").selectChild(dijit.byId("Dictionary"));
				dojo.query(".WordList", dojo.byId("Dictionary")).forEach(function(node){
					// make wordlist 0 width;
					//dijit.byNode(node).attr("style", {width: "0px"});
				});
				Dictionary.SelectWord(WordId);
			}

			function showWordNet(clicked){
				dojo.query(".WordNetDefinition", clicked.parentNode.parentNode).forEach(function(node){
					dojo.fx.wipeIn({node: node, duration: 1000}).play();
				});
				clicked.innerHTML = "View more definitions -";
				clicked.onclick = function(){ hideWordNet(this) };
			}

			function hideWordNet(clicked){
				dojo.query(".WordNetDefinition", clicked.parentNode.parentNode).forEach(function(node){
					dojo.fx.wipeOut({node: node, duration: 750}).play();
				});
				clicked.innerHTML = "View more definitions +";
				clicked.onclick = function(){ showWordNet(this) };
			}

			function dddpicker(tab, item, value, label){
				if(label){
					dijit.byId(tab+item).setLabel(label);
				} else {
					dijit.byId(tab+item).setLabel(value);
				}

				if(tab == 'home' && item == 'searchtype' && value !== "Google"){
					dojo.fx.wipeOut({node: dojo.byId("GoogleSearch")}).play();
					var anim = dojo.fadeIn({node: dojo.byId("homesearchlangchooser")});
					dojo.connect(anim, 'onBegin', function(){
						dojo.byId("homesearchlangchooser").style.display = 'inline';
					});
					anim.play();
				} else if (tab == 'home' && item == 'searchtype') {
					dojo.fx.wipeIn({node: dojo.byId("GoogleSearch")}).play();
					var anim = dojo.fadeOut({node: dojo.byId("homesearchlangchooser")});
					dojo.connect(anim, 'onEnd', function(){
						dojo.byId("homesearchlangchooser").style.display = 'none';
					});
					anim.play();
				}

				dojo.byId(tab+item+'value').value = value;
				dijit.byId(tab+item+'dialog').onCancel();
			}

			// There probably should be a cleaner way to do this...
			function ObjectToQuery(it){
				var e = encodeURIComponent;
				var q = "";
				if(it){
					if(dojo.isObject(it)){
						for(var i in it){
							if(dojo.isObject(it[i])){
								for(var j in it[i]){
									if(dojo.isObject(it[i][j])){
										for(var k in it[i][j]){
											if(dojo.isObject(it[i][j][k])){
												for(var l in it[i][j][k]){
													q += e(i + "[" + j + "][" + k + "][" + l + "]") + "=" + e(it[i][j][k][l]) + "&";
												}
											} else {
												q += e(i + "[" + j + "][" + k + "]") + "=" + e(it[i][j][k]) + "&";
											}
										}
									} else {
										q += e(i + "[" + j + "]") + "=" + e(it[i][j]) + "&";
									}
								}
							} else {
								q += e(i) + "=" + e(it[i]) + "&";
							}
						}
					} else {
						q += e(it) + "&";
					}
					return q.substring(0, q.length - 1);
				} else {
					return false;
				}
			}

			Dictionary.openHelpCenter = function(){
				var main = dijit.byId("Main");
				if(dijit.byId("Help"))	main.selectChild(dijit.byId("Help"));
				else {
					var helpTab = new dijit.layout.ContentPane({
						id: "Help",
						title: "Help / Feedback",
						closable: true,
						href: "helpCenter.php",
						style: "padding: 0px;"
					});
					main.addChild(helpTab)
					main.selectChild(helpTab);
				}
			}

			Dictionary.openContributors = function(){
				var main = dijit.byId("Main");
				if(dijit.byId("Contributors")){
					main.selectChild(dijit.byId("Contributors"));
					dijit.byId("Contributors").refresh();
				} else {
					var contribTab = new dijit.layout.ContentPane({
						id: "Contributors",
						title: "Top Contributors",
						closable: true,
						href: "contributors.php",
						style: "padding: 0px;"
					});
					main.addChild(contribTab)
					main.selectChild(contribTab);
				}
			}

			Dictionary.openGames = function(){
				var main = dijit.byId("Main");
				if(dijit.byId("Games")){
					main.selectChild(dijit.byId("Games"));
					dijit.byId("Games").refresh();
				} else {
					var gamesTab = new dijit.layout.ContentPane({
						id: "Games",
						title: "Games",
						closable: true,
						href: "games/browser.php",
						style: "padding: 0px;"
					});
					main.addChild(gamesTab)
					main.selectChild(gamesTab);
				}
			}

			Dictionary.openLessons = function(){
				var main = dijit.byId("Main");
				if(dijit.byId("Lesson-Lesson")){
					main.selectChild(dijit.byId("Lesson-Lesson"));
					dijit.byId("Lesson-Lesson").refresh();
				} else {
					var lessonsTab = new dijit.layout.ContentPane({
						id: "Lesson-Lesson",
						title: "Lessons",
						closable: true,
						href: "lessons.php",
						style: "padding: 0px;"
					});
					main.addChild(lessonsTab)
					main.selectChild(lessonsTab);
				}
			}


			Dictionary.TimedRefresh = function(){ // Expects to be hitched.
				var now = new Date();
				if(this.lastRefresh && (now.getTime() - this.lastRefresh.getTime()) > 60000 ){
					setTimeout( dojo.hitch(this, function(){this.refresh();}), 500);
					this.lastRefresh = now;
				} if(!this.lastRefresh) this.lastRefresh = now;
			}

			Dictionary.openDialog = function(id, title, href){

				dojo.require("dojox.widget.Dialog");
				dojo.require("dojo.fx.easing");

				var pane = dijit.byId(id);
				if(!pane){
					var pane = new dojox.widget.Dialog({
						title: title,
						id: id,
						//draggable: true,
						sizeToViewport: true,
						viewportPadding: 100,
						easing: dojo.fx.easing.expoInOut,
						sizeDuration: 300,
						executeScripts: true,
						//sizeMethod:"combine",
						href: href
					});

					dojo.connect(pane, "show", function(){
						var resizer = dojo.hitch(this, function(){
							dojo.query(".dijitBorderContainer", this.containerNode).forEach(function(n){
								dijit.byNode(n).resize();
							});
						});
						setTimeout(resizer, 2000);
						setTimeout(resizer, 5000);
						setTimeout(resizer, 10000);
					});
					pane.startup();
				} else {					
					if(pane.href != href) pane.setHref(href);
				}
				pane.show();
			}

			Dictionary.report = function(type, id){
				var reason = prompt("Please briefly describe the abuse or mistake:");
				if(reason){
					dojo.xhrPost({
						url: 'report.php',
						handleAs: 'json',
						content: {
							type: type,
							id: id,
							reason: reason
						},
						load: function(data){
							if(data.ok){
								alert("The item has been reported");
							} else {
								if(data.error) alert(data.error);
								else alert("There was an error sending the report. Please try again.");
							}
						}
					});
				} else {
					alert("You did not specify any details.\nAbuse report was not sent.");
				}
			}

			Dictionary.AddA = {

				Word: function(word, wordtype, language){
					if(word.length && wordtype && language){
						Dictionary.Post('Word', language, wordtype, word, function(result){
							if(result.ok){
								Dictionary.SelectWord(result.id);
							}
						});
					}
				},
				Tag: function(kws, wordId){
					if(kws.tag && wordId && kws.tag != "Enter the tag here... "){
						Dictionary.Post('Tag', 'Add', wordId, kws.tag, function(result){
							if(result.ok){
								// hide textbox and notify success
								dojo.query(".WordDisplay", dojo.byId("Dictionary")).forEach(function(node){
									dijit.byNode(node).refresh();
								});
							}
						});
					}
				},
				Sentence: function(kws, wordId){
					if(kws.sentence && wordId && kws.sentence != "Write your sentence here... "){
						Dictionary.Post('Resource', 'Sample Sentence', wordId, kws.sentence, function(result){
							if(result.ok){
								// hide textbox and notify success
								dojo.query(".WordDisplay", dojo.byId("Dictionary")).forEach(function(node){
									dijit.byNode(node).refresh();
								});
							}
						});
					}
				},
				Definition: function(kws, wordId){
					if(kws.definition && wordId && kws.definition != "Write your definition here..."){
						Dictionary.Post('Resource', 'Definition', wordId, kws.definition, function(result){
							if(result.ok){
								// hide textbox and notify success
								dojo.query(".WordDisplay", dojo.byId("Dictionary")).forEach(function(node){
									dijit.byNode(node).refresh();
								});
							}
						});
					}
				},
				Translation: function(kws, wordId, callback){

					if( typeof(callback) == "undefined" ){
						callback = function(){
							alert("Thank you, your translation is now awaiting approval.");
							dojo.query(".WordDisplay", dojo.byId("Dictionary")).forEach(function(node){
								dijit.byNode(node).refresh();
							});
						}
					}

					if(kws.language && wordId && kws.translation && kws.translation != "Add your translation here..."){
						Dictionary.Post('Translation', kws.language, wordId, kws.translation, dojo.hitch({cb:callback}, function(result){
							if(result.ok){
								this.cb();
							} else if (result.error == "exists"){
								var dialog = Dictionary.Edit.Dialog();
								dialog.attr('title', 'Choose translation');
								var heading = document.createElement("P");
								heading.innerHTML = "Multiple entries have been found for the word <strong>" + result.newword + "</strong>. Please select an option from the list below.";
								var optionList = document.createElement("UL");
								optionList.style.listStyle = "none";
								dojo.forEach(result.options, dojo.hitch({cb:this.cb}, function(option){
									optionList.appendChild(document.createElement("LI"));
									var worddata = {translation: option, linkto: wordId};
									var selectButton = new dijit.form.Button({
										label: "Select",
										onClick: dojo.hitch({worddata:worddata, cb:this.cb}, function(){
											Dictionary.Dialog.hide();
											Dictionary.AddA.Translation({
												translation: this.worddata.translation.id + "|||" + this.worddata.translation.typeid + "|||" + this.worddata.translation.word,
												language: kws.language
											}, this.worddata.linkto, this.cb);
										})
									});
									selectButton.worddata = worddata;
									optionList.lastChild.appendChild(selectButton.domNode);
									optionList.lastChild.appendChild(document.createElement("SPAN"));
									optionList.lastChild.lastChild.innerHTML = " &nbsp; &nbsp; <strong>" + option.word + " (" + option.type + ")</strong>";
								}));
								dialog.containerNode.appendChild(heading);
								dialog.containerNode.appendChild(optionList);
								dialog.show();
							} else {
								alert(result.error);
							}
						}));
					}
				}
			}

			Dictionary.Post = function(classname, classtype, wordId, item, onAdded){
				if(!onAdded) onAdded = function(){};
				if(classname && classtype && wordId && item){
					dojo.xhrPost({
						url: 'addItem.php',
						handleAs: 'json',
						content: {
							classname: classname,
							classtype: classtype,
							wordId: wordId,
							item: item
						},
						load: onAdded
					});
				}
			}


			Dictionary.Edit = {
				Sentence: function(sentenceId){
					Dictionary.Get(sentenceId, 'Sample Sentence', function(data){
						var dialog = Dictionary.Edit.Dialog();
						dialog.attr('title', 'Edit Sentence');
						var sentenceInput = new dijit.form.TextBox({
							name: "sentence",
							value: data.Data,
							style: "width: 80%;"
						});
						var sentenceEdit = new dojox.form.BusyButton({
							label: "Save",
							busyLabel: "Saving...",
							timeout: 2000,
							onClick: function(){
								var newSentence = dijit.byNode(this.domNode.previousSibling).value;
								if(newSentence){
									Dictionary.Put.Sentence(sentenceId, newSentence);
								} else {
									if(confirm("This will delete this sentence, are you sure you want to do this?")){
										Dictionary.Delete.Sentence(sentenceId);
									}
								}
							}
						});
						dialog.containerNode.appendChild(sentenceInput.domNode);
						dialog.containerNode.appendChild(sentenceEdit.domNode);

						var errata = document.createElement("DIV");
						errata.innerHTML = "<span class='stamp'>Notice: Rating will be reset to zero.</span>";
						dialog.containerNode.appendChild(errata);

						dialog.show();

					});
				},
				Definition: function(definitionId){
					Dictionary.Get(definitionId, 'Definition', function(data){
						data.Data = data.Data.replace(/<br \/>/gi, "");
						var dialog = Dictionary.Edit.Dialog();
						dialog.attr('title', 'Edit Definition');
						var definitionInput = new dijit.form.Textarea({
							name: "definition",
							value: data.Data,
							style: "width: 80%;"
						});
						var definitionEdit = new dojox.form.BusyButton({
							label: "Save",
							busyLabel: "Saving...",
							timeout: 2000,
							onClick: function(){
								var newDefinition = dijit.byNode(this.domNode.previousSibling).value;
								if(newDefinition){
									Dictionary.Put.Definition(definitionId, newDefinition);
								} else {
									if(confirm("This will delete this definition, are you sure you want to do this?")){
										Dictionary.Delete.Definition(definitionId);
									}
								}
							}
						});
						dialog.containerNode.appendChild(definitionInput.domNode);
						dialog.containerNode.appendChild(definitionEdit.domNode);

						var errata = document.createElement("DIV");
						errata.innerHTML = "<span class='stamp'>Notice: Rating will be reset to zero.</span>";
						dialog.containerNode.appendChild(errata);

						dialog.show();

					});
				},
				Dialog: function(){
					if(!Dictionary.Dialog){
						Dictionary.Dialog = new dijit.Dialog({
							title: "Edit",
							style: "width: 50%;"
						});
					}
					Dictionary.Dialog.setContent("");
					return Dictionary.Dialog;
				}
			}

			Dictionary.Put = {
				Sentence: function(id, sentence){
					dojo.xhrPost({
						url: "putItem.php",
						handleAs: 'json',
						content: {
							id: id,
							data: sentence,
							"class": "Sample Sentence"
						},
						load: Dictionary.Put.onPut
					});
				},
				Definition: function(id, definition){
					dojo.xhrPost({
						url: "putItem.php",
						handleAs: 'json',
						content: {
							id: id,
							data: definition,
							"class": "Definition"
						},
						load: Dictionary.Put.onPut
					});
				},
				onPut: function(data){
					if(data.ok){
						Dictionary.Dialog.setContent("Changes Saved");
						setTimeout(function(){
							Dictionary.Dialog.hide();
							dojo.query(".WordDisplay", dojo.byId("Dictionary")).forEach(function(node){
								dijit.byNode(node).refresh();
							});
						}, 2000);
					} else {
						Dictionary.Dialog.setContent(data.error);
					}
				}
			}

			Dictionary.Delete = {
				Word: function(id){
					if (confirm("Are you certain that you wish to delete this word?"))
						dojo.xhrPost({
							url: "deleteItem.php",
							handleAs: 'json',
							content: {
								"id": id,
								"class": "Word"
							},
							load: Dictionary.Delete.onDelete
						});
				},
				Tag: function(wid, tid){
					if (confirm("Are you certain that you wish to remove this tag?"))
						dojo.xhrPost({
							url: "deleteItem.php",
							handleAs: 'json',
							content: {
								"id": wid,
								"tid": tid,
								"class": "Tag"
							},
							load: Dictionary.Delete.onDelete
						});
				},
				Translation: function(wid, tid){
					if (confirm("Are you certain that you wish to remove this translation link?"))
						dojo.xhrPost({
							url: "deleteItem.php",
							handleAs: 'json',
							content: {
								"id": wid,
								"tid": tid,
								"class": "Translation"
							},
							load: Dictionary.Delete.onDelete
						});
				},
				Sentence: function(id){
					dojo.xhrPost({
						url: "deleteItem.php",
						handleAs: 'json',
						content: {
							"id": id,
							"class": "Sample Sentence"
						},
						load: Dictionary.Delete.onDelete
					});
				},
				Definition: function(id){
					dojo.xhrPost({
						url: "deleteItem.php",
						handleAs: 'json',
						content: {
							"id": id,
							"class": "Definition"
						},
						load: Dictionary.Delete.onDelete
					});
				},
				UserAudio: function(id){
					dojo.xhrPost({
						url: "deleteItem.php",
						handleAs: 'json',
						content: {
							"id": id,
							"class": "User Word Audio"
						},
						load: Dictionary.Delete.onDelete
					});
				},
				SentenceAudio: function(id){
					dojo.xhrPost({
						url: "deleteItem.php",
						handleAs: 'json',
						content: {
							"id": id,
							"class": "User Sentence Audio"
						},
						load: Dictionary.Delete.onDelete
					});
				},
				onDelete: function(data){
					if(data.ok){
						dojo.query(".WordDisplay", dojo.byId("Dictionary")).forEach(function(node){
							dijit.byNode(node).refresh();
						});
 						Dictionary.Dialog.setContent("Item has been removed.");
 						setTimeout(function(){
 							Dictionary.Dialog.hide();
 							//dojo.query(".WordDisplay", dojo.byId("Dictionary")).forEach(function(node){
 							//	dijit.byNode(node).refresh();
 							//});
 						}, 2000);
					} else {
						Dictionary.Dialog.setContent(data.error);
					}
				}
			}

			Dictionary.Get = function(id, classname, onGet){
				dojo.xhrGet({
					url: 'getItem.php?id=' + id + '&class=' + encodeURIComponent(classname),
					handleAs: 'json',
					load: onGet
				});
			}

			Dictionary.ShowForms = function(link){
				var container = null;
				dojo.query(".wordforms", link.parentNode).forEach(function(n){
					if(dojo.style(n, "display") == "none"){
						dojo.fx.wipeIn({node: n}).play();
						link.innerHTML = "Forms -";
					} else {
						dojo.fx.wipeOut({node: n}).play();
						link.innerHTML = "Forms +";
					}
				});
			}

			Dictionary.New = {
				CertifyMessage: function(){
					var node = document.createElement("DIV");
					dojo.style(node, {
						"padding": "5px",
						"margin": "5px",
						"border": "1px solid #999"
					});
					node.innerHTML = '<strong style="font-size: smaller;">By clicking "Add" you certify that you have the right to distribute this content and that it does not violate the <a onclick=\'Dictionary.openDialog("TermsOfUse", "Terms Of Use", "terms.php");\' style="cursor:pointer; text-decoration: underline; display: inline;">Terms of Use</a>.</strong>';
					return node;
				},
				AudioUploadMessage: function(){
					var node = document.createElement("DIV");
					dojo.style(node, {
						"padding": "5px",
						"margin": "5px",
						"border": "1px solid #999"
					});
					node.innerHTML = '<strong style="font-size: smaller;">Click "submit" to save your recording.</strong>';
					return node;
				},
				Word: function(){
					dijit.byId("Main").selectChild(dijit.byId("Dictionary"));
					dojo.query(".WordDisplay", dojo.byId("Dictionary")).forEach(function(node){
						dijit.byNode(node).setHref("addWord.php");
					});
				},
				InputDialog: function(placeAtNode, classname, exists){
					exists = exists || false;
					var box = null;
					if(exists){
						dojo.query("."+classname, placeAtNode).forEach(function(node){
							box = new dijit.layout.ContentPane({}, node);
						});
					} else {
						box = new dijit.layout.ContentPane({"class": classname});
						placeAtNode.appendChild(box.domNode);
					}
					box.domNode.style.display = "none";
					var form = new dijit.form.Form();
 					box.domNode.appendChild(form.domNode);
					box.theForm = form;
					setTimeout(
						dojo.hitch(box, function(){
							dojo.fx.wipeIn({node: this.domNode}).play();
						}), 20
					);
					return box;
				},
				Tag: function(placeAtNode, wordId){
					var link = null;
					dojo.query("a.Add", placeAtNode).forEach(function(n){
						link = n;
					});
					var container = null;
					dojo.query(".newtag", placeAtNode).forEach(function(n){
						container = dijit.byNode(n);
					});
					if(container){
						if(container.domNode.style.display == 'none'){
							dojo.fx.wipeIn({node: container.domNode}).play();
							link.innerHTML = "Add a tag -";
						} else {
							dojo.fx.wipeOut({node: container.domNode}).play();
							link.innerHTML = "Add a tag +";
						}
					} else {
						var container = Dictionary.New.InputDialog(placeAtNode, 'newtag');
						var tagInput = new dijit.form.TextBox({
							name: "tag",
							style: "width:10em;",
							value: "Enter the tag here...",
							onFocus: function(){
								if (this.getValue() == "Enter the tag here...") this.setValue("");
							}
						});
						var tagSubmit = new dijit.form.Button({label: "Add", onClick: function(e){
							Dictionary.AddA.Tag(dijit.byNode(this.domNode.parentNode).getValues(), this.wordId);
						}});
						tagSubmit.wordId = wordId;
						container.theForm.domNode.appendChild(tagInput.domNode);
						container.theForm.domNode.appendChild(tagSubmit.domNode);

						var whatIsATag = new dijit.layout.ContentPane({
							"style": "padding: 5px; margin: 5px; border: 1px solid #999;"
						}).placeAt(container.theForm.domNode).setContent([
							"<small>",
							"<em><strong>What is a tag?</strong></em>",
							"A tag is a way to identify which words belong to common themes.",
							"For example, the word 'Snow' can be tagged with the following themes:",
							"weather, cold, or winter. Please only add one tag at a time.",
							"</small>"
						].join("\n"));

						link.innerHTML = "Add a tag -";
					}
				},
				Sentence: function(placeAtNode, wordId){
					var link = null;
					dojo.query("a.Add", placeAtNode).forEach(function(n){
						link = n;
					});
					var container = null;
					dojo.query(".newsentence", placeAtNode).forEach(function(n){
						container = dijit.byNode(n);
					});
					if(container){
						if(container.domNode.style.display == 'none'){
							dojo.fx.wipeIn({node: container.domNode}).play();
							link.innerHTML = "Add a sentence -";
						} else {
							dojo.fx.wipeOut({node: container.domNode}).play();
							link.innerHTML = "Add a sentence +";
						}
					} else {
						var container = Dictionary.New.InputDialog(placeAtNode, 'newsentence');
						var sentenceInput = new dijit.form.TextBox({
							name: "sentence",
							style: "width:80%;",
							value: "Write your sentence here...",
							onFocus: function(){
								if (this.getValue() == "Write your sentence here...") this.setValue("");
							}
						});
						var sentenceSubmit = new dijit.form.Button({label: "Add", onClick: function(e){
							Dictionary.AddA.Sentence(dijit.byNode(this.domNode.parentNode).getValues(), this.wordId);
						}});
						sentenceSubmit.wordId = wordId;
						container.theForm.domNode.appendChild(sentenceInput.domNode);
						container.theForm.domNode.appendChild(sentenceSubmit.domNode);
						container.theForm.domNode.appendChild(Dictionary.New.CertifyMessage());
						link.innerHTML = "Add a sentence -";
					}
				},
				Definition: function(placeAtNode, wordId, wordLanguage){
					var link = null;
					dojo.query("a.Add", placeAtNode).forEach(function(n){
						link = n;
					});
					var container = null;
					dojo.query(".newdefinition", placeAtNode).forEach(function(n){
						container = dijit.byNode(n);
					});
					if(container){
						if(container.domNode.style.display == 'none'){
							dojo.fx.wipeIn({node: container.domNode}).play();
							link.innerHTML = "Add a definition -";
						} else {
							dojo.fx.wipeOut({node: container.domNode}).play();
							link.innerHTML = "Add a definition +";
						}
					} else {
						var container = Dictionary.New.InputDialog(placeAtNode, 'newdefinition', true);
						var definitionInput = new dijit.form.Textarea({
							name: "definition",
							style: "width: 80%;",
							value: "Write your definition here...",
							onFocus: function(){
								if (this.getValue() == "Write your definition here...") this.setValue("");
							}
						});
						var definitionSubmit = new dijit.form.Button({label: "Add", onClick: function(e){
							Dictionary.AddA.Definition(dijit.byNode(this.domNode.parentNode).getValues(), this.wordId);
						}});
						definitionSubmit.wordId = wordId;
						container.theForm.domNode.appendChild(definitionInput.domNode);
						container.theForm.domNode.appendChild(definitionSubmit.domNode);

						if(wordLanguage){
							var langNotice = document.createElement("DIV");
							dojo.style(langNotice, {"padding": "5px",	"margin": "5px"});
							langNotice.innerHTML = "<strong>Note</strong>: Please write your definition in " + wordLanguage;
							container.theForm.domNode.appendChild(langNotice);
						}

						container.theForm.domNode.appendChild(Dictionary.New.CertifyMessage());
						link.innerHTML = "Add a definition -";
					}
				},
				Translation: function(placeAtNode, wordId){
					var link = null;
					dojo.query("a.Add", placeAtNode).forEach(function(n){
						link = n;
					});
					var container = null;
					dojo.query(".newtranslation", placeAtNode).forEach(function(n){
						container = dijit.byNode(n);
					});
					if(container){
						if(container.domNode.style.display == 'none'){
							dojo.fx.wipeIn({node: container.domNode}).play();
							link.innerHTML = "Add a translation -";
						} else {
							dojo.fx.wipeOut({node: container.domNode}).play();
							link.innerHTML = "Add a translation +";
						}
					} else {
						var container = Dictionary.New.InputDialog(placeAtNode, 'newtranslation');
						var translationLang = new dijit.form.FilteringSelect({
							name: "language",
							store: Dictionary.Languages.Store,
							labelAttr: "label",
							searchAttr: "label"
						});
						translationLang.setDisplayedValue("Choose Language");
						var translationInput = new dijit.form.TextBox({
							name: "translation",
							value: "Add your translation here...",
							onFocus: function(){
								if (this.getValue() == "Add your translation here...") this.setValue("");
							}
						});
						var translationSubmit = new dijit.form.Button({label: "Add", onClick: function(e){
							Dictionary.AddA.Translation(dijit.byNode(this.domNode.parentNode).getValues(), this.wordId);
						}});
						translationSubmit.wordId = wordId;
						container.theForm.domNode.appendChild(document.createElement("BR"));
						container.theForm.domNode.appendChild(translationLang.domNode);
						container.theForm.domNode.appendChild(document.createElement("BR"));
						container.theForm.domNode.appendChild(translationInput.domNode);
						container.theForm.domNode.appendChild(translationSubmit.domNode);
						link.innerHTML = "Add a translation -";
					}
				},
				Audio: function(placeAtNode, wordId){
					var link = null;
					dojo.query("a.Add", placeAtNode).forEach(function(n){
						link = n;
					});
					var container = null;
					dojo.query(".newaudio", placeAtNode).forEach(function(n){
						container = dijit.byNode(n);
					});
					if(container){
						if(container.domNode.style.display == 'none'){
							dojo.fx.wipeIn({node: container.domNode}).play();
							link.innerHTML = "Add audio file -";
						} else {
							dojo.fx.wipeOut({node: container.domNode}).play();
							link.innerHTML = "Add audio file +";
						}
					} else {
						var container = Dictionary.New.InputDialog(placeAtNode, 'newaudio');

						var audioInput = new dijit.layout.ContentPane({ href: "recorder.php?wid="+wordId+"&type=word" });

						var demoMov = document.createElement("DIV");
						dojo.style(demoMov, { textAlign: "right", padding: "3px", fontSize: "xx-small", float: "right" });
						new dijit.form.Button({ label: "View demo", onClick: function(){
							Dictionary.openDialog("WordAudioDemo", "Adding audio to words...", "youtube.php?link=Er0hmwG1uTs");
						}}).placeAt(demoMov);

						container.theForm.domNode.appendChild(demoMov);
						container.theForm.domNode.appendChild(document.createElement("BR"));
						container.theForm.domNode.appendChild(audioInput.domNode);
						
						container.theForm.domNode.appendChild(Dictionary.New.AudioUploadMessage());

						link.innerHTML = "Add audio file -";
						audioInput.startup();
					}
				},
				SentenceAudio: function(placeAtNode, sentenceId){
					var link = null;
					dojo.query("a.Add", placeAtNode).forEach(function(n){
						link = n;
					});
					var container = null;
					dojo.query(".newsentenceaudio", placeAtNode).forEach(function(n){
						container = dijit.byNode(n);
					});
					if(container){
						if(container.domNode.style.display == 'none'){
							dojo.fx.wipeIn({node: container.domNode}).play();
							link.innerHTML = "Add audio file -";
						} else {
							dojo.fx.wipeOut({node: container.domNode}).play();
							link.innerHTML = "Add audio file +";
						}
					} else {
						var container = Dictionary.New.InputDialog(placeAtNode, 'newsentenceaudio');
						container.theForm.domNode.style.color = "#000";


						var audioInput = new dijit.layout.ContentPane({ href: "recorder.php?wid="+sentenceId+"&type=sentence" });

						var demoMov = document.createElement("DIV");
						dojo.style(demoMov, { textAlign: "right", padding: "3px", fontSize: "xx-small", float: "right" });
						new dijit.form.Button({ label: "View demo", onClick: function(){
							Dictionary.openDialog("SentenceAudioDemo", "Adding audio to sentences...", "youtube.php?link=LD8TzioMjHY");
						}}).placeAt(demoMov);

						container.theForm.domNode.appendChild(demoMov);

						container.theForm.domNode.appendChild(document.createElement("BR"));
						container.theForm.domNode.appendChild(audioInput.domNode);
						//container.theForm.domNode.appendChild(document.createElement("BR"));
						//container.theForm.domNode.appendChild(audioSubmit.domNode);
						container.theForm.domNode.appendChild(Dictionary.New.AudioUploadMessage());
						link.innerHTML = "Add audio file -";
						audioInput.startup();
					}
				}
			}

			Dictionary.Rate = function(ItemType, ItemId, vote){
				if((ItemType.length > 3) && (ItemId >= 1) && (vote >= 1 && vote <= 5)){
					dojo.xhrPost({
						url: "Rate.php",
						handleAs: "json",
						content: {type: ItemType, id: ItemId, vote: vote},
						load: function(data){
							if(data.ok){

							} else {
								if(data.error){
									alert(data.error);
								} else {
									alert("An unknown error has occured");
								}
							}
						}
					});
				}
			}

			Dictionary.WordList = {
				ShowMore: function(requestVars){
					query = ObjectToQuery(requestVars);
					if(requestVars.ref)	var nRef = dojo.byId(requestVars.ref).parentNode;
					else var nRef = dojo.byId("Dictionary");
					dojo.query(".WordList", nRef).forEach(function(node){
						dojo.query(".ShowMore", node).forEach(function(showMoreNode){
							var pane = new dijit.layout.ContentPane();
							showMoreNode.parentNode.appendChild(pane.domNode);
							pane.setHref("/Dictionary/WordList.php?" + query);
							var anim = dojo.fx.wipeOut({node: showMoreNode});
							dojo.connect(anim, "onEnd", dojo.hitch(showMoreNode, function(){
								this.parentNode.removeChild(this);
							}));
							anim.play();
						});
					});
				}
			}

			Dictionary.Profile = {
				View: function(uid){

					// Close Message center on profile view.
					var msgCenter = dijit.byId("MessageCenter");
					if(msgCenter && msgCenter.open) dijit.byId("MessageCenter").hide();

					var alreadyOpen = false;
					dijit.byId("Main").getChildren().forEach(function(tab){
						if(tab.userId && tab.userId == uid){
							dijit.byId("Main").selectChild(tab);
							tab.refresh();
							alreadyOpen = true;
						}
					});
					if(alreadyOpen) return;

					dojo.xhrPost({
						url: "getNameByUid.php",
						handleAs: "json",
						content: {uid: uid},
						load: function(data){
							var main = dijit.byId("Main");
							var profile = new dijit.layout.ContentPane({
								title: data.nickname + "'s profile",
								closable: true,
								href: "profile.php?uid=" + uid
							});
							profile.urlhash = "Profile/" + uid;
							profile.userId = uid;
							main.addChild(profile)
							main.selectChild(profile);
						}
					});
				},
				Favorites: {
					ShowList: function (id, clicked){
						var panes = dijit.byNode(clicked.parentNode.parentNode.parentNode).getChildren();
							// 0 == FavList  1 == FavListList
						panes[0].setHref("showFavoriteList.php?id=" + id);
						if(clicked){
							var anims = [];
							anims.push(dojo.animateProperty({
								node: clicked,
								properties: {
									color: "#000", paddingLeft: 5
								}
							}));
							dojo.query(".FavLists a", panes[1].domNode).forEach(function(favLink){
								favLink.style.display = "block";
								if(favLink != clicked) anims.push(dojo.animateProperty({
									node: favLink,
									properties: {
										color: "#888", paddingLeft: 0
									}
								}));
							});
							var anim = dojo.fx.combine(anims);
							dojo.connect(anim, "onEnd", dojo.hitch(clicked, function(){
							}));
							anim.play();
						}
					},
					Remove: function(id){
						dojo.xhrPost({
							url: "removeFavorite.php",
							handleAs: "json",
							content: {fid: id},
							load: function(data){
								if(data.ok){
									dojo.query(".FavList").forEach(function(favlist){
										dijit.byNode(favlist).refresh();
									});
								} else {
									alert(data.error);
								}
							}
						});
					},
					RemoveList: function(id){
						dojo.xhrPost({
							url: "removeFavoriteList.php",
							handleAs: "json",
							content: {fid: id},
							load: function(data){
								if(data.ok){
									dojo.query(".FavList, .FavListList").forEach(function(favlist){
										dijit.byNode(favlist).refresh();
									});
								} else {
									alert(data.error);
								}
							}
						});
					},
					Add: function(placeAtNode, wordId){
						if(!Dictionary.AddingAFavorite){
							Dictionary.AddingAFavorite = true;
							var link = null;
							var llist = dojo.query("a.Add", placeAtNode);
							if(llist) link = llist[0]; // Favorite button needs to be first. hackish but functional
							else alert("Something just failed");
							var container = null;
							dojo.query(".newfavorite", placeAtNode).forEach(function(n){
								container = dijit.byNode(n);
							});
							if(container){
								if(container.domNode.style.display == 'none'){
									dojo.fx.wipeIn({node: container.domNode}).play();
									link.innerHTML = "Add as Favorite -";
								} else {
									dojo.fx.wipeOut({node: container.domNode}).play();
									link.innerHTML = "Add as Favorite +";
								}
								Dictionary.AddingAFavorite = false;
							} else {
								dojo.xhrGet({
									url: "getFavLists.php",
									handleAs: "json",
									load: dojo.hitch({"placeAt": placeAtNode, "wordId": wordId, "link": link}, function(favs){
										var container = Dictionary.New.InputDialog(this.placeAt, 'newfavorite');
										var first = true;
										for(i in favs){
											var rButton = new dijit.form.RadioButton({
												name: "fid",
												value: favs[i].listid
											});
											var rLabel = document.createElement("LABEL");
											rLabel.innerHTML = " " + favs[i].list;
											rLabel.htmlFor = rButton.id;
											container.theForm.domNode.appendChild(rButton.domNode);
											container.theForm.domNode.appendChild(rLabel);
											container.theForm.domNode.appendChild(document.createElement("BR"));
											if(first){
												rButton.setChecked(true);
												first = false;
											}
										}
										rButton = new dijit.form.RadioButton({
											name: "fid",
											value: "-1"
										});
										rLabel = new dijit.form.TextBox({name:"newlist", value: "Create new list...", onFocus: function(){
											if (this.getValue() == "Create new list...") this.setValue("");
										}});
										container.theForm.domNode.appendChild(rButton.domNode);
										container.theForm.domNode.appendChild(rLabel.domNode);
										container.theForm.domNode.appendChild(document.createElement("BR"));
										container.theForm.domNode.appendChild(document.createElement("BR"));
										var favSubmit = new dijit.form.Button({label: "Add to Favorites", onClick: dojo.hitch(container, function(e){
											var query = this.theForm.getValues();
											query.wordid = this.theForm.wordId;
											dojo.xhrPost({
												url: "addFavorite.php",
												handleAs: "json",
												content: query,
												load: dojo.hitch(this, function(data){
													if(data.ok){
														dojo.fx.wipeOut({node: this.domNode}).play();
														link.innerHTML = "Add as Favorite +";
														alert("Favorite added");
														setTimeout(dojo.hitch(this, function(){
															this.destroyRecursive();
															dojo.query(".FavList, .FavListList").forEach(function(favlist){
																dijit.byNode(favlist).refresh();
															});
														}), 1000);
													} else {
														alert(data.error);
													}
												})
											});
										})});
										container.theForm.wordId = this.wordId;
										container.theForm.domNode.appendChild(favSubmit.domNode);
										this.link.innerHTML = "Add as Favorite -";
										Dictionary.AddingAFavorite = false;
									})
								});
							}
						}
					}
				}
			}

			Dictionary.Friends = {
				Add: function(id){
					dojo.xhrPost({
						url: "addFriend.php",
						handleAs: "json",
						content: {id: id},
						load: function(data){
							if(data.ok){
								alert("Friend added.");
								dojo.query(".friendslist").forEach(function(n){
									dijit.byNode(n).refresh();
								});
								if(dijit.byId("Main").selectedChildWidget.refresh && dijit.byId("Main").selectedChildWidget.id != "Profile"){
									dijit.byId("Main").selectedChildWidget.refresh();
								}
							} else {
								alert("An unknown error occured");
							}
						}
					});
				},
				Remove: function(id){
					if(confirm("Are you sure you want to remove this person as a friend?")){
						dojo.xhrPost({
							url: "removeFriend.php",
							handleAs: "json",
							content: {id: id},
							load: function(data){
								if(data.ok){
									alert("Friend removed.");
									dojo.query(".friendslist").forEach(function(n){
										dijit.byNode(n).refresh();
									});
								} else {
									alert("An unknown error occured");
								}
							}
						});
					}
				}
			}

			Dictionary.MemberSearch = function(callback){
				var main = dijit.byId("Main");
				if(dijit.byId("Members")){
					main.selectChild(dijit.byId("Members"));
					if( typeof(callback) != "undefined" ) callback();
				} else {

					if( typeof(callback) != "undefined" ){
						dojo.hitch({cb:callback}, function(){
							if(dijit.byId("memberSearchResults")){
								this.cb();
							} else {
								setTimeout(dojo.hitch({cb:this.cb}, arguments.callee), 500);
							}
						})();
					}

					var membersTab = new dijit.layout.ContentPane({
						id: "Members",
						title: "Members",
						closable: true,
						href: "members.php",
						style: "padding: 0px;"
					});
					main.addChild(membersTab)
					main.selectChild(membersTab);
				}
			}

			Dictionary.startMessageCenter = function(initSendId){
				if(initSendId){
					MessageCenter.newMessage(initSendId);
				} else {

					dijit.byId("Main").selectChild(dijit.byId("Profile"));
					var selectMessaging = function(selfRef){
						if(Dictionary.Profile.Tabs){
							Dictionary.Profile.Tabs.selectChild(dijit.byId("MessageCenter"));
						} else {
							setTimeout(dojo.hitch({selfRef: selfRef}, function(){
								this.selfRef(this.selfRef);
							}), 500);
						}
					}
					selectMessaging(selectMessaging);
				
				}
			}

			Dictionary.onRecordSave = function(uid, wid, type, gender, accent){
				if(type == "wordBulk"){ // special handle for bulk word audio additions
					var callback = function(data) {
						if(data.ok){
							alert("Audio added successfully");
							Dictionary.BulkAdd.wordaudio.refresh();
						} else {
							alert("An error occured: " + data.error);
						}
					}
				} else {
					var callback = function(data){
						if(data.ok){
							alert("Audio added successfully");
							dojo.query(".WordDisplay", dojo.byId("Dictionary")).forEach(function(node){
								dijit.byNode(node).refresh();
							});
						} else {
							alert("An error occured: " + data.error);
						}
					}
				}
				dojo.xhrPost({
					url: "recorder.php",
					handleAs: "json",
					content: {doSave: true, uid: uid, wid: wid, type: type, gender: gender, accent: accent},
					load: callback
				});
			}

function SelectWord(wordId){
	Dictionary.SelectWord(wordId);
}










MessageCenter = new Object();
MessageCenter.messages = null;
MessageCenter.composing = false;
MessageCenter.currentFolder = "inbox";
MessageCenter.init = function(){

	if(MessageCenter.Display){
		MessageCenter.selectFolder("inbox", dojo.query("a", MessageCenter.FolderList.domNode)[0]);
// 			<? if (isset($_REQUEST['newTo'])) try { $sendTo = Doctrine::getTable("User")->find((int)$_REQUEST['newTo']); ?>
// 				MessageCenter.newMessage(<?=$sendTo->PKID?>, "<?=$sendTo->Nickname?>");
// 			<? } catch (Exception $e) { ?>
// 				console.dir(<?=json_encode($e->getMessage())?>);
// 			<? } ?>
	} else {
		MessageCenter.Loader = setTimeout(MessageCenter.init, 1000);
	}
}
MessageCenter.refreshCurrent = function(){
	switch(MessageCenter.currentFolder){
		case("inbox"): var anum = 0; break;
		case("sent"): var anum = 1; break;
		case("trash"): var anum = 2; break;
		default: var anum = -1; break;
	}
	if(anum != -1){
		MessageCenter.selectFolder(MessageCenter.currentFolder,
			dojo.query("a", MessageCenter.FolderList.domNode)[anum]
		);
	}
}

MessageCenter.getMessages = function(mode, onGet){
	dojo.xhrGet({
		url: "getMessages.php?mode=" + mode,
		handleAs: "json",
		load: function(messages){
			dojo.forEach(messages, function(message){
				//console.dir(message);
				if(!message.seen) message.subject = "<strong>" + message.subject + "</strong>";
			});
			MessageCenter.messages = messages;
			onGet(messages);
		}
	});
}
MessageCenter.getMessageById = function(id){
	if(MessageCenter.messages){
		for (var i in MessageCenter.messages){
			if(MessageCenter.messages[i].id == id){
				return MessageCenter.messages[i];
			}
		}
	}
	return false;
}

MessageCenter.newMessage = function(toId, to, subject, postmessage){
	var message = {
		to: toId ? toId : null,
		subject: encodeURIComponent(subject ? subject : ""),
		message: encodeURIComponent(postmessage ? postmessage.message : "")
	};
	dojo.xhrPost({
		url: "sendMessage.php",
		content: {Auth: new Date()},
		handleAs: "json",
		load: dojo.hitch(message, function(data){
			MessageCenter.hash = data.hash;
			Dictionary.openDialog(
				"SendMessageDialog", "Send Message",
				"newMessage.php?to="+this.to+"&subject="+this.subject+"&message="+this.message
			);
		})
	});

}

MessageCenter.viewMessage = function(id){
	//setTimeout(MessageCenter.refreshCurrent,1);
	var message = MessageCenter.getMessageById(id);
	if(message){
		MessageCenter.seenMessage(id);
		MessageCenter.Display.destroyDescendants();

		var display = [];
		display.push("<div style='float: left; border-right: 1px solid #999; border-bottom: 1px solid #999; font-size: smaller; margin: 0 1em 1em 0; padding: 1em;'>");
		display.push("<table cellspacing='3'>");
		display.push("<tr><td align='right' height='1'>To:</td><td><strong>");
		display.push("<a class='BlueHover' onclick='Dictionary.Profile.View(" + message.recipientId + ");'>" + message.recipient + "</a>");
		display.push("</strong></td>");
		display.push("</td></tr>");
		display.push("<tr><td align='right' height='1'>From:</td><td><strong>");
		display.push("<a class='BlueHover' onclick='Dictionary.Profile.View(" + message.senderId + ");'>" + message.sender + "</a>");
		display.push("</strong></td></tr>");
		display.push("<tr><td align='right' height='1'>Subject:</td><td><strong>" + message.subject + "</strong></td></tr>");
		display.push("<tr><td align='right' height='1'>Date:</td><td><strong>" + message.sentOn + "</strong></td></tr>");
		display.push("<tr><td colspan='2'><hr /><div class='nowrap buttonHolder'></div></td></tr>");
		display.push("</table></div>");
		display.push("<div style='font-size: larger; margin: 1em;'>" + message.message.replace(/\n/g, "<br />") + "</big>");
		MessageCenter.Display.setContent(display.join("\n"));
		var buttons = dojo.query(".buttonHolder", MessageCenter.Display.domNode)[0];
		new dijit.form.Button({
			label: "Reply",
			onClick: dojo.hitch(message, function(){
				MessageCenter.newMessage(this.senderId, this.sender, "re: " + this.subject, this);
			})
		}).placeAt(buttons);
		new dijit.form.Button({
			label: "Forward",
			onClick: dojo.hitch(message, function(){
				MessageCenter.newMessage(null, null, "fw: " + this.subject, this);
			})
		}).placeAt(buttons);
		new dijit.form.Button({
			label: message.trash ? "Delete" : "Trash",
			onClick: dojo.hitch(message, function(){ MessageCenter[message.trash ? "deleteMessage" : "trashMessage"](this.id) })
		}).placeAt(buttons);
	} else {
		alert("An error occured, try refreshing the page and trying agian.");
	}
}
MessageCenter.sendMessage = function(toId, subject, message, onSend){
	dojo.xhrPost({
		url: "sendMessage.php",
		handleAs: "json",
		content: {hash: MessageCenter.hash, to: toId, subject: subject, message: message},
		load: typeof onSend == 'function' ? onSend : function(resp){
			if(resp.ok)	alert("Your message has been sent.");
			else alert("There was an error sending your message");
		}
	});

}
MessageCenter.trashMessage = function(messageId, onMod){
	dojo.xhrPost({
		url: "modMessage.php?do=trash",
		handleAs: "json",
		content: {message: messageId},
		load: typeof onMod == 'function' ? onMod : function(resp){
			if(resp.ok)	alert("This message has been moved to the trash.");
			else alert("There was an error moving this message to the trash");
			MessageCenter.refreshCurrent();
		}
	});
}

MessageCenter.deleteMessage = function(messageId, onMod){
	dojo.xhrPost({
		url: "modMessage.php?do=delete",
		handleAs: "json",
		content: {message: messageId},
		load: typeof onMod == 'function' ? onMod : function(resp){
			if(resp.ok)	alert("This message has been deleted.");
			else alert("There was an error deleting this message");
			MessageCenter.refreshCurrent();
		}
	});
}
MessageCenter.seenMessage = function(messageId, onMod){
	dojo.xhrPost({
		url: "modMessage.php?do=seen",
		handleAs: "json",
		content: {message: messageId},
		load: typeof onMod == 'function' ? onMod : function(resp){
			Dictionary.MessageChecker(); // Update main toolbar with message count
		}
	});
}

MessageCenter.selectFolder = function(folder, clicked){
	MessageCenter.currentFolder = folder;
	var panes = dijit.byNode(clicked.parentNode.parentNode.parentNode).getChildren();
	// 0 == header  1 == folder list  2 = messageArea (0 = listing, 1 = contents)
	if(clicked){
		var anims = [];
		anims.push(dojo.animateProperty({
			node: clicked.parentNode,
			properties: {
				color: "#000", paddingLeft: 10
			}
		}));
		dojo.query("a", panes[1].domNode).forEach(function(folderLink){
			if(folderLink != clicked) anims.push(dojo.animateProperty({
				node: folderLink.parentNode,
				properties: {
					color: "#888", paddingLeft: 0
				}
			}));
		});
		var anim = dojo.fx.combine(anims);
		anim.play();
	}

	MessageCenter.getMessages(folder, function(messages){
		var grid = MessageCenter.makeGrid([
			{ field: "subject", name: "Subject", width: "auto" },
			{ field: folder == "sent" ? "recipient" : "sender" , name: folder == "sent" ? "Recipient" : "From" , width: "auto" },
			{ field: "sentOn", name: "Date", width: "auto" }],
			messages,
			MessageCenter.Listing.domNode
		);

	});
}
MessageCenter.makeGrid = function(layout, data, attachTo, query){
	dojo.require("dojox.data.jsonPathStore");

	dojo.require("dojox.grid.DataGrid");
	var store = new dojox.data.jsonPathStore({ data: data, idAttribute: "id" });
	var existingGrid = dojo.query(".dojoxGrid", attachTo).forEach(function(gridNode){
		dijit.byNode(gridNode).destroy();
	});
	var gridNode = document.createElement("DIV");
	var grid = new dojox.grid.DataGrid({
		query: query ? query : {},
		store: store,
		clientSort: true,
		rowSelector: "0px",
		structure: layout,
		selectionMode: 'none',
		onRowClick: function(row){
			MessageCenter.viewMessage(row.grid.getItem(row.rowIndex).id);
		}
	}, gridNode).placeAt(attachTo);
	grid.startup();
}



