/*
	Copyright (c) Zeros 2 Heroes All Rights Reserved.
*/  
dojo.require("dojo.parser"); // scan page for widgets and instantiate them
 
dojo.require("dijit.ProgressBar");

dojo.require("dojo.number");
dojo.require("dijit.Dialog");
dojo.require("dojo.data.ItemFileWriteStore");
dojo.require("dijit.form.DateTextBox"); 

dojo.require("dijit.Editor");
dojo.require("dijit._Widget");
dojo.require("dijit._editor.plugins.AlwaysShowToolbar");
dojo.require("dijit._editor.plugins.EnterKeyHandling");
dojo.require("dijit._editor.plugins.FontChoice"); // 'fontName','fontSize','formatBlock' buttons
dojo.require("dijit._editor.plugins.TextColor");  // 'foreColor' button
dojo.require("dijit._editor.plugins.LinkDialog"); // 'createLink' button
dojo.require("dojox.editor.plugins.UploadImage"); // 'uploadImage' button

dojo.require("dojo.io.iframe");
dojo.require("dojo.fx"); 
dojo.require("dojox.fx.easing"); 
dojo.require("dojox.fx.scroll");
//dojo.require("dojo.window");


//---------------------- EXTEND DOJO TEXT EDITOR -------------------------------- 
dojo.extend(dijit._editor.plugins.LinkDialog, {
	// overwrite to hide invalid error message for our default value
	urlRegExp: "((http?|https?|ftps?)\\://|)(|((?:(?:[\\da-zA-Z](?:[-\\da-zA-Z]{0,61}[\\da-zA-Z])?)\\.)*(?:[a-zA-Z](?:[-\\da-zA-Z]{0,6}[\\da-zA-Z])?)\\.?)|(((\\d|[1-9]\\d|1\\d\\d|2[0-4]\\d|25[0-5])\\.){3}(\\d|[1-9]\\d|1\\d\\d|2[0-4]\\d|25[0-5])|(0[xX]0*[\\da-fA-F]?[\\da-fA-F]\\.){3}0[xX]0*[\\da-fA-F]?[\\da-fA-F]|(0+[0-3][0-7][0-7]\\.){3}0+[0-3][0-7][0-7]|(0|[1-9]\\d{0,8}|[1-3]\\d{9}|4[01]\\d{8}|42[0-8]\\d{7}|429[0-3]\\d{6}|4294[0-8]\\d{5}|42949[0-5]\\d{4}|429496[0-6]\\d{3}|4294967[01]\\d{2}|42949672[0-8]\\d|429496729[0-5])|0[xX]0*[\\da-fA-F]{1,8}|([\\da-fA-F]{1,4}\\:){7}[\\da-fA-F]{1,4}|([\\da-fA-F]{1,4}\\:){6}((\\d|[1-9]\\d|1\\d\\d|2[0-4]\\d|25[0-5])\\.){3}(\\d|[1-9]\\d|1\\d\\d|2[0-4]\\d|25[0-5])))(\\:\\d+)?(/(?:[^?#\\s/]+/)*(?:[^?#\\s/]+(?:\\?[^?#\\s/]*)?(?:#[A-Za-z][\\w.:-]*)?)?)?",

	_onOpenDialog: function() { 
		this.dropDown.setValues({urlInput: "http://"}); // default value
	}
}); 

dojo.extend(dojox.editor.plugins.UploadImage, { 
	onComplete: function(data,ioArgs,widgetRef) {
		data = data[0];
		var tmpImgNode = dojo.withGlobal(this.editor.window, "byId", dojo, [this.currentImageId]);
		
		if (data.error || data.name == "") {
			if (data.error) {
				Z2h.link.error(data.error);
			} else {
				Z2h.link.error("Unknown error occured, please try again.");
			}
			
			var editor = dijit.byId("dojo_editor_textarea");

			var paragraph = document.createElement("p");
			paragraph.innerHTML = editor.getValue();

			for (var i in paragraph.children) {
				if (paragraph.children[i].localName == "IMG") {
					var node = paragraph.children[i];
					var src = dojo.attr(node, "src");
					
					if (src == "") {
						paragraph.removeChild(node);
						editor.attr("value", paragraph.innerHTML);
					}
				}
			}
			 
			dojo.destroy(tmpImgNode); 
		} else {
			// image is ready to insert 
			var file;
			
			// downloadPath is mainly used so we can access a PHP script
			// not relative to this file. The server *should* return a qualified path
			if (this.downloadPath) {
				file = this.downloadPath + data.name
			} else {
				file = data.file;
			}
			 
			tmpImgNode.src = file;
			dojo.attr(tmpImgNode,'_djrealurl',file);
			
			if (data.width) {
				tmpImgNode.width = data.width;
				tmpImgNode.height = data.height;
			} 
		}
	},
	
	insertTempImage: function(){
		// inserting a "busy" image to show something is hapening
		//	during upload and download of the image.
		this.currentImageId = "img_"+(new Date().getTime()); 
		var iTxt = '<img id="'+this.currentImageId+'" src="/images/editor-loader.gif" width="32" height="32" />';
		this.editor.execCommand('inserthtml', iTxt);
	}
});
 
//---------------------- EXTEND DOJO FILTERING SELECT --------------------------------  
function getQueryValue(query) {
	if (query.username) {
		return query.username.replace(/\*/, "");
	} else if (query.name) {
		return query.name.replace(/\*/, "");
	}
}
   
// start filtering when at least 2 characters are entered
dojo.declare("Z2hFilteringSelectInbox", dijit.form.FilteringSelect, { 
	_startSearchFromInput: function() {
	    if (this.focusNode.value.length >= 2) {
	        this._startSearch(this.focusNode.value);
	    }
	}, 
    
    _startSearch: function(/*String*/ key) { 
		// if null, get a new list of users whose username matched with keyword 
		if (!this.store) {
			this.keyword = key;
			this.store = new dojo.data.ItemFileWriteStore({
				url: this.alt + "keyword/" + this.keyword
			});
		} 			 
			 
		if (!this._popupWidget) {
			var popupId = this.id + "_popup";
			
			this._popupWidget = new dijit.form._ComboBoxMenu({
				onChange: dojo.hitch(this, this._selectOption),
				id: popupId
			});
			
			dijit.removeWaiState(this.focusNode, "activedescendant");
			dijit.setWaiState(this.textbox, "owns", popupId); // associate popup with textbox
		}
			
		// create a new query to prevent accidentally querying for a hidden
		// value from FilteringSelect's keyField
		this.item = null; // #4872
		var query = dojo.clone(this.query); // #5970
		this._lastInput = key; // Store exactly what was entered by the user.
		this._lastQuery = query[this.searchAttr] = this._getQueryString(key);
			
		// #5970: set _lastQuery, *then* start the timeout
		// otherwise, if the user types and the last query returns before the timeout,
		// _lastQuery won't be set and their input gets rewritten
		this.searchTimer=setTimeout(dojo.hitch(this, function(query, _this) {
			var fetch = {
				queryOptions: {
					ignoreCase: this.ignoreCase, 
					deep: true
				},
				query: query,
				onBegin: dojo.hitch(this, "_setMaxOptions"),
				onComplete: function(a, b) {
					var keysearch = getQueryValue(b.query); // b.query.username.replace(/\*/, "");
						
					if (a.length == 0 && _this.lastKeyword != keysearch) {
						if (_this.lastKeyword) {
							if (!(keysearch.length > _this.lastKeyword.length)) {
								_this.lastKeyword = keysearch;
								_this.store = null;
								_this._startSearch(keysearch);
							} else {
								_this._openResultList(a, b);
							}
						} else {
							//set the store to null and retry the search
							_this.lastKeyword = keysearch;
							_this.store = null;
							_this._startSearch(keysearch);
						}
					} else {
						_this._openResultList(a, b);
					}
				},
				onError: function(errText) {						 
					console.error("dijit.form.ComboBox: " + errText);
					dojo.hitch(_this, "_hideResultList")();	  
				},
				start: 0,
				count: this.pageSize
			};
				
			dojo.mixin(fetch, _this.fetchProperties);
			
			var dataObject = _this.store.fetch(fetch);
			var nextSearch = function(dataObject, direction) {
				dataObject.start += dataObject.count * direction;
				// #4091:
				// tell callback the direction of the paging so the screen
				// reader knows which menu option to shout
				dataObject.direction = direction;
				this.store.fetch(dataObject);
			};
				
			this._nextSearch = this._popupWidget.onPage = dojo.hitch(this, nextSearch, dataObject);
		}, query, this), this.searchDelay);
	}
});
 
//---------------------- GLOBAL VARIABLES & FUNCTIONS --------------------------------  
Z2h = {}; // initialize z2h

// get possible recipients
/*var z2h_users =
	new dojo.data.ItemFileWriteStore({
		url: "/community/inbox/get-users/format/json"
});*/

// get possible countries
var countries =
	new dojo.data.ItemFileReadStore({
		url: "/default/interaction/get-countries/format/json"
});

// get possible regions
var regions =
	new dojo.data.ItemFileReadStore({
		url: "/default/interaction/get-regions/format/json"
}); 

// get possible profile categories
var profile_categories =
	new dojo.data.ItemFileWriteStore({
		url: "/user/profile/get-categories/format/json"
});

// get possible message categories
var message_categories =
	new dojo.data.ItemFileReadStore({
		url: "/community/discussion/get-categories/format/json"
}); 

//get possible group categories
var group_categories =
	new dojo.data.ItemFileReadStore({
		url: "/group/index/get-categories/format/json"
});

// initialize application-wide js functions
Z2h.global = {
	init: function() {
		Z2h.mailing.init();	
	    Z2h.link.init();
		Z2h.comment.init();
		Z2h.twitt.init();
		Z2h.inbox.init();
		Z2h.inbox.recipients.init();
		Z2h.user.init();
		Z2h.user.profile.init();
		Z2h.autocomplete.init();
		Z2h.connection.init();
		Z2h.editor.init(); 
		Z2h.social.init();
		Z2h.creation.init();
		Z2h.group.init();
		Z2h.signup.init();
		Z2h.login.init();
		Z2h.forgot.init();
		Z2h.reset.init();
		Z2h.event.init(); 
		Z2h.links.init();
	}
}

// detect client's screen size and resize client's browse window
function fullScreen(url) {
	var screenX = screen.width;
	var screenY = screen.height;
	var pv = window.open(url, "fs", "status = yes, height = " + screenY + ", width = " + screenX + ", top = 0, left = 0", false);
} 

/* customized function to check username availiablity and give suggestions if the name is not available.
**********************************************************************************/
function usernameChecker(username){
	var checker_msg = dojo.byId('username_checker_msg');
			
	if (checker_msg) {
		checker_msg.innerHTML = "";	 	 
			
		if(username!=""){
				dojo.xhrGet({ 
					url: "/user/authentication/check-username/username/"+username+"/format/json",   
					handleAs: "json",
					sync: true,
					headers: {"X-Requested-With": "XMLHttpRequest"},
					load: function(data,ioargs){  
						if (data.result == "1") {
							dojo.style(checker_msg, {"color": "#aaaaaa"});
							checker_msg.innerHTML = "This username is available.";
				 		} else {
				 			dojo.style(checker_msg, {"color": "#ff0000"});
				 			checker_msg.innerHTML = "This username is already taken.";
				 		} 
						
						return data; //always return the response back 
					},
					// if any error occurs, it goes here:
					error: function(response, ioArgs){
						console.log("failed xhrPost", response, ioArgs);
						
						alert("ERROR: There was an error while submitting your form. Please try again!");
						/* handle the error... */ 
			            return response; //always return the response back 
					}
				});  
		}
	}  
} 

/* customized function to measure user's password strength using meter.
**********************************************************************************/
function PWStrength(password){
	var level = new Array();
	
	level[0] = "Very Weak";
	level[1] = "Weak";
	level[2] = "Better";
	level[3] = "Medium";
	level[4] = "Strong";
	level[5] = "Super Strong!"; 
	
	var point = 0;
	var i = 1;
	var meter_description = dojo.byId("meter_description");
	var password_points = dojo.byId("password_points"); 
	
	/*********************************** 
	   Password Strength Point System	          
	************************************/	
	
	// if password length is 0, reset meter.
	if(password.length == 0){
		point = 0;
		password_points.value = 0;
		
		if (meter_description) {
			meter_description.innerHTML = "&nbsp;";
		}
	 
		for(i=0; i<=5; i++){
			var meter = dojo.byId("meter"+i);
			
			if (meter) {
				dojo.style(meter, {"backgroundColor": "white"});
			} 
		} 
	}else{
		//1. if password length is bigger than 6, give 1 point.
		if(password.length >= 6){
		 	point++;
		}  
		
		//2. if password has both lower and uppercase characters, give 1 point.
		if((password.match(/[a-z]/)) && (password.match(/[A-Z]/))){
		 	point++;
		}
		
		//3. if password has at least one number, give 1 point.
	    if((password.length > 1)&&(password.match(/\d+/))){
		 	point++; 
		}
	 
	    //4. if password has at least one special caracther, give 1 point.
	    if(password.match(/.[!,@,#,$,%,^,&,*,?,_,~,-,(,)]/)){
		 	point++;
		}
	     
	    //5. if password bigger than 9, give another 1 point.
	    if(password.length > 9){
		 	point++;
		}
		
		//6. if length is less than 6, subtract 1 point.
		if((point>4) && (password.length < 6)){
			point--;
		}
		 
		if (meter_description) {
			meter_description.innerHTML = level[point];
		}
		 
		password_points.value = point;
		
		for(i=0; i<=5; i++){
            var meter = dojo.byId("meter"+i);
			
			if (meter) {  
				if(i<=point){
					if(i < 2){
						dojo.style(meter, {"backgroundColor": "#fa0000"});  
					}else{ 
						dojo.style(meter, {"backgroundColor": "#009000"});
					} 
				}else{
					dojo.style(meter, {"backgroundColor": "white"});
				}
			}  
		} 
	} 
}

//---------------------- STRING FUNCTIONS --------------------------------
Z2h.string = {  
	// trim empty string from front
	leftTrim: function(sString) {
		while (sString.substring(0,1) == " ") {
			sString = sString.substring(1, sString.length);
		}
		
		return sString;
	},
	
	// trim empty string from end
	rightTrim: function(sString) {
		while (sString.substring(sString.length-1, sString.length) == " "){
			sString = sString.substring(0,sString.length-1);
		}
		
		return sString;
	},
	
	// trim empty string from front-end
	trimAll: function(sString) {
		while (sString.substring(0,1) == " ") {
			sString = sString.substring(1, sString.length);
	    }
		
		while (sString.substring(sString.length-1, sString.length) == " ") {
			sString = sString.substring(0,sString.length-1);
		}
		
		return sString;
	},
	
	// count total characters entered in textarea (max 1000 characters)
	countTextarea: function(txtNode, updateId, max) { 
		var numChars = dojo.number.parse(txtNode.value.length);
	    var remainingChars = dojo.byId(updateId);
	    
	    var currentValue = parseInt(max) - numChars;
	    
	    if (currentValue > 0) { 
	    	//dojo.removeAttr(submitBtn, "disabled"); 
	    	dojo.style(remainingChars, "color", "#aaaaaa");
	    	remainingChars.innerHTML = currentValue + " characters remaining"; 
	    } else { 
	    	txtNode.value = txtNode.value.slice(0, max);
	    	//dojo.attr(submitBtn, "disabled", "disabled"); 
	    	dojo.style(remainingChars, "color", "#C00000");
	    	remainingChars.innerHTML = "You have run out characters";
	    } 
	    
		return;
	}
}

//---------------------- VALIDATOR FUNCTIONS --------------------------------  
Z2h.validator = {  
	email: function(email, required, error_id) {
		var errors = 0;
		var email_p = dojo.byId(error_id); 
		var email_filter  = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
		
		// validate email
		if (required && email.length == 0) {
			errors++;
			
			if (email_p) { 
				email_p.innerHTML = "Email is required.";
			} 
		}  
		
		if (errors == 0) {
			// continue validate email 
			if (!email_filter.test(email)) {
				errors++; 
	
				if (email_p) { 
					email_p.innerHTML = "Please enter a valid email address.";
				}
			}
		}
		
		// validate form
		if (errors > 0) {
			return false; 
		} else { 
			if (email_p) { 
				email_p.innerHTML = "";
			} 
			
			return true;
		} 
	},
	
	username: function(username, required, error_id) {
		var errors = 0; 
		var username_p = dojo.byId(error_id);; 
		var username_filter  = /^([a-zA-Z0-9])+([a-zA-Z0-9\s])*([a-zA-Z0-9])+$/;
		
		// validate username
		if (required && username.length == 0) {
			errors++;
			
			if (username_p) { 
				username_p.innerHTML = "Username is required.";
			} 
		}  
		
		if (errors == 0) {
			// continue validate username
			if (username.length < 3 || username.length > 16) {
				errors++; 

				if (username_p) { 
					username_p.innerHTML = "Username must be between 3 and 16 characters long.";
				}
			} else if (!username_filter.test(username)) {
				// username should be a-zA-Z0-9 and spaces between characters, but leading/trailing space
				errors++;
				
				if (username_p) { 
					username_p.innerHTML = "Username should contain only letters, numbers and spaces (no leading or trailing)."; 
				} 
			} 
		}
		
		// validate form
		if (errors > 0) {
			return false; 
		} else { 
			if (username_p) { 
				username_p.innerHTML = "";
			} 
			
			return true;
		}  
	},
	
	password: function(password, required, error_id) {
		var errors = 0; 
		var password_p = dojo.byId(error_id); 
		var password_filter  = /^(\S)+$/;
		
		// validate password
		if (required && password.length == 0) {
			errors++;
			
			if (password_p) { 
				password_p.innerHTML = "Password is required.";
			} 
		}  
		
		if (errors == 0) {
			// continue validate password
			if (!password_filter.test(password)) {
				// check password contains any white space
				errors++; 

				if (password_p) { 
					password_p.innerHTML = "No white space characters are allowed in the password.";
				}
			} else if (password.length < 6) {
				// username should be a-zA-Z0-9 and spaces between characters, but leading/trailing space
				errors++;
				
				if (password_p) { 
					password_p.innerHTML = "Password must be at least 6 characters long."; 
				} 
			} 
		}
		
		// validate form
		if (errors > 0) {
			return false; 
		} else { 
			if (password_p) { 
				password_p.innerHTML = "";
			} 
			
			return true;
		}  
	}
} 

//---------------------- MAILING LIST JS --------------------------------

Z2h.mailing = {
	_running: false, 
	
	// input value messages.
	_success: "THANK YOU!", 
	_error: "INVALID EMAIL", 
        _exist: "EMAIL EXISTS",
	_default: "EMAIL ADDRESS",
	
	init: function() {  
	    // hook event to show/clear default value. 
		var email = dojo.byId('mailing_list_email'); 
		if (email) { 
			dojo.connect(email, 
					    "onfocus",
					    function(e){ 
							e.preventDefault(); 
							
							if (email.value == Z2h.mailing._default || email.value == Z2h.mailing._success || email.value == Z2h.mailing._error || email.value == Z2h.mailing._exist) {
								email.value = "";
							}
							
			});
			
			dojo.connect(email, 
					    "onblur",
					    function(e){ 
							e.preventDefault(); 
							
							if (email.value == "") {
								email.value = Z2h.mailing._default; 
							}
							
			});
		}
		
		// hook onclick event to submit form.
		var mailing_btn = dojo.byId('mailing_list_submit');
		if (mailing_btn) {
			dojo.connect(mailing_btn, 'onclick', Z2h.mailing.subscribe);
		}  

		// for safari, hook onsubmit event to submit form.
		var mailing_form = dojo.byId('mailing_list');
		if (mailing_form) {
			dojo.connect(mailing_form, 'onsubmit', Z2h.mailing.subscribe);
		} 
	},
	
	subscribe: function(evt) {
		evt.preventDefault(); 
		
		// only send an ajax request if nothing is running.
		if (Z2h.mailing._running === false) {  
			var mailing_form = dojo.byId('mailing_list');
			var email = dojo.byId('mailing_list_email');
			var email_filter  = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
			
			if (mailing_form && email) {
				Z2h.mailing._running = true;
				var mailing_email = Z2h.string.trimAll(email.value);
 
				// validate email.
				if (!email_filter.test(mailing_email)) {
					email.value = Z2h.mailing._error;
					Z2h.mailing._running = false;
				} else { 
					email.value = mailing_email;
					dojo.xhrPost({
						url: mailing_form.action+'/format/json', 
						form: "mailing_list",  
						handleAs: "json",
						sync: true,
						headers: {"X-Requested-With": "XMLHttpRequest"},
						load: function(data,ioargs){  
							if(data.result == '1'){ 
								email.value = Z2h.mailing._success; 
							} else if (data.result == '-1') {
								email.value = Z2h.mailing._exist;
							} else {
								email.value = data.error; 
							}
							
							Z2h.mailing._running = false;
							
							return data; //always return the response back 
						},
						// if any error occurs, it goes here:
						error : function(response, ioArgs) { 
				            console.log("failed xhrGet", response, ioArgs); 
				            
				            alert("ERROR: There was an error while submitting your request. Please try again!");
				            
				            /* handle the error... */ 
				            return response; //always return the response back 
				        }
					});
				} 
			} 
			
			// lose focus from input box.
			email.blur();
		} 
	}
}

//---------------------- LINK JS -------------------------------- 
Z2h.link = {
	_running: false, 
	
	_href: null,
	
	_refresh: false,
	
	init: function() {
		// hook onclick event to toggle checkbox
		dojo.query("a.toggle_checkbox").forEach(function(link) {
			dojo.connect(link, "onclick", Z2h.link.toggleSelect);  
		});
	
		var validate_checkbox = dojo.byId('validate_checkbox');
		if (validate_checkbox) {
			dojo.connect(validate_checkbox, 'onclick', Z2h.link.validateSelect); 
		}

		var user_profile_mail_link = dojo.byId('user_profile_mail_link');
		if (user_profile_mail_link) {
			dojo.connect(user_profile_mail_link, 'onclick', Z2h.link.sendMessage); 
		}

		// hook onclick event to rate up creation item
		dojo.query(".button_link").forEach(function(link) {
			var connected = dojo.connect(link, "onclick", function(e) { 
				e.preventDefault();  
				
				var href = e.currentTarget.value;
				window.location.assign(href);
			});  
		});
		
		var send_invites_form = dojo.byId('send_invites_form');
		if (send_invites_form) {
			dojo.connect(send_invites_form, 'onsubmit', Z2h.link.validateSelect); 
		}
		
		// hook onclick event to rate up creation item
		dojo.query("a.rate_up_link").forEach(function(link) {
			var connected = dojo.connect(link, "onclick", function(e) { 
				e.preventDefault();  
				Z2h.link.rate(link, 1, connected); 
			});  
		});
		
		// hook onclick event to rate down creation item
		dojo.query("a.rate_down_link").forEach(function(link) {
			var connected = dojo.connect(link, "onclick", function(e) { 
				e.preventDefault();  
				Z2h.link.rate(link, -1, connected); 
			});  
		});
	
		// hook onclick event to show confirm dialog to delete item
		dojo.query("a.delete").forEach(function(link) {
			dojo.connect(link, "onclick", Z2h.link.doPostDelete);
		});
		
		// hook onclick event to show dialog to send email to friend
		dojo.query("a.send_friend").forEach(function(link) {
			dojo.connect(link, "onclick", Z2h.link.sendEmailDialog);
		}); 
		
		// hook onclick event to show dialog to flag a content
		dojo.query("a.flag").forEach(function(link) {
			var flagHandle = dojo.connect(link, "onclick", function(e) {  
		        Z2h.link.flagDialog(e, flagHandle); // need to pass flag handle to disconnect after flagging item
		    }); 
		});
		
		// hook onclick event to show dialog to flag a content
		dojo.query("a.load_ajax").forEach(function(link) {
			dojo.connect(link, "onclick", Z2h.link.loadAjax); 
		});
		
		// hook onclick event to call manage member function as ajax.
	    dojo.query("a.call_ajax").forEach(function(link) {
			dojo.connect(link, "onclick", Z2h.link.callAjax);
		});
	    
	    // hook onclick event to select an avatar from predefined set.
	    dojo.query("a.avatar_link").forEach(function(link) {
			dojo.connect(link, "onclick", Z2h.link.selectAvatar);
		});
	},
	
	sendMessage: function(evt) {
		evt.preventDefault();

		var href = evt.currentTarget.value;
		window.location.assign(href);

	},

	// select an avatar from predefined set for signup or edit profile.
	selectAvatar: function(evt) {
		evt.preventDefault();
		 
		var signup_avatar_field = dojo.byId('signup_avatar'); 
		
		if (signup_avatar_field) {
			var current_avatar_name = signup_avatar_field.value;
			var current_avatar_node = dojo.byId(current_avatar_name.split(".", 1)+'_img');
			
			var new_avatar_name = evt.currentTarget.id;
			var new_avatar_node = dojo.byId(new_avatar_name+'_img');
			 
			if (current_avatar_name != new_avatar_name) {
				var profile_picture = dojo.attr(new_avatar_node, "alt");
				
				signup_avatar_field.value = profile_picture;  
				dojo.addClass(new_avatar_node, "selected_avatar");
				
				if (current_avatar_node) {
					dojo.removeClass(current_avatar_node, "selected_avatar"); 
				} 
			}
		} 
	},
	
	validateSelect: function(evt) {
		var checked_count = 0;
		var error_p = dojo.byId('validate_checkbox_error');
		
		dojo.query("input.form_checkbox").forEach(function(chk) {
			if (chk.checked) {
				checked_count++;
			} 
		});
		
		if (checked_count > 0) {
			if (error_p) {
				error_p.innerHTML = "";
			} 
		} else { 
			evt.preventDefault(); 
			
			if (error_p) {
				error_p.innerHTML = "Please select users to invite or create a connection.";
			}
		}
	},
	
	// select/unselect all checkbox.
	toggleSelect: function(evt) {
		evt.preventDefault(); 

		var checkbox_class = evt.currentTarget.id;
		
		if (dojo.hasClass(evt.currentTarget, 'select_all')) {
			dojo.query("."+checkbox_class+"_checkbox").forEach("item.checked = true"); 
			
			dojo.removeClass(evt.currentTarget, 'select_all'); 
			dojo.addClass(evt.currentTarget, 'unselect_all');
			evt.currentTarget.innerHTML = "Unselect all"; 
		} else if (dojo.hasClass(evt.currentTarget, 'unselect_all')) { 
			dojo.query("."+checkbox_class+"_checkbox").forEach("item.checked = false");
			
			dojo.removeClass(evt.currentTarget, 'unselect_all'); 
			dojo.addClass(evt.currentTarget, 'select_all');
			evt.currentTarget.innerHTML = "Select all";
		} 
	},
	
	// thumbs up/down a creation item
	rate: function(link, point, connection) {
		// get rating link and parent class
		var href = dojo.attr(link, "href");
		var update_dom_id = dojo.attr(link, "alt");
		var classes = dojo.attr(link,'class');
		
		if ( point == 1 ){
			classes = classes.replace("rate_up_link ","");
		} else {
			classes = classes.replace("rate_down_link ","");
		}
		
		dojo.xhrGet({ 
		    url: href + "/format/json",  
			handleAs: "json",
			sync: true,
			headers: {"X-Requested-With": "XMLHttpRequest"},
			load: function(data,ioargs) {  
				if (data.result == "1") {
					var list = dojo.byId(update_dom_id + "_list");
					list.innerHTML = "<li><p class='"+classes+" chosen_rating'>" + ((point == 1)?"Rated Up":"Rated Down") + "</p></li>";

					// update rating number
					var rating_dom = dojo.byId(update_dom_id);
					
					if (rating_dom) { 
						if (point == 1) {
							var rating_node = dojo.query("p > span.rated_up", rating_dom)[0];
						} else {
							var rating_node = dojo.query("p > span.rated_down", rating_dom)[0];
						}
						
						// get the current rating number
						var current_rating_number = rating_node.innerHTML;
						
						// update rating_number (with + or -)  
						current_rating_number = parseInt(current_rating_number) + parseInt(point); 

						if (current_rating_number > 0) {
							rating_node.innerHTML = "+" + current_rating_number;
						} else {
							rating_node.innerHTML = current_rating_number;
						} 
					} 
					
					// also update ratings count for today
					var stats_box = dojo.byId("logged_in_stats");
					if (stats_box) {
						var rating_count_node = dojo.query("ul > li.logged_in_rating_stat > p", stats_box)[0];
						
						// get the current rating count
						var current_rating = rating_count_node.innerHTML;
						var current_rating_count = current_rating.replace(" rating", "");
						current_rating_count = current_rating_count.replace("s", "");
						
						// update rating count 
						current_rating_count = parseInt(current_rating_count) + 1;
						
						if (current_rating_count != 1) {
							rating_count_node.innerHTML = current_rating_count + " ratings";
						} else {
							rating_count_node.innerHTML = current_rating_count + " rating";
						} 
					} 
				} else {
					// reload the page
					window.location.reload(true);
				} 

				return data; //always return the response back 
			},
			// if any error occurs, it goes here:
			error: function(response, ioArgs) {
				console.log("failed xhrGet", response, ioArgs);

				alert("ERROR: There was an error while rating. Please try again!"); 

				/* handle the error... */ 
	            return response; //always return the response back 
			} 
		});  
		
		// remove the rating links
		//dojo.query("." + update_dom_id + "_link").forEach(function(node, i) {  
			 //node.innerHTML = "";
			//dojo.disconnect(connection);
			//dojo.connect(node,"onclick",function(e){ e.preventDefault() });
		//}); 
		

	},
	
	// load action by ajax call
	callAjax: function(evt) {
		evt.preventDefault();
		
		dojo.xhrGet({ 
			url: evt.currentTarget.href+"/format/json",   
			handleAs: "json",
			sync: true,
			headers: {"X-Requested-With": "XMLHttpRequest"},
			load: function(data,ioargs){  
				if (data.result == "1") {
		 			var call_back = dojo.byId('do_after_callback');
					if (call_back) { 
						if (document.createEvent) {
							// Firefox etc.
							event = document.createEvent("HTMLEvents");
							event.initEvent("click", false, true);
							call_back.dispatchEvent(event);
						} else {
							// IE
							call_back.fireEvent("onclick");
						}  
					} else {
						// refresh the current page
						window.location.reload(true);
					} 
		 		} else {
		 			// refresh the current page
					window.location.reload(true);
		 		} 
				
				return data; //always return the response back 
			},
			// if any error occurs, it goes here:
			error: function(response, ioArgs){
				console.log("failed xhrPost", response, ioArgs);
				
				alert("ERROR: There was an error while submitting your form. Please try again!");
				/* handle the error... */ 
	            return response; //always return the response back 
			}
		});
	},
	
	// load content by ajax call
	loadAjax: function(evt) {
		evt.preventDefault();
		
		// update dom id (make sure there is div id=load_ajax_content_here)
		var update_dom = dojo.byId("load_ajax_content_here");
		
		// while loading (make sure there is div id=load_ajax_content_loading)
		var loading_wait = dojo.byId("load_ajax_content_loading");
		
		// ajax requst url
		var href = evt.currentTarget.href; 
		
		// only send an ajax request if nothing is running and the dom exists
		if (update_dom && Z2h.link._running === false) {
			Z2h.link._running = true; 
			 
			if (loading_wait) { 
				update_dom.style.display = "none"; 
				loading_wait.style.display = ""; 
			}
			
			dojo.xhrGet({ 
				url: href + "/format/text/",
				handleAs: "text",
//			 	sync: true,
			 	// run this function if the request is successful
		        load : function(response, ioArgs) { 
		            // set some element's content
					update_dom.innerHTML = response;  
					
					if (loading_wait) { 
						loading_wait.style.display = "none"; 
						update_dom.style.display = ""; 
					}
					
		            // initialize js
					Z2h.global.init(); 
					 
		            return response; //always return the response back 
		        }, 
		        // run this function if the request is not successful
		        error : function(response, ioArgs) { 
		            console.log("failed xhrGet", response, ioArgs); 
		             
		            alert("ERROR: There was an error while submitting your request. Please try again!");
		            /* handle the error... */ 
		            return response; //always return the response back 
		        } 
			}); 
			
			Z2h.link._running = false; 
		}  
	},
	
	// show dialog popup
	popup: function(id, title, msg, okCallback, yes_close) {
		if (typeof yes_close === 'undefined') {
			yes_close = true;
                }

		// close already opend overlay form
		var opened_dialog = dijit.byId(id);
		
		if (opened_dialog) {
			opened_dialog.hide(); 
			opened_dialog.destroy();
		} 
			
		// initialize dialog
		var confirm_form = new dijit.Dialog({id: id, title: title}); 
		dojo.style(confirm_form.titleBar, "display", "none");
		
		var tableContainer = document.createElement("table"); 
		dojo.attr(tableContainer, "border", "0");
		dojo.attr(tableContainer, "cellspacing", "0");
		dojo.attr(tableContainer, "cellpadding", "0");  
		
		var tableBody = document.createElement("tbody");
		
		var tableRow1 = document.createElement("tr"); 
		
		var tableRow1Cell1 = document.createElement("td");
		dojo.addClass(tableRow1Cell1, "overlay_corner");
		dojo.attr(tableRow1Cell1, "id", "top_left_content");
		
		var tableRow1Cell2 = document.createElement("td");
		dojo.attr(tableRow1Cell2, "id", "top_middle_content"); 
		tableRow1Cell2.innerHTML = '<h4 id="signup_overlay_header">' + title + '</h4>';
		
		var tableRow1Cell3 = document.createElement("td");
		dojo.attr(tableRow1Cell3, "id", "top_right_content");
							    					  
		var tableRow2 = document.createElement("tr");
		
		var tableRow2Cell1 = document.createElement("td");
		dojo.addClass(tableRow1Cell1, "overlay_corner");
		dojo.attr(tableRow2Cell1, "id", "left_content");
		
		var tableRow2Cell2 = document.createElement("td");
		dojo.addClass(tableRow2Cell2, "overlay_content"); 
									 
		var closeIcon = document.createElement("div");
		dojo.attr(closeIcon, "title", "Cancel");
		dojo.addClass(closeIcon, "dijitDialogCloseIcon");  
		closeIcon.innerHTML = '<span class="closeText" title="Cancel"></span>'; 
		 
	    // close popup
		var closeHandle = dojo.connect(closeIcon, 
									   "onclick",
									   dojo.hitch(confirm_form, 
											      function(e) { 
										    		e.preventDefault();
										    		confirm_form.attr('content', ''); 
										    		confirm_form.hide(); 
										    		confirm_form.destroy(); 
										     		dojo.disconnect(closeHandle); 
		}));  
		
	    // create popup container 
	    var divContainer = document.createElement("div");
	    dojo.addClass(divContainer, "popupContainer"); 
	    dojo.style(divContainer, {"width": "300px"});
	    
	    // create popup message
	    var pMessage = document.createElement("p");
	    dojo.addClass(pMessage, "popupMessageContent");  
	    dojo.attr(pMessage, "id", id+"_msg");  
	    pMessage.innerHTML = msg; 

            var waitMessage = document.createElement("p");

	    dojo.attr(waitMessage, "id", id+"_wait");  
	    waitMessage.innerHTML = "Please wait ..."; 
	    dojo.style(waitMessage, "color", "#41A317");  
	    dojo.style(waitMessage, "float", "right");
            dojo.style(waitMessage, "display", "none");  
			 
	    var tableRow2Cell3 = document.createElement("td");
	    dojo.attr(tableRow2Cell3, "id", "right_content");
	    
	    var tableRow3 = document.createElement("tr");
	    
	    var tableRow3Cell1 = document.createElement("td");
		dojo.attr(tableRow3Cell1, "id", "bottom_left_content");
		dojo.addClass(tableRow3Cell1, "overlay_corner");
		
		var tableRow3Cell2 = document.createElement("td");
		dojo.attr(tableRow3Cell2, "id", "bottom_middle_content"); 
		
		// create popup buttons
	    var divButtons = document.createElement("div");
	    dojo.addClass(divButtons, "popupButtons");

	    var divButtons_div = document.createElement("div");
	    dojo.attr(divButtons_div, "id", id+"_popupButtons_div");
	    
		var tableRow3Cell3 = document.createElement("td");
	    dojo.attr(tableRow3Cell3, "id", "bottom_right_content");
	    dojo.addClass(tableRow3Cell3, "overlay_corner");
	   
	    if (okCallback) { 
		    // create yes button
	    	var yesBtn = document.createElement("button");
		    dojo.attr(yesBtn, "type", "submit");
                    dojo.attr(yesBtn, "id", id+"_yesBtn");
		    dojo.addClass(yesBtn, "popupYesButton");
		    yesBtn.innerHTML = "<span>Ok</span>";
		    	
			var yesHandle = dojo.connect(yesBtn, 
			    						 "onclick",
			    						  dojo.hitch(confirm_form, 
			    						     		function(e){
					    							    e.preventDefault();

												    if (yes_close) {
													confirm_form.attr("content", ""); 
											    		confirm_form.hide(); 
											    		confirm_form.destroy();
												    }
											    		 
			    						     			dojo.disconnect(yesHandle); 
			    						     			
			    						     			okCallback();
			    						 }));
			    
			dojo.place(yesBtn, divButtons_div, "last"); 
			
			// create no button
		    var noBtn = document.createElement("a"); 
		    dojo.addClass(noBtn, "popupCancelButton");
                    dojo.attr(noBtn, "id", id+"_noBtn");
		    noBtn.innerHTML = "<span>Cancel</span>";  
		    	  
			var noHandle = dojo.connect(noBtn, 
			    						"onclick", 
			    						dojo.hitch(confirm_form, 
			    						    	   function(e){
						    							e.preventDefault();
											    		confirm_form.attr("content", ""); 
											    		confirm_form.hide(); 
											    		confirm_form.destroy(); 
													    dojo.disconnect(noHandle); 
			    						})); 
			    
			dojo.place(noBtn, divButtons_div, "last");
	    } else {
	    	// create yes button.
		    var yesBtn = document.createElement("button");
		    dojo.attr(yesBtn, "type", "submit");
		    dojo.attr(yesBtn, "id", id+"_yesBtn");
		    dojo.addClass(yesBtn, "popupYesButton");
		    yesBtn.innerHTML = "<span>Ok</span>";
		    	
			var yesHandle = dojo.connect(yesBtn, 
			    						 "onclick",
			    						  dojo.hitch(confirm_form, 
			    						     		function(e){
					    							    e.preventDefault();

												    if (yes_close) {
													confirm_form.attr("content", ""); 
											    		confirm_form.hide(); 
											    		confirm_form.destroy();
												    }

					    							    
			    						     			dojo.disconnect(yesHandle);  
			    						 }));
			    
			dojo.place(yesBtn, divButtons_div, "last"); 
	    }
	      
		dojo.place(tableBody, tableContainer, "last");
	    
		dojo.place(tableRow1, tableBody, "last");
		dojo.place(tableRow2, tableBody, "last");
		dojo.place(tableRow3, tableBody, "last");
		
		dojo.place(tableRow1Cell1, tableRow1, "last");
		dojo.place(tableRow1Cell2, tableRow1, "last"); 
		dojo.place(tableRow1Cell3, tableRow1, "last");
		
		dojo.place(tableRow2Cell1, tableRow2, "last");
		dojo.place(tableRow2Cell2, tableRow2, "last"); 
		dojo.place(tableRow2Cell3, tableRow2, "last"); 
		
		dojo.place(tableRow3Cell1, tableRow3, "last");
		dojo.place(tableRow3Cell2, tableRow3, "last"); 
		dojo.place(tableRow3Cell3, tableRow3, "last"); 
		
		dojo.place(closeIcon, tableRow2Cell2, "last");
		dojo.place(divContainer, tableRow2Cell2, "last");
		dojo.place(pMessage, divContainer, "last");
		    
		dojo.place(divButtons_div, divButtons, "last");
		dojo.place(waitMessage, divButtons, "last");
		dojo.place(divButtons, tableRow3Cell2, "last");  
		
		confirm_form.attr("content", tableContainer);
		confirm_form.show(); 
	},
	
	// show error dialog
	error: function(msg) { 
		Z2h.link.popup("error_overlay", "Error", msg, false);
	},
	
	// show delete dialog
	doPostDelete: function(evt) {
		evt.preventDefault(); 
		
		if (dojo.hasAttr(evt.currentTarget, "alt") 
			&& dojo.attr(evt.currentTarget, "alt") == "refresh") {
			Z2h.link._refresh = true;
		}
		 
		Z2h.link._href = evt.currentTarget.href; 
		Z2h.link.popup("delete_confirm_overlay", "Delete Confirmation", evt.currentTarget.title, Z2h.link.okDelete);
	},
	
	// send post request to delete item
	okDelete: function() {
		if (Z2h.link._refresh) {
			dojo.xhrGet({ 
				url: Z2h.link._href+"/format/json",   
				handleAs: "json",
				sync: true,
				headers: {"X-Requested-With": "XMLHttpRequest"},
				load: function(data,ioargs){  
					if (data.result == "1") {
			 			var call_back = dojo.byId('do_after_callback');
						if (call_back) { 
							if (document.createEvent) {
								// Firefox etc.
								event = document.createEvent("HTMLEvents");
								event.initEvent("click", false, true);
								call_back.dispatchEvent(event);
							} else {
								// IE
								call_back.fireEvent("onclick");
							}  
						} else {
							// refresh the current page
							window.location.reload(true);
						} 
			 		} else {
			 			// refresh the current page
						window.location.reload(true);
			 		} 
					
					return data; //always return the response back 
				},
				// if any error occurs, it goes here:
				error: function(response, ioArgs){
					console.log("failed xhrPost", response, ioArgs);
					
					alert("ERROR: There was an error while submitting your form. Please try again!");
					/* handle the error... */ 
		            return response; //always return the response back 
				}
			});
		} else {
			var form = document.createElement("form");
			form.setAttribute("id", "deleteForm");
			form.setAttribute("method", "POST");
			form.setAttribute("action", Z2h.link._href);
			document.getElementsByTagName("body").item(0).appendChild(form);
			form.submit(); 
		}
		
		Z2h.link._refresh = false;
		Z2h.link._href = null;
	},
	
	// show overlay email form to send a content link to a friend
	sendEmailDialog: function(evt) {
		evt.preventDefault();
		
		var href = evt.currentTarget.href;
		
		// only send an ajax request if nothing is running
		if (Z2h.link._running === false) {
			Z2h.link._running = true;
			
			dojo.xhrGet({ 
			 	url: href + "/format/text",  //the relative URL  
			 	handleAs: "text",
//			 	sync: true,
			 	// run this function if the request is successful
		        load : function(response, ioArgs) { 
			 		if (response == "logged_out") { 
			 			window.location.assign("/login-required");
			 		} else {
			 			// close already opend overlay form
			 			var opened_email_form = dijit.byId("email_form_overlay");
						
			 			if (opened_email_form) {
			 				opened_email_form.hide(); 
			 				opened_email_form.destroy();
			 			} 
			 			
			 			// initialize dialog
						var email_form = new dijit.Dialog({id: "email_form_overlay"}); 
						dojo.style(email_form.titleBar, "display", "none");  
						
						email_form.attr("content", response); 
						email_form.show();
		  
					    // close over flag form
						dojo.query("#close_email_btn, .overlay_email_close").forEach(function(node, i) {   
							var closeHandle = dojo.connect(node, 
														   "onclick",
														   dojo.hitch(email_form, 
														     		  function(e){ 
														    				e.preventDefault();
														    				email_form.attr("content", ""); 
														    				email_form.hide(); 
														    				email_form.destroy(); 
														     				dojo.disconnect(closeHandle); 
							})); 
						});  
						
						// overwrite the default esc key event
						var escHandle = dojo.connect(email_form.domNode, "onkeypress", function(e){
									        var key = e.keyCode || e.charCode;
									        var k = dojo.keys;
						
									        if (key == k.ESCAPE) {
									        	e.preventDefault();
									        	email_form.attr("content", ""); 
									        	email_form.hide(); 
									        	email_form.destroy(); 
							     				dojo.disconnect(escHandle); 
									        }
						}); 
						
						// create a submit button to send the flag form
					    var submitButton = dojo.byId("email_submit"); 
					    if (submitButton) {  
					    	dojo.connect(submitButton, 
							    		"onclick",
							    		function(e){ 
											e.preventDefault();  
											dojo.attr(submitButton, "disabled", "disabled");
											Z2h.link.sendToFriend(href);
					    	}); 
					    } 
					    
					    var email_post_form = dojo.byId("email_form"); 
					    if (email_post_form) {  
					    	dojo.connect(email_post_form, 
							    		"onsubmit",
							    		function(e){ 
											e.preventDefault();
											Z2h.link.sendToFriend(href);
					    	}); 
					    }  
			 		}
			  
		            return response; //always return the response back 
		        }, 
		        // run this function if the request is not successful
		        error : function(response, ioArgs) { 
		            console.log("failed xhrGet", response, ioArgs); 
		            
		            alert("ERROR: There was an error while submitting your request. Please try again!");
		            
		            /* handle the error... */ 
		            return response; //always return the response back 
		        }
			}); 
			
			Z2h.link._running = false; 
		} 
	},
	
	// show overlay form to flag a content
	flagDialog: function(evt, evtHandle) {
		evt.preventDefault();
		
		var href = evt.currentTarget.href;
		var clicked = evt.currentTarget;
		
		// only send an ajax request if nothing is running
		if (Z2h.link._running === false) {
			Z2h.link._running = true;
			
			dojo.xhrGet({ 
			 	url: href + "/format/text",
			 	handleAs: "text",
//			 	sync: true,
			 	// run this function if the request is successful
		        load : function(response, ioArgs) { 
			 		if (response == "logged_out") { 
			 			window.location.assign("/login-required");
			 		} else {
			 			// close already opend overlay form
			 			var opened_flag_form = dijit.byId("flag_form_overlay");
						
			 			if (opened_flag_form) {
			 				opened_flag_form.hide(); 
			 				opened_flag_form.destroy();
			 			}
			 			
			 			// initialize dialog
						var flag_form = new dijit.Dialog({id: "flag_form_overlay"}); 
						dojo.style(flag_form.titleBar, "display", "none");  
						
					    flag_form.attr("content", response); 
					    flag_form.show();
					     
					    // close over flag form
						dojo.query("#flag_cancel_btn, .overlay_flag_close").forEach(function(node, i) {  
							var closeHandle = dojo.connect(node, 
														   "onclick",
														   dojo.hitch(flag_form, 
														     		  function(e){ 
														    				e.preventDefault();
														    				flag_form.attr("content", ""); 
														    				flag_form.hide(); 
														    				flag_form.destroy(); 
														     				dojo.disconnect(closeHandle);
														     		   })); 
						}); 
						
						// overwrite the default esc key event
						var escHandle = dojo.connect(flag_form.domNode, "onkeypress", function(e) {
							var key = e.keyCode || e.charCode;
							var k = dojo.keys;
					 
							if (key == k.ESCAPE) {
								e.preventDefault(); 
								
								flag_form.attr("content", ""); 
								flag_form.hide(); 
								flag_form.destroy(); 
							     				
								dojo.disconnect(escHandle); 
							}
						});
						
						// create a submit button to send the flag form
					    var submitButton = dojo.byId("flag_submit_btn"); 
					    if (submitButton) {  
					    	dojo.connect(submitButton, 
							    		"onclick",
							    		function(e){ 
											e.preventDefault();  
											Z2h.link.sendFlagForm(href, clicked, evtHandle);
					    	}); 
					    } 
					    
					    // hook text character length aid
					    var reason = dojo.byId("reason"); 
					    if (reason) {  
					    	dojo.connect(reason, 
							    		"onkeyup",
							    		function(){  
					    				Z2h.string.countTextarea(reason, "flag_characters_remaining", 1000);
					    	});
					    	
					    	// set focus on textarea
						    reason.focus();
					    }
			 		}
			  
		            return response; //always return the response back 
		        }, 
		        // run this function if the request is not successful 
		        error : function(response, ioArgs) { 
		            console.log("failed xhrGet", response, ioArgs); 
		            
		            alert("ERROR: There was an error while submitting your request. Please try again!");
		            
		            /* handle the error... */ 
		            return response; //always return the response back 
		        }
			});  
			
			Z2h.link._running = false; 
		} 
	},
	
	// send a content link to a friend
	sendToFriend: function(href) {
		// count errors
		var errors = 0;
		 
		// validate friend email
		var email_field = dojo.byId('to_email'); 
		if (email_field) {  
			if (!Z2h.validator.email(email_field.value, true, 'to_email_after')) {
				errors++; 
			} 
		}
		
		// validate body
		var body = Z2h.string.trimAll(dojo.byId('body_email').value); 
		if (body.length < 10) {
			errors++;
			dojo.byId('body_email_after').innerHTML = "Your message is too short, it can't be shorter than 10 characters.";
		} else {
			dojo.byId('body_email_after').innerHTML = ""; 
		}
		 
		// validate form
		if (errors > 0) {
			// display error message
			dojo.byId("email_error_notice").style.display = "block";
			
			// if submit button was disabled, remove the attribute
			var submitButton = dojo.byId('email_submit'); 
			if (submitButton && dojo.hasAttr(submitButton, "disabled")) {
				dojo.removeAttr(submitButton, "disabled");
			}
		} else {
			dojo.byId("email_error_notice").style.display = "none";
			
			// hide the signup form
			dojo.byId("overlay_email_form").style.display = "none";
			dojo.byId("overlay_email_position").style.display = "none";
			dojo.byId("overlay_please_wait").style.display = ""; 
			
			// only send an ajax request if nothing is running
			if (Z2h.link._running === false) {
				Z2h.link._running = true;
				
				dojo.xhrPost({
					url: href + "/format/json",
					form: "email_form",  
					handleAs: "json",
//					sync: true,
					headers: {"X-Requested-With": "XMLHttpRequest"},
					load: function(data,ioargs) {  
						if(data.result == "1"){
							dojo.byId("overlay_please_wait").style.display = "none";   
							dojo.byId("email_form_sent").style.display = ""; 
							dojo.byId("overlay_close_button").style.display = "";
						}else{
							// show the signup form with the error message
							dojo.byId("overlay_email_form").style.display = "";
							dojo.byId("overlay_email_position").style.display = "";
							dojo.byId("overlay_please_wait").style.display = "none";
							
							for (var k in data.errors) { 
								if (k == "general") {
									dojo.byId("general_email_error").innerHTML = data.errors[k];
									dojo.byId("email_error_notice").style.display = "block";
								} else { 
									dojo.byId(k + "_after").innerHTML = data.errors[k];
									dojo.byId(k + "_after").style.display = "block"; 
								} 
							} 
							
							// if submit button was disabled, remove the attribute
							var submitButton = dojo.byId('email_submit'); 
							if (submitButton && dojo.hasAttr(submitButton, "disabled")) {
								dojo.removeAttr(submitButton, "disabled");
							}
						}
						
						return data; //always return the response back 
					},
					// if any error occurs, it goes here: 
					error : function(response, ioArgs) { 
			            console.log("failed xhrGet", response, ioArgs); 
			            
			            alert("ERROR: There was an error while submitting your request. Please try again!");
			            
			            /* handle the error... */ 
			            return response; //always return the response back 
			        }
				});
				
				Z2h.link._running = false;
			} 
		} 
	},

	// send flag form.
	sendFlagForm: function(href, clicked, evtHandle) { 
		var reason = dojo.byId("reason"); 
		var reason_error = dojo.byId("reason_form_errors"); 
		 
		if (dojo.hasAttr(clicked, "alt") 
			&& dojo.attr(clicked, "alt") == "refresh") {
			Z2h.link._refresh = true;
		}
		
		if (reason) {
			// validate reason.
			if (reason.value.length > 10) {  
				// hide flag form elements.
				dojo.query(".flag_form_group").forEach(function(node) {
					node.style.display = "none";
				}); 
				
				dojo.byId("overlay_please_wait").style.display = "block";
				
				// only send an ajax request if nothing is running.
				if (Z2h.link._running === false) {
					Z2h.link._running = true;
					
					// submit the form.
					dojo.xhrPost({
						url: href + "/format/json", 
						form: "flag_form",  
						handleAs: "json",
//						sync: true,
						headers: {"X-Requested-With": "XMLHttpRequest"},
						load: function(data,ioargs){  
							if(data.result == "1"){ 
								// close flag overlay form.
								var flag_form = dijit.byId("flag_form_overlay");
								flag_form.hide(); 
			    				flag_form.destroy(); 

			    				if (Z2h.link._refresh) {
			    					var call_back = dojo.byId('do_after_callback');
									if (call_back) { 
										if (document.createEvent) {
											// Firefox etc.
											event = document.createEvent("HTMLEvents");
											event.initEvent("click", false, true);
											call_back.dispatchEvent(event);
										} else {
											// IE
											call_back.fireEvent("onclick");
										}  
									} else {
										// refresh the current page
										window.location.reload(true);
									}
			    				} else {
			    					// disable flag link
				    				dojo.removeClass(clicked, "flag"); 
				    				dojo.addClass(clicked, "awaiting_moderation");
				    				dojo.removeAttr(clicked, "href");
				    				dojo.attr(clicked, "title", "Waiting for moderation"); 
									clicked.innerHTML = "<span>Flagged</span>"; 
			    				} 
								
								dojo.disconnect(evtHandle);  
							}else{
								// show the flag form with the error message
								dojo.query(".flag_form_group").forEach(function(node) {
									node.style.display = "block";
								});
								
								dojo.byId("overlay_please_wait").style.display = "none";
								
								for(var k in data.errors){ 
									reason_error.innerHTML += data.errors[k]+"<br />"; 
								} 
								
								reason_error.style.display = "block";
								
								// set focus on textarea
							    reason.focus();
							}
							
							Z2h.link._refresh = false; 
						},
						// if any error occurs, it goes here:
						error: function(response, ioArgs){
							console.log("failed xhrPost", response, ioArgs); 
							 
							// show the flag form with the error message
							dojo.query(".flag_form_group").forEach(function(node) {
								node.style.display = "block";
							});
							
							dojo.byId("overlay_please_wait").style.display = "none";
							
							alert("ERROR: There was an error while submitting your request. Please try again!"); 
							
							// set focus on textarea
						    reason.focus();
						    
							/* handle the error... */ 
				            return response; //always return the response back 
						}
					});
					
					Z2h.link._running = false;
				} 
			} else { 
				reason_error.innerHTML = "Your reason is too short (min 10 characters)";  
				reason_error.style.display = "block"; 
				
				// show the flag form with the error message
				dojo.query(".flag_form_group").forEach(function(node) {
					node.style.display = "block";
				});
				
				dojo.byId("overlay_please_wait").style.display = "none";
			}
		} 
	}
}

//---------------------- COMMUNITY COMMENT JS --------------------------------
Z2h.comment = {
	_running: false, 
		
	init: function() {
		Z2h.comment.initEditor(); 
		Z2h.comment.initAjax(); 
	},
	
	initEditor: function() { 
		dojo.query(".reply_text").forEach(function(textarea) {  
			var errors = 0;
			dojo.query("div.error_msg", textarea.parentNode).forEach(function(err) {
				errors++;
			}); 
				
			if (textarea.value.length == 0 && errors == 0) {
				dojo.style(textarea, "height", "14px"); 
			} 
			
			dojo.connect(textarea, "onfocus", Z2h.comment.expand);
			dojo.connect(textarea, "onblur", Z2h.comment.shrink);
		}); 
		
		dojo.query(".text_length_aid").forEach(function(aid) {  
			 var id = aid.id;
			 var textarea_dom = dojo.byId(id + "_textarea");
			   
			 var length = 1000;
			 
			 if (dojo.hasAttr(aid, "title")) {
				 length = dojo.attr(aid, "title");
			 } 
			 
			 if (textarea_dom) { 
				 Z2h.string.countTextarea(textarea_dom, id, length);
				 
				 dojo.connect(textarea_dom, "onkeyup", function() {   
					 Z2h.string.countTextarea(textarea_dom, id, length);
		    	 });  
			 } 
		});  
	},
	
	initAjax: function() { 
		dojo.query(".show_no_replies").forEach(function(link) {  
			var showHandle = dojo.connect(link, "onclick", function(e) {
					Z2h.comment.showNoReplies(e);
					dojo.disconnect(showHandle); 
			});  
		}); 
		
		dojo.query(".hide_no_replies").forEach(function(link) {  
			var hideHandle = dojo.connect(link, "onclick", function(e) {
				Z2h.comment.hideNoReplies(e);
				dojo.disconnect(hideHandle); 
			});  
		}); 
		
		dojo.query(".more_replies").forEach(function(link) {  
			var showHandle = dojo.connect(link, "onclick", function(e) {
				Z2h.comment.showMoreReplies(e);
				dojo.disconnect(showHandle); 
			});  
		});  
		
		dojo.query(".less_replies").forEach(function(link) {  
			var hideHandle = dojo.connect(link, "onclick", function(e) {
				Z2h.comment.hideMoreReplies(e);
				dojo.disconnect(hideHandle); 
			});  
		});   
		 
		dojo.query(".add_post_reply").forEach(function(btn) {  
			dojo.connect(btn, "onclick", Z2h.comment.addReply); 
		});
		
		var add_comment = dojo.byId("discussion_comment_submit");
		
		if (add_comment) {
			dojo.connect(add_comment, "onclick", Z2h.comment.addComment); 
		} 
	},
	
	// called after a new comment is added successfully
	refresh: function(href) { 
		// update comment count in the view post page and login section
		dojo.query(".discussion_comment_count").forEach(function(link) {  
			var current_count = dojo.attr(link, "alt");
			var current_text = link.innerHTML;
			
			var new_count = parseInt(current_count) + 1; 
			var new_text = "";
			
			if (new_count != 1) {
				new_text = new_count + " comments";
			} else {
				new_text = new_count + " comment";
			}
			 
			if (dojo.hasAttr(link, "title")) {
				dojo.attr(link, "title", new_text);
			}
			dojo.attr(link, "alt", new_count);
			link.innerHTML = new_text; 
		}); 
		
		// update dom id. (make sure there is div id=load_ajax_content_here)
		var update_dom = dojo.byId("load_ajax_content_here");
		 
		// only send an ajax request if nothing is running and the dom exists
		if (update_dom) {  
			// reload the comment list 
			dojo.xhrGet({ 
				url: href + "/format/text/",
				handleAs: "text",
    		 	sync: true,
			 	// run this function if the request is successful
		        load : function(response, ioArgs) { 
		            // set some element's content
					update_dom.innerHTML = response;  
					
		            // initialize js
					Z2h.global.init(); 
					
		            return response; //always return the response back 
		        }, 
		        // run this function if the request is not successful
		        error : function(response, ioArgs) { 
		            console.log("failed xhrGet", response, ioArgs); 
		            
		            alert("ERROR: There was an error while submitting your request. Please try again!");
		            /* handle the error... */ 
		            return response; //always return the response back 
		        } 
			}); 
		}
	},
	
	addComment: function(evt) { 
		evt.preventDefault();
	 
		var comment_form = dojo.byId("comment_post_form");
		
		// only send an ajax request if nothing is running and the dom exists. 
		if (comment_form && Z2h.comment._running === false) {
			Z2h.comment._running = true;   
		
			var overlay_wait = dojo.byId("comment_post_new_loading"); 
			
			if (overlay_wait) { 
				comment_form.style.display = "none"; 
				overlay_wait.style.display = ""; 
			}
			
			dojo.xhrPost({
				url: comment_form.action+"/format/json",
				form: comment_form.id,
				handleAs: "json",
//				sync: true,
				headers: {"X-Requested-With": "XMLHttpRequest"},
				load: function(data,ioargs){  
					if(data.result == "-1"){ 
						// reload the page.
						window.location.reload(true);
					} else if(data.result == "1"){  
						var hidden_url = dojo.byId("comment_post_new_after_url");
						
						if (hidden_url) {  
							Z2h.comment.refresh(hidden_url.value);
						} else {
							// reload the page
							window.location.reload(true);
						} 
					}else{ 
						if (overlay_wait) { 
							overlay_wait.style.display = "none";  
							comment_form.style.display = ""; 
						}
						
						var comment_errors = dojo.byId("comment_post_new_error");
							
						if (comment_errors) {
							comment_errors.innerHTML = "";
								
							for(var k in data.errors){ 
								var errorItem = document.createElement('p');
								errorItem.innerHTML = data.errors[k][0];
								comment_errors.appendChild(errorItem); 
							}
						} 
					} 
						
					return data; //always return the response back 
				},
				// if any error occurs, it goes here:
				error: function(response, ioArgs){
					console.log("failed xhrPost", response, ioArgs);
						 
					alert("ERROR: There was an error while submitting your comment form. Please try again!");
					/* handle the error... */ 
			        return response; //always return the response back 
				}
			});
			
			Z2h.comment._running = false; 
		} 
	},
	 
	addReply: function(evt) { 
		evt.preventDefault();
		
		var update_dom_id = dojo.attr(evt.currentTarget, "name");
		var update_dom = dojo.byId(update_dom_id);
		var reply_form = dojo.byId("reply_form_" + update_dom_id);
		var hidden_url = dojo.byId(update_dom_id + "_after_url");
		
		var button_id = evt.target.id;
		var reply_textarea_id = button_id.replace("submit", "textarea"); 
		var reply_p_id = button_id.replace("_submit", ""); 
		var error_id = button_id.replace("submit", "error"); 
		var reply_text = dojo.byId(reply_textarea_id);
		
		// only send an ajax request if nothing is running and the dom exists
		if (reply_form && reply_text && Z2h.comment._running === false) {
			Z2h.comment._running = true;   
		
			var overlay_wait = dojo.byId(update_dom_id + "_loading");
			var form_section = dojo.byId(update_dom_id + "_form_section");
			
			if (overlay_wait && form_section) { 
				form_section.style.display = "none"; 
				overlay_wait.style.display = ""; 
			}
			
			dojo.xhrPost({
				url: reply_form.action + "/format/json",
				form: reply_form.id,
				handleAs: "json",
//				sync: true,
				headers: {"X-Requested-With": "XMLHttpRequest"},
				load: function(data,ioargs){  
					if (data.result == "-1") { 
						// reload the page
						window.location.reload(true);
					} else if(data.result == "1") { 
						if (hidden_url && update_dom) {
							// load the updated comment list.  
							dojo.xhrGet({ 
							 	url: hidden_url.value + "/offset/0/format/text", 
							 	handleAs: "text",
//							 	sync: true,
							 	// run this function if the request is successful
						        load : function(response, ioArgs) { 
									// set some element's content
									update_dom.innerHTML= response;  
									
									Z2h.comment.init();
									
									// initialize flag link
									dojo.query("a.flag").forEach(function(link) {
										var flagHandle = dojo.connect(link, "onclick", function(e) {  
									        Z2h.link.flagDialog(e, flagHandle); // need to pass flag handle to disconnect after flagging item.
									    }); 
									});
									
						            return response; //always return the response back 
						        }, 
						        // run this function if the request is not successful 
						        error : function(response, ioArgs) { 
						            console.log("failed xhrGet", response, ioArgs); 
						            
						            alert("ERROR: There was an error while submitting your request. Please try again!");
						            
						            /* handle the error... */ 
						            return response; //always return the response back 
						        }
							});  
						} 
						
					} else { 
						if (overlay_wait && form_section) { 
							overlay_wait.style.display = "none";  
							form_section.style.display = ""; 
						}
						
						var comment_errors = dojo.byId(error_id);
							
						if (comment_errors) {
							comment_errors.innerHTML = "";
								
							for(var k in data.errors){ 
								var errorItem = document.createElement("p");
								errorItem.innerHTML = data.errors[k][0];
								comment_errors.appendChild(errorItem); 
							}
						} 
						
						dojo.attr(reply_text, "style", "height:150px;"); 
					} 
						
					return data; //always return the response back 
				},
				// if any error occurs, it goes here:
				error: function(response, ioArgs){
					console.log("failed xhrPost", response, ioArgs);
						 
					alert("ERROR: There was an error while submitting your reply form. Please try again!");
					/* handle the error... */ 
			        return response; //always return the response back 
				}
			});
			
			Z2h.comment._running = false; 
		} 
	},
	
	showNoReplies: function(evt) { 
		evt.preventDefault();  
		 
		var update_dom_id = dojo.attr(evt.currentTarget, "alt");
		var clicked = evt.currentTarget;
		
		var update_dom = dojo.byId("first_reply_" + update_dom_id);
		
		// only send an ajax request if nothing is running and the dom exists
		if (update_dom && Z2h.comment._running === false) {
			Z2h.comment._running = true;   
			
			dojo.query("li.no_replies", update_dom).forEach(function(node) {  
				node.style.display = "";  
			});   
			
			dojo.removeClass(evt.currentTarget, "show_no_replies");
			dojo.removeClass(evt.currentTarget, "collapsed_replies");
			
			dojo.addClass(evt.currentTarget, "hide_no_replies"); 
			dojo.addClass(evt.currentTarget, "expanded_replies");  
			
			var hideHandle = dojo.connect(evt.currentTarget, "onclick", function(e){
				Z2h.comment.hideNoReplies(e);
				dojo.disconnect(hideHandle); 
			});  
			
			Z2h.comment._running = false; 
		} 
	},
	
	hideNoReplies: function(evt) { 
		evt.preventDefault();  
		 
		var update_dom_id = dojo.attr(evt.currentTarget, "alt");
		var clicked = evt.currentTarget;
		
		var update_dom = dojo.byId("first_reply_" + update_dom_id);
		
		// only send an ajax request if nothing is running and the dom exists. 
		if (update_dom && Z2h.comment._running === false) {
			Z2h.comment._running = true;   
			
			dojo.query("li.no_replies", update_dom).forEach(function(node) {  
				node.style.display = "none";  
			});
			
			dojo.removeClass(evt.currentTarget, "hide_no_replies");
			dojo.removeClass(evt.currentTarget, "expanded_replies");
			
			dojo.addClass(evt.currentTarget, "show_no_replies"); 
			dojo.addClass(evt.currentTarget, "collapsed_replies"); 
			
			var showHandle = dojo.connect(evt.currentTarget, "onclick", function(e){
				Z2h.comment.showNoReplies(e);
				dojo.disconnect(showHandle); 
			});  
			
			Z2h.comment._running = false; 
		} 
	},
	 
	showMoreReplies: function(evt) { 
		evt.preventDefault(); 
		
		var href = evt.currentTarget.href;
		var update_dom_id = dojo.attr(evt.currentTarget, "alt");
		var clicked = evt.currentTarget;
		
		var update_dom = dojo.byId(update_dom_id);
		
		// only send an ajax request if nothing is running and the dom exists 
		if (update_dom && Z2h.comment._running === false) {
			Z2h.comment._running = true; 
			
			var overlay_wait = dojo.byId(update_dom_id + "_loading");
			
			if (overlay_wait) { 
				overlay_wait.style.display = ""; 
			}
			
			// check the ajax request is made previously
			var already_requested = dojo.query('ul.hide_comment_replies_list', update_dom).length;
			var hidden_replies_dom = null;
			
			if (already_requested == 1) {
				hidden_replies_dom = dojo.query('ul.hide_comment_replies_list', update_dom)[0];
				dojo.removeClass(hidden_replies_dom, 'hide_comment_replies_list');
				update_dom.style.display = "";
			} else { 
				// hide the link from user double clicking
				evt.currentTarget.style.display = "none";  
				
				// if not, call a ajax request
				dojo.xhrGet({ 
				 	url: href + "/format/text", 
				 	handleAs: "text",
				 	sync: true,
				 	// run this function if the request is successful
			        load : function(response, ioArgs) { 
						// set some element's content
						update_dom.innerHTML= response; 
			             
						// initialize editor
						Z2h.comment.initEditor(); 
						
						// initialize rating links
						dojo.query('a.rate_up_link').forEach(function(link) {
							var connected = dojo.connect(link, "onclick", function(e){ 
								e.preventDefault();  
								Z2h.link.rate(link, 1, connected); 
							});  
						});
						
						// hook onclick event to rate down creation item
						dojo.query('a.rate_down_link').forEach(function(link) {
							var connected = dojo.connect(link, 
									    "onclick",
									     function(e){ 
											e.preventDefault();  
											Z2h.link.rate(link, -1, connected); 
									     });
						});

						// initialize flag link.
						dojo.query('a.flag').forEach(function(link) {
							var flagHandle = dojo.connect(link, 'onclick', function(e){  
						        Z2h.link.flagDialog(e, flagHandle); // need to pass flag handle to disconnect after flagging item.
						    }); 
						}); 
						
			            return response; //always return the response back 
			        }, 
			        // run this function if the request is not successful 
			        error : function(response, ioArgs) { 
			            console.log("failed xhrGet", response, ioArgs); 
			            
			            alert("ERROR: There was an error while submitting your request. Please try again!");
			            
			            /* handle the error... */ 
			            return response; //always return the response back 
			        }
				}); 
			}
			
			evt.currentTarget.style.display = "";
			
			dojo.removeClass(evt.currentTarget, "more_replies");
			dojo.addClass(evt.currentTarget, "less_replies"); 
			 
			var link_span = evt.currentTarget.innerHTML; 
			var new_link_span = link_span.replace("+ Show","- Hide");
			var new_title = new_link_span.replace("<span>- ","");
			new_title = new_title.replace("</span>","");
			
			evt.currentTarget.innerHTML = new_link_span;
			dojo.attr(evt.currentTarget, "title", new_title);
			
			var hideHandle = dojo.connect(evt.currentTarget, 
										  "onclick",
										  function(e){
											Z2h.comment.hideMoreReplies(e);
										    dojo.disconnect(hideHandle); 
									      }); 
			 
			if (overlay_wait) { 
				overlay_wait.style.display = "none"; 
			}
			
			Z2h.comment._running = false; 
		} 
	},
	
	hideMoreReplies: function(evt) { 
		evt.preventDefault(); 
		
		var href = evt.currentTarget.href;
		var update_dom_id = dojo.attr(evt.currentTarget, "alt");
		var clicked = evt.currentTarget;
		
		var update_dom = dojo.byId(update_dom_id);
		
		// only send an ajax request if nothing is running and the dom exists. 
		if (update_dom && Z2h.comment._running === false) {
			Z2h.comment._running = true;  
			
			update_dom.style.display = "none";
			
			// check the ajax request is made previously.  
			var already_requested = dojo.query('ul.comment_replies_list', update_dom).length;
			var replies_dom = null;
			
			if (already_requested == 1) {
				replies_dom = dojo.query('ul.comment_replies_list', update_dom)[0];
				dojo.addClass(replies_dom, 'hide_comment_replies_list');
			}    
			
			dojo.removeClass(evt.currentTarget, "less_replies");
			dojo.addClass(evt.currentTarget, "more_replies");  
			
			var link_span = evt.currentTarget.innerHTML;
			var new_link_span = link_span.replace("- Hide","+ Show");
			
			var new_title = new_link_span.replace("<span>+ ","");
			new_title = new_title.replace("</span>","");
			
			evt.currentTarget.innerHTML = new_link_span; 
			dojo.attr(evt.currentTarget, "title", new_title);
			
			var showHandle = dojo.connect(evt.currentTarget, 
										  "onclick",
										  function(e){
												Z2h.comment.showMoreReplies(e);
											    dojo.disconnect(showHandle); 
									      }); 
			
			Z2h.comment._running = false; 
		} 
	},
	
	expand: function(evt) { 
		var errors = 0;
		dojo.query('div.error_msg', evt.currentTarget.parentNode).forEach(function(err) {
			if (err.innerHTML) {
				errors++;
			}  
		});
		
		if (evt.currentTarget.value.length == 0 && errors == 0) {
			dojo.animateProperty({ 
				node : evt.currentTarget, 
			    duration : 350, 
			    properties : { 
			    	height : {start: '14', end: '150'} 
			    } 
			}).play();
		} 
	},
	
	shrink: function(evt) {  
		var errors = 0;
		dojo.query('div.error_msg', evt.currentTarget.parentNode).forEach(function(err) {
			if (err.innerHTML) {
				errors++;
			}
		});
		
		if (evt.currentTarget.value.length == 0 && errors == 0) {
			dojo.animateProperty({ 
				node : evt.currentTarget, 
			    duration : 350, 
			    properties : { 
			    	height : {start: '150', end: '14'} 
			    } 
			}).play(); 
		} 
	}
}

//---------------------- INBOX JS --------------------------------

Z2h.inbox = {
	_href: null,
		
	init: function() {  
		// hook onchange event to select messages.
		var mark_select_link = dojo.byId('mark_as_select');
		if (mark_select_link) {
			dojo.connect(mark_select_link, 'onchange', Z2h.inbox.markSelect); 
		}
	
		// hook onclick event to mark all the selected messages as read.
		var mark_read_link = dojo.byId('markAsRead');
		if (mark_read_link) {
			dojo.connect(mark_read_link, 'onclick', Z2h.inbox.markRead); 
		}
	
		// hook onclick event to mark all the selected messages as unread.
		var mark_unread_link = dojo.byId('markAsUnread');
		if (mark_unread_link) {
			dojo.connect(mark_unread_link, 'onclick', Z2h.inbox.markUnread); 
		}
		
		// hook onclick event to delete all the selected messages.
		var mark_hidden_link = dojo.byId('markAsHidden');
		if (mark_hidden_link) {
			dojo.connect(mark_hidden_link, 'onclick', Z2h.inbox.markHidden); 
		}  
	},
	
	markSelect: function(evt) {
		evt.preventDefault();
		 
		switch (evt.currentTarget.value) {
			case 'all':
				Z2h.inbox.selectAll();
				break;
				
			case 'unread':
				Z2h.inbox.selectUnread();
				break;
				
			case 'read':
				Z2h.inbox.selectRead();
				break;
				
			default:
				Z2h.inbox.selectNone();
		} 
	},
	
	selectAll: function() { 
		dojo.query(".message_unread").concat(
				dojo.query(".message_read").concat(
						dojo.query(".message_reply"))).forEach("item.checked = true");  
	},
	
	selectUnread: function() { 
		Z2h.inbox.selectNone();
		 
		// message_unread
		dojo.query(".message_unread").forEach("item.checked = true");
		 
	},
	
	selectRead: function() {
		Z2h.inbox.selectNone();
		 
		// message_read && message_reply
		dojo.query(".message_read").concat(
				dojo.query(".message_reply")).forEach("item.checked = true"); 
	},
	
	selectNone: function() {
		dojo.query(".message_unread").concat(
				dojo.query(".message_read").concat(
						dojo.query(".message_reply"))).forEach("item.checked = false"); 
	},
	
	markRead: function(evt) {
		evt.preventDefault();
		
		var items = new Array();
		dojo.query(".message_unread").concat(
				dojo.query(".message_read").concat(
						dojo.query(".message_reply"))).forEach(
							function(item){
								if (item.checked) {
									items.push(item.value);
								}
							});
		 
		// check as least one message is selected.
		if (items.length > 0) { 
			items = items.join(";"); 
			 
			window.location.assign(evt.currentTarget.value+"/ids/"+items); 
		} else {
			Z2h.link.error("Please select at least one message to mark as read.");
		}  
	},
	
	markUnread: function(evt) {
		evt.preventDefault();
		 
		var items = new Array();
		dojo.query(".message_unread").concat(
				dojo.query(".message_read").concat(
						dojo.query(".message_reply"))).forEach(
							function(item){
								if (item.checked) {
									items.push(item.value);
								}
							});
		
		// check as least one message is selected.
		if (items.length > 0) { 
			items = items.join(";");

			window.location.assign(evt.currentTarget.value+"/ids/"+items); 
		} else {
			Z2h.link.error("Please select at least one message to mark as unread.");
		} 
	},
	
	markHidden: function(evt) {
		evt.preventDefault();
		 
		var items = new Array();
		dojo.query(".message_unread").concat(
				dojo.query(".message_read").concat(
						dojo.query(".message_reply"))).forEach(
							function(item){
								if (item.checked) {
									items.push(item.value);
								}
							});
		
		// check as least one message is selected.
		if (items.length > 0) {
			var questionString = "Are you sure you want to delete";
			 
			if (items.length > 1) {
				questionString += " these messages?";
			} else {
				questionString += " this message?";
			}
			
			questionString += " Deleting a message will not block particient from replying to the message.";
			
			items = items.join(";");
			
			Z2h.inbox._href = evt.currentTarget.value+"/ids/"+items; 
			
			Z2h.link.popup('delete_confirm_overlay', 'Delete Confirmation', questionString, Z2h.inbox.okDeleteAll); 
		} else {
			Z2h.link.error("Please select at least one message to delete.");
		} 
	},
	
	// send post request to delete all item.
	okDeleteAll: function() {
		window.location.assign(Z2h.inbox._href);
		
		Z2h.inbox._href = null;
	}
} 

//---------------------- INBOX AUTO-COMPLETE RECIPIENTS JS --------------------------------

Z2h.inbox.recipients = { 
	init: function() { 
		// hook onclick event to remove a recipient from recipients list.
		dojo.query('a.remove_user').forEach(function(link) {
			dojo.connect(link, 'onclick', Z2h.inbox.recipients.remove);
		}); 
		
		var total = Z2h.inbox.recipients.total();
		if (total > 1) { 
			var select = dijit.byId('username_select');
			if (select) {
				select.promptMessage = '';
				select.invalidMessage = '';
			} 
		} 
	}, 
	
	// count total number of recipients.
	total: function() {
		var total = 0; 
		var hiddenRecipients = dojo.byId('hidden_recipients');
		
		if (hiddenRecipients) { 
			// check the maximum recipients. 
			dojo.query("div#hidden_recipients input.hidden_to").forEach(function(node, i){
			   	total++;
			});
		} 

		return total;
	},
	
	// clear username input field.
	clear: function(select) { 
		if (!select.isValid()) {
	    	select.textbox.value = "";
	    } else {
	    	select.focus();
	    }
		
		select.promptMessage = '';
		select.invalidMessage = '';
	},
	
	// check username is available from the options.
	check: function(select) { 
		var user_id = select.getValue();
		var username = select.textbox.value; 
		var total = Z2h.inbox.recipients.total();
		var added = 0;
		
	    if (user_id && username) {  
	    	dojo.query("div#hidden_recipients > input.recipient_"+user_id).forEach(function(node, i){
				added++;
			}); 
	    	
	    	if (added == 0) { 
		   		if (total < 20) {
		   			// add the user to recipient container. 
			   		Z2h.inbox.recipients.add(user_id, username);
			  		select.promptMessage = '';
					select.invalidMessage = '';
					total++;  
		   		} 
		   	} else {
		   		select.promptMessage = 'You already added '+username;
		   	}

		   	// reset select.
		  	select.textbox.value = "";  
		  	select.reset();

		  	if (total >= 20) {
		  		select.promptMessage = 'You\'ve added the maximum recipients';
		  		select.setDisabled(true);
		  	}
	    }
	},
	
	// add a recipient.
	add: function(id, username) {
		// add to hidden recipients list.
		var hiddenRecipients = dojo.byId('hidden_recipients');
		
		if (hiddenRecipients) {
			var inputHiddenTo = document.createElement("input");
			 
			dojo.addClass(inputHiddenTo, "hidden_to");
			dojo.addClass(inputHiddenTo, "recipient_"+id);
			dojo.attr(inputHiddenTo, "type", "hidden");
			dojo.attr(inputHiddenTo, "name", "recipient_to["+id+"]["+username+"]");
			dojo.attr(inputHiddenTo, "value", id);
					 
			dojo.place(inputHiddenTo, hiddenRecipients, "last"); 
			
			// create recipient container box.
			var hiddenContainer = dojo.byId('hidden_container');
		 
			if (hiddenContainer) {
				var divRecipientBox = document.createElement("div");
				dojo.addClass(divRecipientBox, "recipient_box");
				dojo.addClass(divRecipientBox, "recipient_"+id);	 
				divRecipientBox.innerHTML = username;
				
				var aRecipientRemoveLink = document.createElement("a");
				dojo.addClass(aRecipientRemoveLink, "remove_user");
				dojo.attr(aRecipientRemoveLink, "id", id);
				dojo.attr(aRecipientRemoveLink, "alt", username);
				dojo.attr(aRecipientRemoveLink, "title", "Remove this user from recipients?");
				aRecipientRemoveLink.innerHTML = "x";
				
				// hook remove recipient event to x. 
				dojo.connect(aRecipientRemoveLink, "onclick", Z2h.inbox.recipients.remove);
						    
				dojo.place(aRecipientRemoveLink, divRecipientBox, "last"); 
				dojo.place(divRecipientBox, hiddenContainer, "last");  
				
				// delete the username from the option list.
				/* z2h_users.fetch({ 
					onItem: function(item) {  
						if (z2h_users.hasAttribute(item, "id")) {
							var this_id = z2h_users.getValue(item, "id");
							if (this_id == id) { 
								z2h_users.setValue(item, "status", '0');
							}  
						} 
					}  
				}); */
			} 	
		} 
	},
	
	// remove a recipient.
	remove: function(evt) {
		evt.preventDefault();
		
		var remove_id = evt.currentTarget.id;
	    var remove_user = dojo.byId(remove_id); 
	    
	    if (remove_id && remove_user) {
	    	var remove_username = dojo.attr(remove_user, "alt");
			 
			var total = Z2h.inbox.recipients.total();
				
			dojo.query(".recipient_"+remove_id).forEach(function(node, i){
				node.parentNode.removeChild(node); 
			}); 
			
			/*z2h_users.fetch({ 
				onItem: function(item) {  
					if (z2h_users.hasAttribute(item, "id")) {
						var this_id = z2h_users.getValue(item, "id");
						var this_status = z2h_users.getValue(item, "status");
						if (this_id == remove_id && this_status == '0') { 
							z2h_users.setValue(item, "status", '10');
						}  
					} 
				}  
			});*/ 
			
			// if select option was disabled, clear the restriction.
			total--;

			if (total < 20) {
				var select = dijit.byId('username_select');
				
				if (total < 1) {
					select.promptMessage = 'start typing a username';
					select.invalidMessage = 'no such username found';
				} else {
					select.promptMessage = '';
					select.invalidMessage = '';
				} 
				
		  		select.setDisabled(false); 
		  		select.textbox.value = '';
		  		select.focus();
		   	} 
	    } 
	}
}

//---------------------- USER MODULE JS --------------------------------

Z2h.user = {
	_running: false, 
		
	init: function() {  
		// hook onclick event to show login form.
		var login_link = dojo.byId('back_to_login');
		if (login_link) {
			dojo.connect(login_link, 'onclick', Z2h.user.showLogin); 
		}
		
		// hook onclick event to submit login form.
		var login_submit_btn = dojo.byId('login_submit');
		if (login_submit_btn) {
			dojo.connect(login_submit_btn, 'onclick', Z2h.user.login);
		}  

		// for safari, hook onsubmit event to submit login form.
		var login_submit_form = dojo.byId('login_form');
		if (login_submit_form) {
			dojo.connect(login_submit_form, 'onsubmit', Z2h.user.login);
		} 
		
		// hook onclick event to show forgot password form.
		var forgot_password_link = dojo.byId('forgot_password_link');
		if (forgot_password_link) {
			dojo.connect(forgot_password_link, 'onclick', Z2h.user.showForgot); 
		}
	
		// hook onclick event to submit forgot password form.
		var forgot_submit_btn = dojo.byId('lost_password_submit');
		if (forgot_submit_btn) {
			dojo.connect(forgot_submit_btn, 'onclick', Z2h.user.forgot);
		} 
		
		// for safari, hook onsubmit event to submit forgot password form.
		var forgot_submit_form = dojo.byId('forgot_form');
		if (forgot_submit_form) {
			dojo.connect(forgot_submit_form, 'onsubmit', Z2h.user.forgot); 
		} 
		
		// hook onclick event to show dialog to sign up.
		dojo.query('a.signup').forEach(function(link) {
			dojo.connect(link, 'onclick', Z2h.user.showSignup); 
		});
	},
	
	showLogin: function(evt) {
		evt.preventDefault(); 
		
		// login form fields. 
		var passwd_field = dojo.byId('login_passwd');
		var error_msg = dojo.byId('login_form_error_msg');
		
		// reset values.
		passwd_field.value = "";
		error_msg.style.display = "none";
		error_msg.innerHTML = "";
		
		// hide forgot password form section, but show login form section.
		dojo.byId('forgotpasswd_form_section').style.display = "none"; 
		dojo.byId('login_form_section').style.display = "block"; 
	},
	
	showForgot: function(evt) {
		evt.preventDefault(); 
		
		// forgot form fields. 
		var email_field = dojo.byId('forgot_email'); 
		var error_msg = dojo.byId('forgot_form_error_msg');
		var success_msg = dojo.byId('forgot_form_success_msg');
		
		// reset values.
		email_field.value = "";
		error_msg.style.display = "none";
		error_msg.innerHTML = "";
		success_msg.innerHTML = "";
		
		// hide login form section, but show forgot password form section.
		dojo.byId('login_form_section').style.display = "none";
		dojo.byId('forgotpasswd_form_section').style.display = "block";  
		
		// hide after form submission section, but show forgot password form section.
		dojo.byId("forgot_form_success_container").style.display = "none"; 
		dojo.byId("forgot_form_field").style.display = "block"; 
	},
	
	login: function(evt) {
		evt.preventDefault(); 
		
		// clear session logged out error message.
		dojo.query('.error_msg').forEach(function(node) {  
			node.parentNode.removeChild(node);
		}); 
		
		// login form fields.
		var form = dojo.byId('login_form');
		var username_field = dojo.byId('login_username');
		var passwd_field = dojo.byId('login_passwd');
		var error_msg = dojo.byId('login_form_error_msg');
		 
		var errors = 0; 
		
		// validate username. 
		if (username_field.value.length == 0) { 
			error_msg.innerHTML = "Username is required."; 
			errors++;
		} 
		
		// validate password.  
		if (passwd_field.value.length == 0) {
			if (errors == 0) {
				// no username error.
				error_msg.innerHTML = "Password is required."; 
			} else {
				error_msg.innerHTML = "Username and Password are required."; 
			}
			
			errors++;  
		} 
		
		// validate form.
		if(errors == 0){ 
			error_msg.style.display = "none";
			error_msg.innerHTML = "";
			
			// hide the login form.
			dojo.byId("login_form_submit").style.display = "none";
			dojo.byId("login_please_wait").style.display = "";  
			
			dojo.xhrPost({
				url: form.action+'/format/json', 
				form: "login_form",  
				handleAs: "json",
//				sync: true,
				headers: {"X-Requested-With": "XMLHttpRequest"},
				load: function(data,ioargs){  
					if(data.result == '1'){ 
						if (data.target == "/") {
							window.location.reload(true);
						} else {
							window.location.assign(data.target);
						}  
					} else {
						error_msg.innerHTML = data.login_error;
						error_msg.style.display = "block";
						 
						dojo.byId("login_form_submit").style.display = "";
						dojo.byId("login_please_wait").style.display = "none";  
					}
					
					return data; //always return the response back 
				},
				// if any error occurs, it goes here:
				error : function(response, ioArgs) { 
		            console.log("failed xhrGet", response, ioArgs); 
		            
		            alert("ERROR: There was an error while submitting your request. Please try again!");
		            
		            dojo.byId("login_form_submit").style.display = "";
					dojo.byId("overlay_please_wait").style.display = "none";
					
		            /* handle the error... */ 
		            return response; //always return the response back 
		        }
			});
		} else {
			error_msg.style.display = "block";
		} 
	},
	
	forgot: function(evt) {
		evt.preventDefault(); 
		
		// forgot form fields.
		var form = dojo.byId('forgot_form');
		var email_field = dojo.byId('forgot_email'); 
		var error_msg = dojo.byId('forgot_form_error_msg');

		var errors = 0; 
		var email_filter  = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
		
		// validate email.
		if (email_field.value.length == 0) {
			error_msg.innerHTML = "Please enter the email you signed up with."; 
			errors++;
		} else if(!email_filter.test(email_field.value)) {
			error_msg.innerHTML = "Please enter a valid email address.";
			errors++;
		} 
		
		// validate form.
		if(errors == 0){ 
			error_msg.style.display = "none";
			error_msg.innerHTML = "";
			
			dojo.xhrPost({
				url: form.action+'/format/json', 
				form: "forgot_form",  
				handleAs: "json",
//				sync: true,
				headers: {"X-Requested-With": "XMLHttpRequest"},
				load: function(data,ioargs){  
					if(data.result == '1'){ 
						dojo.byId('forgot_email').value = "";
						dojo.byId("forgot_form_success_msg").innerHTML = "Ok. We sent you an Email with a link to reset your password.";
						dojo.byId("forgot_form_field").style.display = "none";
						dojo.byId("forgot_form_success_container").style.display = "block";
					} else {
						error_msg.innerHTML = data.forgot_error;
						error_msg.style.display = "block";
					}
					
					return data; //always return the response back 
				},
				// if any error occurs, it goes here:
				error : function(response, ioArgs) { 
		            console.log("failed xhrGet", response, ioArgs); 
		            
		            alert("ERROR: There was an error while submitting your request. Please try again!");
		            
		            /* handle the error... */ 
		            return response; //always return the response back 
		        }
			});
		} else {
			error_msg.style.display = "block";
		} 
	},
	
	// show overlay form to sign up.
	showSignup: function(evt) {
		evt.preventDefault();
		
		var href = evt.currentTarget.href;
		
		// only send an ajax request if nothing is running.
		if (Z2h.user._running === false) {
			Z2h.user._running = true;
			
			dojo.xhrGet({ 
			 	url: href+"/format/text",  //the relative URL  
			 	handleAs: "text",
//			 	sync: true,
			 	// run this function if the request is successful 
		        load : function(response, ioArgs) { 
			 		// close already opend signup form.
			 		var opened_signup_form = dijit.byId('signup_form_overlay');
						
			 		if (opened_signup_form) {
			 			opened_signup_form.hide(); 
			 			opened_signup_form.destroy();
			 		} 
			 		
			 		// initialize dialog.
					var signup_form = new dijit.Dialog({id: "signup_form_overlay"}); 
					dojo.style(signup_form.titleBar, "display", "none");  
					
					signup_form.attr('content', response); 
					signup_form.show();
					 
					// hide parent email field as default.
					var parentEmail = dojo.byId('parent_email'); 
				    if (parentEmail) {  
				    	parentEmail.style.display = "none";
				    }
				    
					// close over flag form. 
					dojo.query(".overlay_signup_close").forEach(function(node, i){  
						//node.style.display = "block";
						var closeHandle = dojo.connect(node, 
													   "onclick",
													   dojo.hitch(signup_form, 
													     		  function(e){ 
													    				e.preventDefault();
													    				signup_form.attr('content', ''); 
													    				signup_form.hide(); 
													    				signup_form.destroy(); 
													     				dojo.disconnect(closeHandle); 
													     		   })); 
					}); 
					
					// overwrite the default esc key event.
					var escHandle = dojo.connect(signup_form.domNode, "onkeypress", function(e){
								        var key = e.keyCode || e.charCode;
								        var k = dojo.keys;
					
								        if (key == k.ESCAPE) {
								        	e.preventDefault();
								        	signup_form.attr('content', ''); 
						    				signup_form.hide(); 
						    				signup_form.destroy(); 
						     				dojo.disconnect(escHandle); 
								        }
					});
					
					// create a submit button to send the flag form.
				    var submitButton = dojo.byId('signup_submit'); 
				    if (submitButton) {  
				    	dojo.connect(submitButton, 
						    		"onclick",
						    		function(e){ 
										e.preventDefault();   
										Z2h.user.signup();
				    	}); 
				    } 
				    
				    var signup_post_form = dojo.byId('signup_form'); 
				    if (signup_post_form) {  
				    	dojo.connect(signup_post_form, 
						    		"onsubmit",
						    		function(e){ 
										e.preventDefault();
										Z2h.user.signup();
				    	}); 
				    } 
				    
				    // hook onclick event to select an avatar from predefined set.
				    dojo.query("a.avatar_link").forEach(function(link) {
						dojo.connect(link, "onclick", Z2h.link.selectAvatar);
					});
				    
				    // hook events with birthday select list.
				    var signup_birth_y = dojo.byId('signup_birth_y'); 
				    var signup_birth_m = dojo.byId('signup_birth_m'); 
				    var signup_birth_d = dojo.byId('signup_birth_d'); 
				    
				    if (signup_birth_y && signup_birth_m && signup_birth_d) { 
				    	dojo.connect(signup_birth_m, 
						    		"onchange",
						    		 function(e){ 
				    					Z2h.user.calenderDays('signup_birth_d', 'signup_birth_m', 'signup_birth_y');
				    	}); 
				    	
				    	dojo.connect(signup_birth_y, 
						    		"onchange",
						    		 function(e){  
										Z2h.user.calenderDays('signup_birth_d', 'signup_birth_m', 'signup_birth_y');
				    	});  
				    }  
			  
		            return response; //always return the response back 
		        }, 
		        // run this function if the request is not successful 
		        error : function(response, ioArgs) { 
		            console.log("failed xhrGet", response, ioArgs); 
		            
		            alert("ERROR: There was an error while submitting your request. Please try again!");
		            
		            /* handle the error... */ 
		            return response; //always return the response back 
		        }
			});
			
			Z2h.user._running = false;
		} 
	}, 
	
	// send signup form.
	signup: function() { 
		// only send an ajax request if nothing is running.
		if (Z2h.user._running === false) {
			Z2h.user._running = true; 
			
			var form = dojo.byId('signup_form');
			
			if (form) { 
				var signup_errors = dojo.byId('signup_errors');
				var parentEmail = dojo.byId('parent_email'); 
			    
				// show/hide parent email form field.
				var birth_m = dojo.byId('signup_birth_m').value;
				var birth_d = dojo.byId('signup_birth_d').value;
				var birth_y = dojo.byId('signup_birth_y').value; 
				
				if(parentEmail && birth_m != '00' && birth_d != '00' && birth_y != '0000'){ 
					// get an age.
					var current_age = Z2h.user.getAge(parseInt(birth_y), parseInt(birth_m), parseInt(birth_d));  
					
					if (current_age <= 13) {
						parentEmail.style.display = ""; 
					} else {
						parentEmail.style.display = "none";
					}
				}
				
				var status_active = dojo.byId("overlay_signup_form");
				var btn_active = dojo.byId("overlay_signup_position");
				var overlay_wait = dojo.byId("signup_please_wait"); 
				 
				if (status_active && btn_active && overlay_wait) {
					status_active.style.display = "none";
					btn_active.style.display = "none";
					overlay_wait.style.display = ""; 
				}
				
				dojo.xhrPost({
					url: form.action+'/format/json', 
					form: "signup_form",  
					handleAs: "json",
//					sync: true,
					headers: {"X-Requested-With": "XMLHttpRequest"},
					load: function(data,ioargs){  
						if(data.result == '1'){ 
							window.location.assign(data.redirect);   
						} else { 
							status_active.style.display = "";
							btn_active.style.display = "";
							overlay_wait.style.display = "none";  
							
							if (signup_errors) {
								signup_errors.innerHTML = "";
								 
								for(var k in data.errors){  
									signup_errors.innerHTML += data.errors[k][0]+"<br />";  
								}  
								
								signup_errors.style.display = "block";
							} 
						}
						
						return data; //always return the response back 
					},
					// if any error occurs, it goes here:
					error : function(response, ioArgs) { 
			            console.log("failed xhrGet", response, ioArgs); 
			            
			            alert("ERROR: There was an error while submitting your request. Please try again!");
			            
			            /* handle the error... */ 
			            return response; //always return the response back 
			        }
				});  
			} 
			
			Z2h.user._running = false; 
		}
	},
	
	// update number of days based on selected year and month.
	calenderDays: function(day_select_id, month_select_id, year_select_id) { 
		var month = parseInt(dojo.byId(month_select_id).value); 
		var year = parseInt(dojo.byId(year_select_id).value);
		var day = parseInt(dojo.byId(day_select_id).value);
		var day_options = dojo.byId(day_select_id);
		 
		var thirtyone_days = ["01", "03", "05", "07", "08", "10", "12"]; 
		var thirty_days = ["04", "06", "09", "11"];
		var found;
		
		// check the selected month has 31 days.
		found = dojo.indexOf(thirtyone_days, month); 
		if (found == -1) {
			// check the selected month has 30 days.
			found = dojo.indexOf(thirty_days, month); 
				
			if (found == -1) { 
				// a year will be a leap year if it is divisible by 4 but not by 100. 
				// if a year is divisible by 4 and by 100, it is not a leap year unless it is also divisible by 400. 
				if (year > 0) {
					if ((year%4 == 0 && year%100 != 0) || (year%4 == 0 && year%100 == 0 && year%400 == 0)) {
						// a leap year has 29 days in February.
						dojo.removeAttr(day_options.options[29], "disabled");
						dojo.attr(day_options.options[30], "disabled", "disabled");
						dojo.attr(day_options.options[31], "disabled", "disabled");
						
						if (day > 29) {
							dojo.attr(day_options.options[29], "selected", "selected"); 
							day_options.selectedIndex = 29; 
						}
					} else {
						// set it to 28 days for February.
						dojo.attr(day_options.options[29], "disabled", "disabled");
						dojo.attr(day_options.options[30], "disabled", "disabled");
						dojo.attr(day_options.options[31], "disabled", "disabled");
						
						if (day > 28) {
							dojo.attr(day_options.options[28], "selected", "selected"); 
							day_options.selectedIndex = 28; 
						} 
					}
				} else {
					// set it to 28 days for February.
					dojo.attr(day_options.options[29], "disabled", "disabled");
					dojo.attr(day_options.options[30], "disabled", "disabled");
					dojo.attr(day_options.options[31], "disabled", "disabled");
					 
					if (day > 28) {
						dojo.attr(day_options.options[28], "selected", "selected"); 
						day_options.selectedIndex = 28; 
					} 
				} 
			} else {
				// hide day 31th from the day select option.
				dojo.removeAttr(day_options.options[29], "disabled");
				dojo.removeAttr(day_options.options[30], "disabled");
				dojo.attr(day_options.options[31], "disabled", "disabled");
				
				if (day > 30) {
					dojo.attr(day_options.options[30], "selected", "selected"); 
					day_options.selectedIndex = 30; 
				}
			}
		} else {
			// remove all disabled from options.
			dojo.removeAttr(day_options.options[29], "disabled");
			dojo.removeAttr(day_options.options[30], "disabled");
			dojo.removeAttr(day_options.options[31], "disabled");
		} 
	},
	
	// calculate age.
	getAge: function(birth_y, birth_m, birth_d) { 
		var d = new Date();
		var current_year = d.getFullYear();
		var current_month = d.getMonth();
		var current_day = d.getDay(); 
		 
		var year_diff  = current_year - birth_y;
		var month_diff = current_month - birth_m;
		var day_diff   = current_day - birth_d;
		 
		if (month_diff < 0) {
		 	year_diff--;
		} else if ((month_diff==0) && (day_diff < 0)) {
		 	year_diff--;
		} 
		
		return year_diff;
	}
}

//---------------------- COMMUNITY TWITT JS --------------------------------
Z2h.twitt = {
	_running: false, 
		
	init: function() {
		dojo.behavior.add({
			".twitt_ajax": {
				onclick: function(e){
					e.preventDefault(); 
					var href = dojo.attr(e.currentTarget, "href"); 			
					Z2h.twitt.load(href, 1);
				}
			},
			
			".twitt_replies": {
				onclick: function(e){
					e.preventDefault();   			
					Z2h.twitt.showReplies(e, 0);
				}
			}, 
			
			".twitt_replies_add": {
				onclick: function(e){
					e.preventDefault();   			
					Z2h.twitt.showReplies(e, 1);
				}
			},
			
			"#twitt_btn": {
				onclick: function(e){
					e.preventDefault();
					Z2h.twitt.addComment(e);
				}
			},
		
			"#twitt_form": {
				onsubmit: function(e){
					e.preventDefault();
					Z2h.twitt.addComment(e);
				}
			},
			
			".twitt_reply_btn": {
				onclick: function(e){
					e.preventDefault();
					Z2h.twitt.addReply(e);
				}
			} 
		}); 
	},

	showReplies: function(evt, anchor) { 
		evt.preventDefault();
		 
		var href = evt.currentTarget.href;
		var update_dom_id = dojo.attr(evt.currentTarget, "alt");
		var clicked = evt.currentTarget;
		
		var update_dom = dojo.byId(update_dom_id);
		
		// only send an ajax request if nothing is running and the dom exists 
		if (update_dom && Z2h.twitt._running === false) {
			Z2h.twitt._running = true; 
			
			var overlay_wait = dojo.byId(update_dom_id + "_loading");
			
			if (overlay_wait) { 
				overlay_wait.style.display = "";
				update_dom.style.display = "none";
			}
			
			// if not, call a ajax request
			dojo.xhrGet({ 
				 	url: href + "/format/text", 
				 	handleAs: "text",
				 	sync: true,
				 	// run this function if the request is successful
			        load : function(response, ioArgs) { 
						// set some element's content
						update_dom.innerHTML= response;  
						
						if (anchor == 1) {
							var ele = dojo.byId("reply_bottom_"+update_dom_id);
							//var from_win = dojo.byId("reply_top_"+update_dom_id);
							 
							var anim0 = dojox.fx.smoothScroll({ node: ele, win: window, duration:1000, easing:dojox.fx.easing.easeOut });
							anim0.play(); 
							
							 //dojox.fx.smoothScroll({node:ele,win:window,duration:400}).play();
							//    dojox.fx.highlight({node:ele,duration:800}).play();
							//var r = dojo.window.scrollIntoView(ele);
				//			var foo=dijit.scrollIntoView(ele); 

						}
						
						Z2h.twitt.initEditor();  
 
			            return response; //always return the response back 
			        }, 
			        // run this function if the request is not successful 
			        error : function(response, ioArgs) { 
			            console.log("failed xhrGet", response, ioArgs); 
			            
			            alert("ERROR: There was an error while submitting your request. Please try again!");
			            
			            /* handle the error... */ 
			            return response; //always return the response back 
			        }
			}); 
			 
			if (overlay_wait) { 
				overlay_wait.style.display = "none"; 
				update_dom.style.display = ""
			}
			
			Z2h.twitt._running = false; 
		} 
	},
	
	initEditor: function() { 
		dojo.query(".twitt_reply_textbox").forEach(function(textarea) {  	
			if (textarea.value.length == 0) {
				dojo.style(textarea, "height", "22px"); 
			} 
			 
			dojo.connect(textarea, "onfocus", Z2h.twitt.expand);
			dojo.connect(textarea, "onblur", Z2h.twitt.shrink);
		}); 
		
		dojo.query(".text_length_aid").forEach(function(aid) {  
			 var id = aid.id;
			 var textarea_dom = dojo.byId(id + "_textarea");
			   
			 var length = 1000;
			 
			 if (dojo.hasAttr(aid, "title")) {
				 length = dojo.attr(aid, "title");
			 } 
			 
			 if (textarea_dom) { 
				 Z2h.string.countTextarea(textarea_dom, id, length);
				 
				 dojo.connect(textarea_dom, "onkeyup", function() {   
					 Z2h.string.countTextarea(textarea_dom, id, length);
		    	 });  
			 } 
		}); 
		 
		dojo.behavior.apply();
	},
	
	expand: function(evt) { 
		if (evt.currentTarget.value.length == 0) {
			dojo.animateProperty({ 
				node : evt.currentTarget, 
			    duration : 350, 
			    properties : { 
			    	height : {start: '22', end: '150'} 
			    } 
			}).play();
		} 
	},
	
	shrink: function(evt) {  
		if (evt.currentTarget.value.length == 0) {
			dojo.animateProperty({ 
				node : evt.currentTarget, 
			    duration : 350, 
			    properties : { 
			    	height : {start: '150', end: '22'} 
			    } 
			}).play(); 
		} 
	},
	
	addReply: function(evt) { 
		evt.preventDefault();
	
		var update_dom_id = dojo.attr(evt.currentTarget, "name");
		var update_dom = dojo.byId(update_dom_id);
		var reply_form = dojo.byId("reply_form_" + update_dom_id);
		var hidden_url = dojo.byId(update_dom_id + "_after_url");
		
		var a_count = dojo.byId(update_dom_id + "_a_count");
		
		var button_id = evt.target.id;
		var reply_textarea_id = button_id.replace("submit", "textarea"); 
		
		var reply_p_id = button_id.replace("_submit", ""); 
		var error_id = button_id.replace("submit", "error"); 
		var reply_text = dojo.byId(reply_textarea_id);
		var reply_errors = dojo.byId(error_id);
		var reply_txt_aid = dojo.byId(reply_p_id);
		
		// only send an ajax request if nothing is running and the dom exists
		if (reply_form && reply_text && Z2h.twitt._running === false) {
			var body = Z2h.string.trimAll(reply_text.value); 
			 
			if (body.length > 0) {
				Z2h.twitt._running = true;   
				
				var overlay_wait = dojo.byId(update_dom_id + "_loading");
				var form_section = dojo.byId(update_dom_id);
				
				if (overlay_wait && form_section) { 
					form_section.style.display = "none"; 
					overlay_wait.style.display = ""; 
				}
				
				if (reply_errors) {
					reply_errors.innerHTML = "";
				}
				
				dojo.xhrPost({
					url: reply_form.action + "/format/json",
					form: reply_form.id,
					handleAs: "json",
//					sync: true,
					headers: {"X-Requested-With": "XMLHttpRequest"},
					load: function(data,ioargs){  
						if (data.result == "-1") { 
							// reload the page
							window.location.reload(true);
						} else if(data.result == "1") { 
							if (hidden_url && update_dom) {
								// load the updated comment list.  
								dojo.xhrGet({ 
								 	url: hidden_url.value + "/offset/0/format/text", 
								 	handleAs: "text",
//								 	sync: true,
								 	// run this function if the request is successful
							        load : function(response, ioArgs) { 
										// set some element's content
										update_dom.innerHTML= response;  
										
										Z2h.twitt.initEditor();
										
										// update the reply count.
										var p_count = dojo.byId(update_dom_id + "_p_count");
										var a_count = dojo.byId(update_dom_id + "_a_count");
										 
										if (p_count) {
											var current_count = dojo.attr(p_count, "name");
											p_count.style.display = "none";
										} else if (a_count) {
											var current_count = dojo.attr(a_count, "name"); 
										}
										
										var new_count = parseInt(current_count) + 1;
										
										if (a_count) {
											if (new_count == 1) {
												a_count.innerHTML = "1 Reply";
											} else {
												a_count.innerHTML = new_count + " Replies";
											}
											
											dojo.attr(a_count, "name", new_count);
											a_count.style.display = "";
										}
										 
										if (p_count) {
											dojo.attr(p_count, "name", new_count);
										}
										
										if (overlay_wait && form_section) { 
											overlay_wait.style.display = "none";  
											form_section.style.display = ""; 
										}
										  
							            return response; //always return the response back 
							        }, 
							        // run this function if the request is not successful 
							        error : function(response, ioArgs) { 
							            console.log("failed xhrGet", response, ioArgs); 
							            
							            alert("ERROR: There was an error while submitting your request. Please try again!");
							            
							            /* handle the error... */ 
							            return response; //always return the response back 
							        }
								});  
							} 
							
						} else { 
							if (overlay_wait && form_section) { 
								overlay_wait.style.display = "none";  
								form_section.style.display = ""; 
							}
							
							if (reply_errors) {
								reply_errors.innerHTML = "";
									
								for(var k in data.errors){ 
									reply_errors.innerHTML = data.errors[k][0]+" "; 
								}
							} 
							 
							dojo.attr(reply_text, "style", "height:150px;"); 
						} 
							
						return data; //always return the response back 
					},
					// if any error occurs, it goes here:
					error: function(response, ioArgs){
						console.log("failed xhrPost", response, ioArgs);
							 
						alert("ERROR: There was an error while submitting your reply form. Please try again!");
						/* handle the error... */ 
				        return response; //always return the response back 
					}
				});
				
				Z2h.twitt._running = false;
			} else {
				reply_text.value = "";
 
			    if (reply_txt_aid) {
			    	reply_txt_aid.innerHTML = "150 characters remaining";
			    }

                if (reply_errors) {
                 	reply_errors.innerHTML = "Your message is required.";        			 			 
				} 
			}
		}
	},
	
	addComment: function(evt) { 
		evt.preventDefault();
	 
		var comment_form = dojo.byId("twitt_form");
		var overlay_wait = dojo.byId("preview_twitt");  			
		var twitt_textarea = dojo.byId("twitt_description_textarea");
		var comment_errors = dojo.byId("twitt_error");
			
		// only send an ajax request if nothing is running and the dom exists. 
		if (comment_form && Z2h.twitt._running === false) {
			
			var body = Z2h.string.trimAll(twitt_textarea.value); 
 
			if (twitt_textarea && body.length > 0) { 				
				if (overlay_wait) { 
					comment_form.style.display = "none"; 
					overlay_wait.style.display = ""; 
				}
		
				if (comment_errors) {
					comment_errors.innerHTML = "";
				}
			
				Z2h.twitt._running = true;   
				
				dojo.xhrPost({
				url: comment_form.action+"/format/json",
				form: comment_form.id,
				handleAs: "json",
//				sync: true,
				headers: {"X-Requested-With": "XMLHttpRequest"},
				load: function(data,ioargs){  
					if(data.result == "1"){ 
					 	// reload the comments.
						Z2h.twitt.refresh();
					}else{ 	
						if (comment_errors) {
							comment_errors.innerHTML = "";
								
							for(var k in data.errors){ 
								var errorItem = document.createElement('p');
								errorItem.innerHTML = data.errors[k][0];
								comment_errors.appendChild(errorItem); 
							}
						} 
					} 
                                             
                                              if (overlay_wait) { 
						overlay_wait.style.display = "none";  
						comment_form.style.display = ""; 
					}
							
					return data; //always return the response back 
				},
				// if any error occurs, it goes here:
				error: function(response, ioArgs){
					console.log("failed xhrPost", response, ioArgs);
						 
					alert("ERROR: There was an error while submitting your comment form. Please try again!");
					/* handle the error... */ 
			        return response; //always return the response back 
				}
			});

			Z2h.twitt._running = false;
	 
			} else {
			       twitt_textarea.value = "";

                               var twitt_description = dojo.byId("twitt_description");
			       if (twitt_description) {
					twitt_description.innerHTML = "150 characters remaining";
			       }
 
                               if (comment_errors) {
					comment_errors.innerHTML = ""; 
                                        var errorItem = document.createElement('p');
					errorItem.innerHTML = "Your message is required.";
					comment_errors.appendChild(errorItem); 							 			 
				} 
			}
 
		} 
	},
	 
    // called after a new comment is added successfully
	refresh: function() {   
		// hook events again. 
		dojo.behavior.apply();

		var twitt_textarea = dojo.byId("twitt_description_textarea");
		if (twitt_textarea) {
			twitt_textarea.value = "";
		}

		var twitt_description = dojo.byId("twitt_description");
		if (twitt_description) {
			twitt_description.innerHTML = "150 characters remaining";
		}
 
        Z2h.twitt.load("/community/twitt/get-twitts");        
	},

    // called after a new comment is added successfully
	load: function(href, loading) {  
		// update dom id. (make sure there is div id=load_ajax_content_here)
		var update_dom = dojo.byId("twitt_list"); 
        var overlay_wait = dojo.byId("loading_more_twitts");
		 
		// only send an ajax request if nothing is running and the dom exists
		if (update_dom) {  
			if (loading == 1) { 
				update_dom.style.display = "none"; 
				overlay_wait.style.display = ""; 
			}
 
            // reload the comment list 
			dojo.xhrGet({ 
				url: href+"/format/text/",
				handleAs: "text",
    		 	sync: true,
			 	// run this function if the request is successful
		        load : function(response, ioArgs) { 
		            // set some element's content
					update_dom.innerHTML = response;  
				 
					if (loading == 1) { 
						update_dom.style.display = ""; 
						overlay_wait.style.display = "none"; 
			        }
			      
					// hook events again. 
					dojo.behavior.apply();

					// initialize flag link.
					dojo.query('a.flag').forEach(function(link) {
						var flagHandle = dojo.connect(link, 'onclick', function(e){  
					        Z2h.link.flagDialog(e, flagHandle); // need to pass flag handle to disconnect after flagging item.
					    }); 
					}); 
					
		            return response; //always return the response back 
		        }, 
		        // run this function if the request is not successful
		        error : function(response, ioArgs) { 
		            console.log("failed xhrGet", response, ioArgs); 
		            
		            alert("ERROR: There was an error while submitting your request. Please try again!");
		            /* handle the error... */ 
		            return response; //always return the response back 
		        } 
			}); 
		}
	} 
}

//---------------------- USER PROFILE MODULE JS --------------------------------

Z2h.user.profile = {
	_running: false, 
	
	init: function() {   
		dojo.behavior.add({
			".filter_my_events": {
				onclick: function(e){
					e.preventDefault();
					Z2h.user.profile.filterEvents(e);
				}
			},
			
			".filter_my_friends": {
				onclick: function(e){
					e.preventDefault();
					Z2h.user.profile.filterFriends(e);
				}
			},
		
			"#my_about_me": {
				onclick: function(e){
					e.preventDefault();
					Z2h.user.profile.viewAboutMe();
				}
			},
			
			"#my_edit_profile": {
				onclick: function(e){
					e.preventDefault();
					Z2h.user.profile.loadEditMyProfile();
				}
			},
			
			"#about_me_btn": {
				onclick: function(e){
					e.preventDefault();
					Z2h.user.profile.updateMyProfile();
				}
			},
			
			"#about_me_form": {
				onsubmit: function(e){
					e.preventDefault();
					Z2h.user.profile.updateMyProfile();
				}
			}
		}); 
		
		// initialize status.
		Z2h.user.profile.initStatus();
		
		// initialize add profile form.
		Z2h.user.profile.initAddProfile(); 
	},
	
	filterEvents: function(evt) {
		// only send an ajax request if nothing is running.
		if (Z2h.user.profile._running === false) {
			Z2h.user.profile._running = true;
			 
			var status_active = dojo.byId("swith_events");
			var overlay_wait = dojo.byId("preview_events");
			
			if (status_active && overlay_wait) {
				status_active.style.display = "none";
				overlay_wait.style.display = ""; 
			}
			 
			var event_filter = dojo.attr(evt.currentTarget, "title");
			var href = dojo.attr(evt.currentTarget, "href");
			
			dojo.xhrGet({ 
			 	url: href+"/format/text",  //the relative URL  
			 	handleAs: "text",
//			 	sync: true,
			 	// run this function if the request is successful 
		        load : function(response, ioArgs) { 
					status_active.innerHTML= response;
			 			
			 		status_active.style.display = "";
					overlay_wait.style.display = "none"; 
					
				    dojo.query('ul#events_list_sort > li.forum_list_sort_selected').forEach( function(link){
						dojo.removeClass(link,'forum_list_sort_selected');
					});
					  
					var new_tab = dojo.byId(event_filter+"_events_tab"); 
					if (new_tab) {
						dojo.addClass(new_tab, "forum_list_sort_selected");  
					}
						
					// hook events again. 
					dojo.behavior.apply(); 
			 		   
		            return response; //always return the response back 
		        },
				// if any error occurs, it goes here:
				error : function(response, ioArgs) { 
		            console.log("failed xhrGet", response, ioArgs); 
		            
		            alert("ERROR: There was an error while submitting your request. Please try again!");
		            
		            /* handle the error... */ 
		            return response; //always return the response back 
		        }
			});
			
			Z2h.user.profile._running = false;
		} 
		
	},
	
	filterFriends: function(evt) {
		// only send an ajax request if nothing is running.
		if (Z2h.user.profile._running === false) {
			Z2h.user.profile._running = true;
			 
			var status_active = dojo.byId("swith_friends");
			var overlay_wait = dojo.byId("preview_friends");
		 
			if (status_active && overlay_wait) {
				status_active.style.display = "none";
				overlay_wait.style.display = ""; 
			}
			 
			var friend_filter = dojo.attr(evt.currentTarget, "title");
			var href = dojo.attr(evt.currentTarget, "href");
			
			dojo.xhrGet({ 
			 	url: href+"/format/text",  //the relative URL  
			 	handleAs: "text",
//			 	sync: true,
			 	// run this function if the request is successful 
		        load : function(response, ioArgs) { 
					status_active.innerHTML= response;
			 			
			 		status_active.style.display = "";
					overlay_wait.style.display = "none"; 
					
				    dojo.query('ul#friends_list_sort > li.forum_list_sort_selected').forEach( function(link){
						dojo.removeClass(link,'forum_list_sort_selected');
					});
					  
					var new_tab = dojo.byId(friend_filter+"_friends_tab"); 
					if (new_tab) {
						dojo.addClass(new_tab, "forum_list_sort_selected");  
					}
						
					// hook events again. 
					dojo.behavior.apply(); 
			 		   
		            return response; //always return the response back 
		        },
				// if any error occurs, it goes here:
				error : function(response, ioArgs) { 
		            console.log("failed xhrGet", response, ioArgs); 
		            
		            alert("ERROR: There was an error while submitting your request. Please try again!");
		            
		            /* handle the error... */ 
		            return response; //always return the response back 
		        }
			});
			
			Z2h.user.profile._running = false;
		} 
		
	},
	
	viewAboutMe: function() { 
		// only send an ajax request if nothing is running.
		if (Z2h.user.profile._running === false) {
			Z2h.user.profile._running = true;
			 
			var status_active = dojo.byId("swith_my");
			var overlay_wait = dojo.byId("preview_my");
			
			if (status_active && overlay_wait) {
				status_active.style.display = "none";
				overlay_wait.style.display = ""; 
			}
			 
			dojo.xhrGet({ 
			 	url: "/user/profile/about-me/format/text",  //the relative URL  
			 	handleAs: "text",
//			 	sync: true,
			 	// run this function if the request is successful 
		        load : function(response, ioArgs) { 
					if (response == 'logged_out') { 
			 			window.location.assign('/login-required');
			 		} else {
			 			status_active.innerHTML= response;
			 			
			 			status_active.style.display = "";
						overlay_wait.style.display = "none"; 
						
						var about_me_tab = dojo.byId("about_me_tab");
						var edit_profile_tab = dojo.byId("edit_profile_tab");
						
						if (about_me_tab && edit_profile_tab) {
							dojo.removeClass(edit_profile_tab, "forum_list_sort_selected");
							dojo.addClass(about_me_tab, "forum_list_sort_selected"); 
						}
						
						// hook events again. 
						dojo.behavior.apply(); 
			 		} 
					 
		            return response; //always return the response back 
		        },
				// if any error occurs, it goes here:
				error : function(response, ioArgs) { 
		            console.log("failed xhrGet", response, ioArgs); 
		            
		            alert("ERROR: There was an error while submitting your request. Please try again!");
		            
		            /* handle the error... */ 
		            return response; //always return the response back 
		        }
			});
			
			Z2h.user.profile._running = false;
		} 
	},
	
	loadEditMyProfile: function() {
		// only send an ajax request if nothing is running.
		if (Z2h.user.profile._running === false) {
			Z2h.user.profile._running = true;
			 
			var status_active = dojo.byId("swith_my");
			var overlay_wait = dojo.byId("preview_my");
			
			if (status_active && overlay_wait) {
				status_active.style.display = "none";
				overlay_wait.style.display = ""; 
			}
			 
			dojo.xhrGet({ 
			 	url: "/user/profile/edit-profile/format/text",  //the relative URL  
			 	handleAs: "text",
//			 	sync: true,
			 	// run this function if the request is successful 
		        load : function(response, ioArgs) { 
					if (response == 'logged_out') { 
			 			window.location.assign('/login-required');
			 		} else {
			 			status_active.innerHTML= response;
			 			
			 			status_active.style.display = "";
						overlay_wait.style.display = "none"; 
						
						var about_me_tab = dojo.byId("about_me_tab");
						var edit_profile_tab = dojo.byId("edit_profile_tab");
						
						if (about_me_tab && edit_profile_tab) {
							dojo.removeClass(about_me_tab, "forum_list_sort_selected");
							dojo.addClass(edit_profile_tab, "forum_list_sort_selected"); 
						}
						
						// hook events again. 
						dojo.behavior.apply(); 
			 		} 
					 
		            return response; //always return the response back 
		        },
				// if any error occurs, it goes here:
				error : function(response, ioArgs) { 
		            console.log("failed xhrGet", response, ioArgs); 
		            
		            alert("ERROR: There was an error while submitting your request. Please try again!");
		            
		            /* handle the error... */ 
		            return response; //always return the response back 
		        }
			});
			
			Z2h.user.profile._running = false;
		} 
	},
	
	updateMyProfile: function() {
		// only send an ajax request if nothing is running.
		if (Z2h.user.profile._running === false) {
			Z2h.user.profile._running = true;
			
			var form = dojo.byId('about_me_form');
			
			if (form) {
				dojo.xhrPost({
					url: form.action+'/format/json', 
					form: "about_me_form",  
					handleAs: "json",
//					sync: true,
					headers: {"X-Requested-With": "XMLHttpRequest"},
					load: function(data,ioargs){  
						if(data.result == '1'){ 
							Z2h.user.profile._running = false;
							 
							Z2h.user.profile.viewAboutMe();
							
							dojo.behavior.apply();
						} else { 
							var title_info_error = dojo.byId('profile_error');
							 
							if (title_info_error) {
								title_info_error.innerHTML = "";
								
								for(var k in data.errors){ 
									if(k == 'logged_out'){
										window.location.assign(data.errors[k]);
									} else {
										title_info_error.innerHTML += data.errors[k]+"<br />"; 
									} 
								}  
								
								title_info_error.style.display = "block";
							} 
						}
						
						return data; //always return the response back 
					},
					// if any error occurs, it goes here:
					error : function(response, ioArgs) { 
			            console.log("failed xhrGet", response, ioArgs); 
			            
			            alert("ERROR: There was an error while submitting your request. Please try again!");
			            
			            /* handle the error... */ 
			            return response; //always return the response back 
			        }
				});  
			} 
			
			Z2h.user.profile._running = false;
		} 
		
	},
	
	// initialize status
	initStatus: function() {
		// hook onclick event to show edit status form.
		var edit_status_link = dojo.byId('edit_status_link');
		if (edit_status_link) {  
			dojo.connect(edit_status_link, 'onclick', function(evt) {
				evt.preventDefault();  
				Z2h.user.profile.loadStatus(evt.currentTarget.href);
			});
		}  
		
		// hook text character length aid. (max 255 characters are allowed)
	    var status_info = dojo.byId('edit_status_info'); 
	    if (status_info) {  
	    	dojo.connect(status_info, 
		    		    "onkeyup",
		    		    function(){  
							var numChars = dojo.number.parse(status_info.value.length);
							var currentValue = parseInt(255) - numChars; 
				
							if (currentValue < 0) {  
						    	status_info.value = status_info.value.slice(0, 255);
						    }  
		    }); 
	    }
	    
		// hook onclick event to cancel status form.
		var edit_status_cancel = dojo.byId('edit_status_cancel');  
		if (edit_status_cancel) {  
			dojo.connect(edit_status_cancel, 'onclick', function(evt) {
				evt.preventDefault();  
				Z2h.user.profile.loadStatus(evt.currentTarget.href);
			});
		}  
		
		// hook onclick event to submit status form.
		var edit_status_submit = dojo.byId('edit_status_submit');  
		if (edit_status_submit) { 
			dojo.connect(edit_status_submit, 'onclick', Z2h.user.profile.updateStatus); 
		} 
	},
	
	// show edit status form or refresh status info.
	updateStatus: function(evt) {
		evt.preventDefault(); 
		 
		// only send an ajax request if nothing is running.
		if (Z2h.user.profile._running === false) {
			Z2h.user.profile._running = true;
			
			var form = dojo.byId('user_status_update');
			
			if (form) {
				dojo.xhrPost({
					url: form.action+'/format/json', 
					form: "user_status_update",  
					handleAs: "json",
//					sync: true,
					headers: {"X-Requested-With": "XMLHttpRequest"},
					load: function(data,ioargs){  
						if(data.result == '1'){ 
							Z2h.user.profile._running = false;
							
							// refresh status info.
							var edit_status_cancel = dojo.byId('edit_status_cancel');  
							if (edit_status_cancel) { 
								Z2h.user.profile.loadStatus(edit_status_cancel.href);
							} 
						} else { 
							var status_info_error = dojo.byId('status_info_error');
							 
							if (status_info_error) {
								status_info_error.innerHTML = "";
								
								for(var k in data.errors){ 
									if(k == 'logged_out'){
										window.location.assign(data.errors[k]);
									} else {
										status_info_error.innerHTML += data.errors[k]+"<br />"; 
									} 
								}  
								
								status_info_error.style.display = "block";
							} 
						}
						
						return data; //always return the response back 
					},
					// if any error occurs, it goes here:
					error : function(response, ioArgs) { 
			            console.log("failed xhrGet", response, ioArgs); 
			            
			            alert("ERROR: There was an error while submitting your request. Please try again!");
			            
			            /* handle the error... */ 
			            return response; //always return the response back 
			        }
				});  
			} 
			
			Z2h.user.profile._running = false;
		} 
	},
	
	// load status info or status update form.
	loadStatus: function(href) {  
		// only send an ajax request if nothing is running.
		if (Z2h.user.profile._running === false) {
			Z2h.user.profile._running = true;
			 
			var status_active = dojo.byId("status_active");
			var overlay_wait = dojo.byId("overlay_please_wait");
			
			if (status_active && overlay_wait) {
				status_active.style.display = "none";
				overlay_wait.style.display = ""; 
			}
			 
			dojo.xhrGet({ 
			 	url: href+"/format/text",  //the relative URL  
			 	handleAs: "text",
//			 	sync: true,
			 	// run this function if the request is successful 
		        load : function(response, ioArgs) { 
					if (response == 'logged_out') { 
			 			window.location.assign('/login-required');
			 		} else {
			 			// set some element's content... 
						var update_dom = dojo.byId("user_status_info");
						
						if (update_dom) {
							update_dom.innerHTML= response; 
							
							// hook events again. 
							Z2h.user.profile.initStatus();
						}
			 		} 
					 
		            return response; //always return the response back 
		        },
				// if any error occurs, it goes here:
				error : function(response, ioArgs) { 
		            console.log("failed xhrGet", response, ioArgs); 
		            
		            alert("ERROR: There was an error while submitting your request. Please try again!");
		            
		            /* handle the error... */ 
		            return response; //always return the response back 
		        }
			});
			
			Z2h.user.profile._running = false;
		} 
	},
	
	// load each profile info or profile update form
	loadProfile: function(href, id) {  
		// only send an ajax request if nothing is running.
		if (Z2h.user.profile._running === false) {
			Z2h.user.profile._running = true;
			 
			var status_active = dojo.byId("info_active_"+id);
			var overlay_wait = dojo.byId("info_please_wait_"+id);
			
			if (status_active && overlay_wait) {
				status_active.style.display = "none";
				overlay_wait.style.display = "";
			}
			 
			dojo.xhrGet({ 
			 	url: href+"/format/text",  //the relative URL  
			 	handleAs: "text",
//			 	sync: true,
			 	// run this function if the request is successful 
		        load : function(response, ioArgs) { 
					if (response == 'logged_out') { 
			 			window.location.assign('/login-required');
			 		} else {
			 			// set some element's content... 
						var update_dom = dojo.byId("info_"+id);
						
						if (update_dom) {
							update_dom.innerHTML= response; 
							
							// hook events.
							Z2h.user.profile.initEditProfile(id);
						}
			 		} 
					 
		            return response; //always return the response back 
		        },
				// if any error occurs, it goes here:
				error : function(response, ioArgs) { 
		            console.log("failed xhrGet", response, ioArgs); 
		            
		            alert("ERROR: There was an error while submitting your request. Please try again!");
		            
		            /* handle the error... */ 
		            return response; //always return the response back 
		        }
			});
			
			Z2h.user.profile._running = false;
		} 
	},
	
	// update each profile.
	updateProfile: function(id) {
		// only send an ajax request if nothing is running.
		if (Z2h.user.profile._running === false) {
			Z2h.user.profile._running = true;
			
			var form = dojo.byId('user_profile_update_'+id);
			var status_active = dojo.byId("info_active_"+id);
			var overlay_wait = dojo.byId("info_please_wait_"+id);
			
			if (form) { 
				if (status_active && overlay_wait) {
					status_active.style.display = "none";
					overlay_wait.style.display = ""; 
				}
				 
				if (Z2h.user.profile.validateProfileForm('new_category_name_'+id, 'description_'+id)) {
					dojo.xhrPost({
						url: form.action+'/format/json', 
						form: 'user_profile_update_'+id,  
						handleAs: "json",
//						sync: true,
						headers: {"X-Requested-With": "XMLHttpRequest"},
						load: function(data,ioargs){  
							if(data.result == '1'){ 
								Z2h.user.profile._running = false;
								
								// refresh profile details.  
								var profile_link = dojo.byId('edit_profile_cancel_'+id);  
								if (profile_link) { 
									Z2h.user.profile.loadProfile(profile_link.href, id);
								}  
							} else { 
								if (status_active && overlay_wait) {
									status_active.style.display = "";
									overlay_wait.style.display = "none"; 
								}
								
								var profile_info_error = dojo.byId('profile_personal_error_'+id);
								 
								if (profile_info_error) {
									profile_info_error.innerHTML = "";
									
									for(var k in data.errors){ 
										if(k == 'logged_out'){
											window.location.assign(data.errors[k]);
										} else {
											profile_info_error.innerHTML += data.errors[k]+"<br />"; 
										} 
									}  
									
									profile_info_error.style.display = "block";
								} 
							}
							
							return data; //always return the response back 
						},
						// if any error occurs, it goes here:
						error : function(response, ioArgs) { 
				            console.log("failed xhrGet", response, ioArgs); 
				            
				            alert("ERROR: There was an error while submitting your request. Please try again!");
				            
				            /* handle the error... */ 
				            return response; //always return the response back 
				        }
					});  
				} else {
					if (status_active && overlay_wait) {
						status_active.style.display = "";
						overlay_wait.style.display = "none"; 
					}
					
					var profile_info_error = dojo.byId('profile_personal_error_'+id);
					 
					if (profile_info_error) {
						profile_info_error.innerHTML = "Topic is required.";
						profile_info_error.style.display = "block";
					} 
				}
			} 
			
			Z2h.user.profile._running = false;
		} 
	},
	
	// initialize edit profile form.
	initEditProfile: function(id) {
		if (dijit.byId("new_category_name_"+id)) {
        	dijit.byId("new_category_name_"+id).destroy(); 
        }
        
        dojo.parser.parse(dojo.byId("info_"+id));
        
		// show form by ajax.
		var edit_link = dojo.byId('edit_profile_'+id); 

		// only connect the js action if the edit link is available.
		if (edit_link) { 
			dojo.connect(edit_link,
					    "onclick",
					    function(e){ 
							e.preventDefault();  
							Z2h.user.profile.loadProfile(edit_link.href, id);
			}); 
		} 
		
		// submit form by ajax.
		var update_submit = dojo.byId('edit_profile_submit_'+id); 

		// only connect the js action if the submit button is available.
		if (update_submit) { 
			dojo.connect(update_submit,
					    "onclick",
					    function(e){ 
							e.preventDefault(); 
							Z2h.user.profile.updateProfile(id);
			}); 
		}  
	 
		// cancel form by ajax.
		var update_cancel = dojo.byId('edit_profile_cancel_'+id);  

		// only connect the js action if the cancel button is available.
		if (update_cancel) { 
			dojo.connect(update_cancel, 
					   "onclick",
					    function(e){ 
							e.preventDefault(); 
							Z2h.user.profile.loadProfile(update_cancel.href, id);
			}); 
		}
		
		// hook onclick event to show confirm dialog to delete item.
		var delete_link = dojo.byId('delete_profile_'+id);  

		if (delete_link) {
			dojo.connect(delete_link, 'onclick', Z2h.link.doPostDelete);
		} 
	},
	
	// initialize add profile form.
	initAddProfile: function() { 
		var default_topic  = "Enter a Topic you'd like to talk about!";
	    var default_profile ="Tell us about your interests or hobbies. Talk about your favorite movies, music or books. Tell us little bit about you!";
	    
	    var profile_topic = dojo.byId('profile_category');
		var profile_body = dojo.byId('description');
		 
		if (profile_topic) {
			profile_topic.value = default_topic;
			dojo.addClass(profile_topic, "profile_details_empty");
			
			dojo.connect(profile_topic, 
		    		    "onkeyup",
		    		    function(){  
							var numChars = dojo.number.parse(profile_topic.value.length);
							var currentValue = parseInt(255) - numChars; 
				
							if (currentValue < 0) {  
								profile_topic.value = profile_topic.value.slice(0, 255);
						    }  
		    }); 
			
			dojo.connect(profile_topic, 
					   "onfocus",
					    function(e){ 
							e.preventDefault(); 
							var updated_topic = profile_topic.value;  
							 
							if (updated_topic == default_topic) {
								profile_topic.value = "";
								dojo.removeClass(profile_topic, "profile_details_empty");
							}
							
			}); 
			
			dojo.connect(profile_topic, 
					   "onblur",
					    function(e){ 
							e.preventDefault(); 
							var updated_topic = profile_topic.value;  

							if (updated_topic == "") {
								profile_topic.value = default_topic;
								dojo.addClass(profile_topic, "profile_details_empty");
							}
							
			});
		}
		
		if (profile_body) {
			profile_body.value = default_profile;
			dojo.addClass(profile_body, "profile_details_empty");
			
			dojo.connect(profile_body, 
		    		    "onkeyup",
		    		    function(){  
							var numChars = dojo.number.parse(profile_body.value.length);
							var currentValue = parseInt(1000) - numChars; 
				
							if (currentValue < 0) {  
								profile_body.value = profile_body.value.slice(0, 1000);
						    }  
		    }); 
			
			dojo.connect(profile_body, 
					   "onfocus",
					    function(e){ 
							e.preventDefault(); 
							var updated_description = profile_body.value;  
							 
							if (updated_description == default_profile) {
								profile_body.value = "";
								dojo.removeClass(profile_body, "profile_details_empty");
							}
							
			});

			dojo.connect(profile_body, 
					   "onblur",
					    function(e){ 
							e.preventDefault(); 
							var updated_description = profile_body.value;  

							if (updated_description == "") {
								profile_body.value = default_profile;
								dojo.addClass(profile_body, "profile_details_empty");
							}
							
			});
		} 

		// hook onclick event to submit profile form.
		var add_profile_submit = dojo.byId('add_profile_submit');  
		if (add_profile_submit) { 
			dojo.connect(add_profile_submit, 'onclick', Z2h.user.profile.addProfile); 
		}  
		
		// hook onclick event to edit profile or cancel editing profile.
		dojo.query(".edit_personal_info").forEach(function(node, i){ 
			dojo.connect(node, 'onclick', function(evt) {
				evt.preventDefault();  
				 
				var href = node.href;
				var id = dojo.attr(node, "alt");
				
				Z2h.user.profile.loadProfile(href, id);
			});  
		});
		
		// hook onclick event to show confirm dialog to delete item.
		dojo.query('a.delete').forEach(function(link) {
			dojo.connect(link, 'onclick', Z2h.link.doPostDelete);
		});
	},
	
	// validate profile form.
	validateProfileForm: function(category_id, description_id) { 
		var category = dojo.byId(category_id);
		var description = dojo.byId(description_id); 
		twi
		if (dojo.hasClass(category, 'profile_details_empty')) {
			// topic is required. 
			return false;
		} else { 
			if (category.value.length == 0) {
				return false;
			} else {
				if (dojo.hasClass(description, 'profile_details_empty')) {
					description.value = "";
					dojo.removeClass(description, "profile_details_empty");
				} 
				
				return true;
			} 
		} 
	},
	
	// submit form to add a new profile info.
	addProfile: function(evt) {
		evt.preventDefault(); 
		 
		// only send an ajax request if nothing is running.
		if (Z2h.user.profile._running === false) {
			Z2h.user.profile._running = true;
			
			var form = dojo.byId('user_profile_create');
			var status_active = dojo.byId("add_profile_submit");
			var overlay_wait = dojo.byId("add_personal_please_wait");
			
			if (form) { 
				if (status_active && overlay_wait) {
					status_active.style.display = "none";
					overlay_wait.style.display = ""; 
				}
				 
				if (Z2h.user.profile.validateProfileForm('profile_category', 'description')) {
					dojo.xhrPost({
						url: form.action+'/format/json', 
						form: "user_profile_create",  
						handleAs: "json",
//						sync: true,
						headers: {"X-Requested-With": "XMLHttpRequest"},
						load: function(data,ioargs){  
							if(data.result == '1'){ 
								Z2h.user.profile._running = false;
								
								// refresh profile details.  
								var profile_details_link = dojo.byId('profile_details_link');  
								if (profile_details_link) { 
									Z2h.user.profile.loadProfileDetails(profile_details_link.href);
								}  
							} else { 
								if (status_active && overlay_wait) {
									status_active.style.display = "";
									overlay_wait.style.display = "none"; 
								}
								
								var profile_info_error = dojo.byId('profile_personal_error');
								 
								if (profile_info_error) {
									profile_info_error.innerHTML = "";
									
									for(var k in data.errors){ 
										if(k == 'logged_out'){
											window.location.assign(data.errors[k]);
										} else {
											profile_info_error.innerHTML += data.errors[k]+"<br />"; 
										} 
									}  
									
									profile_info_error.style.display = "block";
								} 
							}
							
							return data; //always return the response back 
						},
						// if any error occurs, it goes here:
						error : function(response, ioArgs) { 
				            console.log("failed xhrGet", response, ioArgs); 
				            
				            alert("ERROR: There was an error while submitting your request. Please try again!");
				            
				            /* handle the error... */ 
				            return response; //always return the response back 
				        }
					});  
				} else {
					if (status_active && overlay_wait) {
						status_active.style.display = "";
						overlay_wait.style.display = "none"; 
					}
					
					var profile_info_error = dojo.byId('profile_personal_error');
					 
					if (profile_info_error) {
						profile_info_error.innerHTML = "Topic is required.";
						profile_info_error.style.display = "block";
					} 
				}
			} 
			
			Z2h.user.profile._running = false;
		} 
	},
	
	// load profile details.
	loadProfileDetails: function(href) {  
		// only send an ajax request if nothing is running.
		if (Z2h.user.profile._running === false) {
			Z2h.user.profile._running = true;
			
			dojo.xhrGet({ 
			 	url: href+"/format/text",  //the relative URL  
			 	handleAs: "text",
//			 	sync: true,
			 	// run this function if the request is successful 
		        load : function(response, ioArgs) { 
					if (response == 'logged_out') { 
			 			window.location.assign('/login-required');
			 		} else {
			 			// set some element's content... 
						var update_dom = dojo.byId("user_profile_info");
						
						if (update_dom) {
							update_dom.innerHTML= response; 

							if (dijit.byId("profile_category")) {
					        	dijit.byId("profile_category").destroy(); 
					        }
					        
					        dojo.parser.parse(update_dom);
					       
							// hook events again.
							Z2h.user.profile.initAddProfile();
						}
			 		} 
					 
		            return response; //always return the response back 
		        },
				// if any error occurs, it goes here:
				error : function(response, ioArgs) { 
		            console.log("failed xhrGet", response, ioArgs); 
		            
		            alert("ERROR: There was an error while submitting your request. Please try again!");
		            
		            /* handle the error... */ 
		            return response; //always return the response back 
		        }
			});
			
			Z2h.user.profile._running = false;
		} 
	}
}

//---------------------- AUTO-COMPLETE COUNTRY & REGION JS --------------------------------
Z2h.autocomplete = { 
	init: function() { 
		var selected_country_field = dojo.byId("selected_country");
		var selected_country_id = 0;
		var country_select = dijit.byId("country_id");
		
		if (selected_country_field) {
			selected_country_id = selected_country_field.value;
		} 
		
		var selected_region_field = dojo.byId("selected_region");
		var selected_region_id = 0;
		var region_select = dijit.byId("region_id");
		
		if (selected_region_field) {
			selected_region_id = selected_region_field.value;
		} 
		 
		// if country is selected, set the country name in the select list
		if (country_select) {
			country_select.setValue(selected_country_id); 
		}
		 
		// if region is selected, set the region name in the select list
		if (region_select) {
			region_select.query = {country_id : selected_country_id};
			region_select.sort = [{attribute: "region_name", descending: true}];  
			region_select.setValue(selected_region_id);   
		} 
	}, 
	
	// clear error
	clearErr: function(select, field) {
		if (!select.isValid()) { 
	    	select.setValue(0);
	    }  
	},
	
	// clear field if default value is selected
	resetField: function(select) { 
		var id = select.getValue();
		
		if (id == 0) {
			select.textbox.value = ""; 
		}
	},
	
	// refresh regions
	refreshRegions: function(select) { 
		if (select.isValid()) {  
			var selected_country_field = dojo.byId("selected_country");
			var current_country_id = 0; 
			var selected_country_id = select.getValue();
			
			if (selected_country_field) {
				current_country_id = selected_country_field.value;
			}  
			
			if (current_country_id != selected_country_id) { 
				// refresh the region list based on selected country id
		    	var selected_country_id = select.getValue(); 
		    	
		    	if (selected_country_field) {
					selected_country_field.value = selected_country_id;
				} 
		    	
				var region_select = dijit.byId("region_id");
				if (region_select) {
					region_select.setValue(0); 
					region_select.textbox.value = "-- select province --";   
					region_select.query = {country_id : selected_country_id};
					region_select.sort = [{attribute: "region_name", descending: true}];
				} 
			} 
	    } 
	}
}

//---------------------- CONNECTION MODULE JS --------------------------------
Z2h.connection = {
	_running: false,

	_href: null, 
		
	init: function() { 
	    // hook onclick event to show reason dialog
	    dojo.query(".follow_me").forEach(function(link) {
			dojo.connect(link, "onclick", Z2h.connection.reasonDialog);
		}); 
	    
            var user_profile_friendship_link = dojo.byId('user_profile_friendship_link');
	    if (user_profile_friendship_link) {
		dojo.connect(user_profile_friendship_link, 'onclick', Z2h.connection.friendRequest); 
	    }

	    var user_profile_cancelfriendship_link = dojo.byId('user_profile_cancelfriendship_link');
	    if (user_profile_cancelfriendship_link) {
		dojo.connect(user_profile_cancelfriendship_link, 'onclick', Z2h.connection.cancelFriendship); 
	    }

	    // hook onclick event to call unblock as ajax.
	    dojo.query(".unblock_ajax").forEach(function(link) {
			dojo.connect(link, "onclick", Z2h.connection.unblock);
		}); 
	},

	// show reason dialog.
	cancelFriendship: function(evt) {
		evt.preventDefault(); 
		  
		Z2h.connection._href = dojo.attr(evt.currentTarget, "href"); 

		if (Z2h.connection._href) {
			var username = evt.currentTarget.name; 
			var description = "Are you sure you want to terminate this friendship with "+username+"? After terminating it, no further friendship requests can be sent to you by "+username+"."
	 		Z2h.link.popup("friendship_remove_overlay", "Terminate Friendship", description, Z2h.connection.okDisconnect, false);
			} 
	},
	
        // show reason dialog.
	friendRequest: function(evt) {
		evt.preventDefault(); 
		  
		Z2h.connection._href = dojo.attr(evt.currentTarget, "href"); 

		if (Z2h.connection._href) {
			var username = evt.currentTarget.name; 
			var description = "Do you wish to send a friendship request to "+username+"? This friendship request will remain pending until "+username+" approves it."
	 		Z2h.link.popup("friendship_request_overlay", "A New Friendship Request", description, Z2h.connection.okConnect, false);
			} 
	},

	// send post request to delete item
	okDisconnect: function() {
		// only send an ajax request if nothing is running
		if (Z2h.connection._running === false) {
			Z2h.connection._running = true; 
			var overlay_id = "friendship_remove_overlay";

			var opened_dialog = dijit.byId(overlay_id);
		
		        if (opened_dialog) {
			    var button_div = dojo.byId(overlay_id+"_popupButtons_div");
			    var wait_msg = dojo.byId(overlay_id+"_wait");

			    if (button_div && wait_msg) {
			        dojo.style(button_div, "display", "none");
				dojo.style(wait_msg, "display", "block");
			    }

			    var form = document.createElement("form");
			    form.setAttribute("id", "disconnectForm");
			    form.setAttribute("method", "POST");
			    form.setAttribute("action", Z2h.connection._href);
			    document.getElementsByTagName("body").item(0).appendChild(form);

			    dojo.xhrPost({
					url: form.action + "/flash_msg/0/format/json", 
					form: "disconnectForm",  
					handleAs: "json",
//					sync: true,
					headers: {"X-Requested-With": "XMLHttpRequest"},
					load: function(data,ioargs){  
						// update popup message.
						var popup_msg = dojo.byId(overlay_id+"_msg");

						if(data.result == "1"){   
							popup_msg.innerHTML = "Ok. Your friendship is now terminated.";
 
							// replace the friendship remove request button to add button.
							var user_profile_cancelfriendship_link = dojo.byId("user_profile_cancelfriendship_link");
							if (user_profile_cancelfriendship_link) {
								dojo.attr(user_profile_cancelfriendship_link, "id", "user_profile_cancelfriendship_link_done");

								// take event off.
								dojo.attr(user_profile_cancelfriendship_link, "href", "");
								dojo.style(user_profile_cancelfriendship_link, "display", "none");

								var user_profile_cancelfriendship_link_after = dojo.byId("user_profile_cancelfriendship_link_after");
								if (user_profile_cancelfriendship_link_after) {
								//	dojo.connect(user_profile_cancelfriendship_link_after, 'onclick', Z2h.connection.friendRequest); 
								    dojo.style(user_profile_cancelfriendship_link_after, "display", "inline");
								}

							}
							 
						} else { 
							popup_msg.innerHTML = "Error!<br />"; 

							for(var k in data.errors){ 
								popup_msg.innerHTML += data.errors[k]+"<br />";
							}  
						}
						
						// only show cancel (change to close) button.
						var no_button = dojo.byId(overlay_id+"_noBtn");
						var yes_button = dojo.byId(overlay_id+"_yesBtn");
						dojo.style(yes_button, "display", "none");
						no_button.innerHTML = "<span>Close</span>";

						// hide wait message.
						dojo.style(button_div, "display", "block");
						dojo.style(wait_msg, "display", "none"); 
	
						return data; //always return the response back 
					},
					// if any error occurs, it goes here:
					error : function(response, ioArgs) { 
						console.log("failed xhrGet", response, ioArgs); 
				            
				        alert("ERROR: There was an error while submitting your request. Please try again!");
				            
				        /* handle the error... */ 
				        return response; //always return the response back 
				   }
				}); 
			}
			
			Z2h.connection._running = false;
			Z2h.connection._href = null;	  
		}  
	},

	// send post request to delete item
	okConnect: function() {
		// only send an ajax request if nothing is running
		if (Z2h.connection._running === false) {
			Z2h.connection._running = true; 

			var opened_dialog = dijit.byId("friendship_request_overlay");
		
		        if (opened_dialog) {
			    var button_div = dojo.byId("friendship_request_overlay_popupButtons_div");
			    var wait_msg = dojo.byId("friendship_request_overlay_wait");

			    if (button_div && wait_msg) {
			        dojo.style(button_div, "display", "none");
				dojo.style(wait_msg, "display", "block");
			    }

			    var form = document.createElement("form");
			    form.setAttribute("id", "connectForm");
			    form.setAttribute("method", "POST");
			    form.setAttribute("action", Z2h.connection._href);
			    document.getElementsByTagName("body").item(0).appendChild(form);

		            dojo.xhrPost({
					url: form.action + "/flash_msg/0/format/json", 
					form: "connectForm",  
					handleAs: "json",
//					sync: true,
					headers: {"X-Requested-With": "XMLHttpRequest"},
					load: function(data,ioargs){  
						// update popup message.
						var popup_msg = dojo.byId("friendship_request_overlay_msg");

						if(data.result == "1"){   
							popup_msg.innerHTML = "Ok. Your friendship request is successfully sent!";
 
							// disable the friendship request button to pending status.
							var user_profile_friendship_link = dojo.byId("user_profile_friendship_link");
							if (user_profile_friendship_link) {
								user_profile_friendship_link.innerHTML = "Friendship Requested";
								dojo.attr(user_profile_friendship_link, "id", "user_profile_friendship_link_pending");

								// take event off.
								dojo.attr(user_profile_friendship_link, "href", "");

							}

							// disable the friendship request button to pending status.
							var user_profile_friendship_link = dojo.byId("user_profile_cancelfriendship_link_after");
							if (user_profile_friendship_link) {
								user_profile_friendship_link.innerHTML = "Friendship Requested";
								dojo.attr(user_profile_friendship_link, "id", "user_profile_cancelfriendship_link_after_pending");

								// take event off.
								dojo.attr(user_profile_friendship_link, "href", "");

							}
						} else { 
							popup_msg.innerHTML = "Error!<br />"; 

							for(var k in data.errors){ 
								popup_msg.innerHTML += data.errors[k]+"<br />";
							}  
						}
						
						// only show cancel (change to close) button.
						var no_button = dojo.byId("friendship_request_overlay_noBtn");
						var yes_button = dojo.byId("friendship_request_overlay_yesBtn");
						dojo.style(yes_button, "display", "none");
						no_button.innerHTML = "<span>Close</span>";

						// hide wait message.
						dojo.style(button_div, "display", "block");
						dojo.style(wait_msg, "display", "none"); 
	
						return data; //always return the response back 
					},
					// if any error occurs, it goes here:
					error : function(response, ioArgs) { 
						console.log("failed xhrGet", response, ioArgs); 
				            
				        alert("ERROR: There was an error while submitting your request. Please try again!");
				            
				        /* handle the error... */ 
				        return response; //always return the response back 
				   }
				});  
			
		        } 
 

			Z2h.connection._running = false;
			Z2h.connection._href = null;	  
		}  
	},


	unblock: function(evt) {
		evt.preventDefault();
		
		dojo.xhrGet({ 
			url: evt.currentTarget.href+"/format/json",   
			handleAs: "json",
			sync: true,
			headers: {"X-Requested-With": "XMLHttpRequest"},
			load: function(data,ioargs){  
				if (data.result == "1") {
		 			var call_back = dojo.byId('do_after_callback');
					if (call_back) { 
						if (document.createEvent) {
							// Firefox etc.
							event = document.createEvent("HTMLEvents");
							event.initEvent("click", false, true);
							call_back.dispatchEvent(event);
						} else {
							// IE
							call_back.fireEvent("onclick");
						}  
					} else {
						// refresh the current page
						window.location.reload(true);
					} 
		 		} else {
		 			// refresh the current page
					window.location.reload(true);
		 		} 
				
				return data; //always return the response back 
			},
			// if any error occurs, it goes here:
			error: function(response, ioArgs){
				console.log("failed xhrPost", response, ioArgs);
				
				alert("ERROR: There was an error while submitting your form. Please try again!");
				/* handle the error... */ 
	            return response; //always return the response back 
			}
		}); 
	}, 
	
	// show reason dialog.
	reasonDialog: function(evt) {
		evt.preventDefault(); 
		 
		var href = evt.currentTarget.href;
		
		// only send an ajax request if nothing is running
		if (Z2h.connection._running === false) {
			Z2h.connection._running = true;
			
			dojo.xhrGet({ 
			 	url: href + "/format/text",  
			 	handleAs: "text",
//			 	sync: true,
			 	// run this function if the request is successful
		        load : function(response, ioArgs) { 
					if (response == "logged_out") { 
			 			window.location.assign("/login-required");
			 		} else if (response == "connected") { 
			 		    // refresh the current page
						window.location.reload(true);
			 		} else {
			 		    // close already opend reason form
				 		var opened_reason_form = dijit.byId("reason_dialog");
							
				 		if (opened_reason_form) {
				 			opened_reason_form.hide(); 
				 			opened_reason_form.destroy();
				 		} 
				 		
				 		// initialize dialog
						var reason_form = new dijit.Dialog({id: "reason_dialog"}); 
						dojo.style(reason_form.titleBar, "display", "none");  
						
						reason_form.attr("content", response); 
						reason_form.show();
						 
						// close over flag form. 
						dojo.query(".dijitDialogCloseIcon, #reason_dialog_cancel").forEach(function(node, i) {  
							//node.style.display = "block";
							var closeHandle = dojo.connect(node, "onclick", dojo.hitch(reason_form, function(e) { 
								e.preventDefault();
								
								reason_form.attr("content", ""); 
								reason_form.hide(); 
								reason_form.destroy(); 
								
								dojo.disconnect(closeHandle); 
							})); 
						}); 
						
						// overwrite the default esc key event
						var escHandle = dojo.connect(reason_form.domNode, "onkeypress", function(e) {
							var key = e.keyCode || e.charCode;
							var k = dojo.keys;
						
							if (key == k.ESCAPE) {
								e.preventDefault();
								
								reason_form.attr("content", ""); 
								reason_form.hide(); 
								reason_form.destroy(); 
							    
								dojo.disconnect(escHandle); 
							}
						});
						
						// create a submit button to send the connection form
					    var submitButton = dojo.byId("reason_dialog_submit"); 
					    
					    if (submitButton) {  
					    	dojo.connect(submitButton, "onclick", function(e) { 
					    		e.preventDefault();   
								Z2h.connection.sendReason();
					    	}); 
					    } 
					    
					    var connect_following_form = dojo.byId("connect_following_form"); 
					    
					    if (connect_following_form) {  
					    	dojo.connect(connect_following_form, "onsubmit", function(e) { 
					    		e.preventDefault();
								Z2h.connection.sendReason();
					    	}); 
					    } 
					    
					    var otherText = dojo.byId("othertext"); 
					    var otherRadio = dojo.byId("otherradio");
					    
						if (otherText && otherText.value.length == 0) {
							otherText.disabled = true;
						}

						// attach radio button
						if (otherRadio && otherText) {
							dojo.connect(otherRadio, "onclick", function(e) {
								otherText.disabled = false;
								otherText.focus();
							});
							
							dojo.connect(otherText, "onclick", function(e) {
								otherRadio.checked = true;
								otherText.disabled = false;
							});
						} 
						
						dojo.query("input[name=reason]").forEach(function(obj) {
							dojo.connect(obj, "onclick", function(evt) { 
								if (evt.target.id != "otherradio") {
									otherText.value = "";
									otherText.disabled = true;
								}
							});
						}); 
			 		} 
					
		            return response; //always return the response back 
		        }, 
		        // run this function if the request is not successful
		        error : function(response, ioArgs) { 
		            console.log("failed xhrGet", response, ioArgs); 
		            
		            alert("ERROR: There was an error while submitting your request. Please try again!");
		            
		            /* handle the error... */ 
		            return response; //always return the response back 
		        }
			});
			
			Z2h.connection._running = false;
		} 
	},
	
	sendReason: function() {
		// only send an ajax request if nothing is running
		if (Z2h.connection._running === false) {
			Z2h.connection._running = true; 
			
			var status_active = dojo.byId("connections_reason_popup");
			var active_btn = dojo.byId("connections_buttons");
			var overlay_wait = dojo.byId("following_please_wait"); 
			var form = dojo.byId("connect_following_form");
			
			if (form) { 
				if (status_active && active_btn && overlay_wait) {
					status_active.style.display = "none";
					active_btn.style.display = "none";
					overlay_wait.style.display = ""; 
				}
				 
				dojo.xhrPost({
					url: form.action + "/format/json", 
					form: "connect_following_form",  
					handleAs: "json",
//					sync: true,
					headers: {"X-Requested-With": "XMLHttpRequest"},
					load: function(data,ioargs){  
						if(data.result != "0"){   
							// close already opend reason form
					 		var opened_reason_form = dijit.byId('reason_dialog');
								
					 		if (opened_reason_form) {
					 			opened_reason_form.hide(); 
					 			opened_reason_form.destroy();
					 		} 
							 
					 		if (data.result == "1") {
					 			var call_back = dojo.byId('do_after_callback');
								if (call_back) { 
									if (document.createEvent) {
										// Firefox etc.
										event = document.createEvent("HTMLEvents");
										event.initEvent("click", false, true);
										call_back.dispatchEvent(event);
									} else {
										// IE
										call_back.fireEvent("onclick");
									}  
								} else {
									// refresh the current page
									window.location.reload(true);
								} 
					 		} else {
					 			// refresh the current page
								window.location.reload(true);
					 		} 
						} else { 
							if (status_active && active_btn && overlay_wait) {
								status_active.style.display = "";
								active_btn.style.display = "";
								overlay_wait.style.display = "none"; 
							}
								
							var following_error = dojo.byId("following_error");
								 
							if (following_error) {
								following_error.innerHTML = "";
									
								for(var k in data.errors){ 
									if(k == "logged_out"){
										window.location.assign(data.errors[k]);
									} else {
										following_error.innerHTML += data.errors[k][0] + "<br />"; 
									} 
								}  
									
								following_error.style.display = "block";
							} 
						}
							
						return data; //always return the response back 
					},
					// if any error occurs, it goes here:
					error : function(response, ioArgs) { 
						console.log("failed xhrGet", response, ioArgs); 
				            
				        alert("ERROR: There was an error while submitting your request. Please try again!");
				            
				        /* handle the error... */ 
				        return response; //always return the response back 
				   }
				});  
			} 
			
			Z2h.connection._running = false;
		} 
	}
}

//---------------------- DOJO EDITOR JS --------------------------------
Z2h.editor = {
	init: function() { 
	    // hook onclick event to replace textarea with dojo editor value
		dojo.query("form.dojo_editor_form").forEach(function(node) {
			dojo.connect(node, "onsubmit", Z2h.editor.submitForm);
		}); 
	},
	
	submitForm: function(evt) {
		evt.preventDefault();
		
		// get editor value as textarea body value 
 		var dojo_editor = dijit.byId("dojo_editor_textarea");
			
 		if (dojo_editor) { 
 			var textarea = document.createElement("textarea"); 
			dojo.attr(textarea, "name", "body");  
			dojo.style(textarea, {"display": "none"});
			textarea.value = dojo_editor.getValue();
			 
			dojo.place(textarea, evt.currentTarget, "first");
 			evt.currentTarget.submit(); 
 		}  
	}
}
 
//---------------------- SOCIAL CAPITAL JS --------------------------------
Z2h.social = { 
	init: function() {  
		var preview_btn = dojo.byId("social_preview_btn");
		
		if (preview_btn) {  
			dojo.connect(preview_btn, "onclick", Z2h.social.doPreview); 
		} 
		
		var save_btn = dojo.byId("social_save_btn");
		
		if (save_btn) {  
			dojo.connect(save_btn, "onclick", Z2h.social.confirmSave); 
		} 
		 
		// for safari, hook onsubmit event to submit login form
		var save_form = dojo.byId("social_capital_form");
		
		if (save_form) {
			dojo.connect(save_form, "onsubmit", Z2h.social.confirmSave);
		} 
	},
	 
	confirmSave: function(evt) {
		evt.preventDefault();
		Z2h.link.popup("save_confirm_overlay", "Save Confirmation", "Are you sure you want to save? Once you save the changes, you cannot undo.", Z2h.social.doSave);
	},
	 
	doSave: function() {
		var form = dojo.byId("social_capital_form"); 
		form.submit(); 
	},
	
	// preview user social capital before saving
	doPreview: function(evt) {
		evt.preventDefault();
		var href = dojo.attr(evt.currentTarget, "title");
		
		// hide no script sections
		dojo.query('div.no_script_running').forEach(function(no_script_section) {
			no_script_section.style.display = "none"; 
		});
		
		// show script sections
		dojo.query('div.script_running').forEach(function(script_section) {
			script_section.style.display = "block"; 
		});

		dojo.xhrPost({ 
			url: href + "/format/text", 
			form: "social_capital_form",  
			handleAs: "text",
//			sync: true,
			headers: {"X-Requested-With": "XMLHttpRequest"},
			load : function(response, ioArgs) {  
				var update_dom = dojo.byId("preview_user_ranks");
				
				if (update_dom) {
					update_dom.innerHTML= response;  
				}
				
				// hide script sections
				dojo.query("div.script_running").forEach(function(script_section) {
					script_section.style.display = "none"; 
				});
				
				// show no script sections
				dojo.query("div.no_script_running").forEach(function(no_script_section) {
					no_script_section.style.display = "block"; 
				});
				
				return response; //always return the response back 
			},
			// if any error occurs, it goes here:
			error : function(response, ioArgs) { 
				console.log("failed xhrGet", response, ioArgs); 
		            
		        alert("ERROR: There was an error while submitting your request. Please try again!");
		            
		        /* handle the error... */ 
		        return response; //always return the response back 
		   }
		});
	} 
}

//---------------------- CREATION JS -------------------------
Z2h.creation = {
	_running: false,
	
	_sliding_base: 520,
	
	init: function() {  
		// sliding effect for prev link
		dojo.query("div.creation_pagination > ul.pagination > li.previous > a").forEach(function(link) {
			dojo.connect(link, "onclick", Z2h.creation.slidingPrevPaginator);
		});
		
		// sliding effect for pagination
		dojo.query("div.creation_pagination > ul.pagination > li.inactive > a").forEach(function(link) {
			dojo.connect(link, "onclick", Z2h.creation.slidingPaginator);
		});
		
		// sliding effect for next link
		dojo.query("div.creation_pagination > ul.pagination > li.next > a").forEach(function(link) {
			dojo.connect(link, "onclick", Z2h.creation.slidingNextPaginator);
		});
	
		// change background color
		var creation_container = dojo.byId("creation_container");
		
		if (creation_container) { 
			dojo.query(".text_light_option").forEach(function(option) {
				dojo.connect(option, "onclick", function(e) {  
					e.preventDefault();
					
					if (dojo.hasClass(creation_container, "text_dark")) { 
						dojo.removeClass(creation_container, "text_dark");
					}
			    }); 
			});
			
			dojo.query(".text_dark_option").forEach(function(option) {
				dojo.connect(option, "onclick", function(e) {  
					e.preventDefault();
					dojo.addClass(creation_container, "text_dark"); 
			    });  
			}); 
		}
		
		// change font size
		var creation_container_content = dojo.byId("creation_container_content");
		
		if (creation_container_content) {
			dojo.query(".font_size_option").forEach(function(option) {
				dojo.connect(option, "onclick", function(e) {  
					e.preventDefault();
					
					var currently_selected = dojo.query(".selected_font_size")[0];
					
					if (currently_selected) {
						var current_font_size = dojo.attr(currently_selected, "title");
						
						if (dojo.hasClass(currently_selected, "selected_font_size")) { 
							dojo.removeClass(currently_selected, "selected_font_size");
						}
						
						if (dojo.hasClass(creation_container_content, "text_size_" + current_font_size)) { 
							dojo.removeClass(creation_container_content, "text_size_" + current_font_size);
						}
					}
					
					var new_font_size = dojo.attr(option, "title");
					
					dojo.addClass(option, "selected_font_size"); 
					dojo.addClass(creation_container_content, "text_size_" + new_font_size); 
			    });  
			});
		}
	},
	
	slidingPrevPaginator: function(evt) {
		evt.preventDefault(); 
		
		var prev_page = 0;
		var next_link = dojo.query("div.creation_pagination > ul.pagination > li.next")[0]; 
		var selected_link = dojo.query("div.creation_pagination > ul.pagination > li.active")[0];
		
		if (selected_link) {
			var selected_page = parseInt(selected_link.innerHTML);
			 
			dojo.removeClass(selected_link, "active");
			dojo.addClass(selected_link, "inactive"); 
			
			var pagination_link = document.createElement("a");
			
			dojo.attr(pagination_link, "id", "fanfiction_page_" + selected_page);
			dojo.attr(pagination_link, "href", "#");
			pagination_link.innerHTML = selected_page;
			dojo.connect(pagination_link, "onclick", Z2h.creation.slidingPaginator);
			
			selected_link.innerHTML = "";
			dojo.place(pagination_link, selected_link, "last");
			
			prev_page = selected_page - 1;
		}
		 
		if (prev_page > 0) {
			var prev_link = dojo.byId("fanfiction_page_" + prev_page);
			
			if (prev_link) {
				var li_parent = prev_link.parentNode;
				
				if (li_parent) {
					dojo.removeClass(li_parent, "inactive");
					dojo.addClass(li_parent, "active");
					li_parent.innerHTML = prev_page; 
				}
				
				// slide to right
				amt = parseInt(Z2h.creation._sliding_base * (1 - prev_page));
				Z2h.creation.slidingRight(amt); 
			}
			
			// show/hide prev link
			if (prev_page == 1) { 
				evt.currentTarget.parentNode.style.display = "none"; 
			} else {
				evt.currentTarget.parentNode.style.display = "";
			} 
		} 
		
		// show next link
		if (next_link) {
			next_link.style.display = "";
		} 
	},
	
	slidingPaginator: function(evt) {
		evt.preventDefault(); 
		
		var page_id = evt.currentTarget.id; 
		var page = page_id.replace("fanfiction_page_", ""); 
		var prev_link = dojo.query("div.creation_pagination > ul.pagination > li.previous")[0];
		var next_link = dojo.query("div.creation_pagination > ul.pagination > li.next")[0];
		 
		var selected_link = dojo.query("div.creation_pagination > ul.pagination > li.active")[0];
		
		if (selected_link) {
			var selected_page = parseInt(selected_link.innerHTML);
			
			dojo.removeClass(selected_link, "active");
			dojo.addClass(selected_link, "inactive"); 
			
			var pagination_link = document.createElement("a");
			
			dojo.attr(pagination_link, "id", "fanfiction_page_" + selected_page);
			dojo.attr(pagination_link, "href", "#");
			pagination_link.innerHTML = selected_page;
			dojo.connect(pagination_link, "onclick", Z2h.creation.slidingPaginator);
			
			selected_link.innerHTML = "";
			dojo.place(pagination_link, selected_link, "last"); 
		}
		
		var li_parent = evt.currentTarget.parentNode;
		
		if (li_parent) {
			dojo.removeClass(li_parent, "inactive");
			dojo.addClass(li_parent, "active");
			li_parent.innerHTML = page; 
			 
			// show/hide next link
			if (next_link) {
				if (dojo.hasClass(li_parent, "last_inactive")) { 
					next_link.style.display = "none";  
				}else{
					next_link.style.display = ""; 
				} 
			} 
		} 
		 
		// show/hide prev link
		if (prev_link) {
			if (page == 1) {
				// show prev link
				prev_link.style.display = "none"; 
			} else {
				prev_link.style.display = "";
			} 
		} 
		
		var amt = 0;
		
		if (page > selected_page) {
			// slide to left
			amt = parseInt(Z2h.creation._sliding_base * (page-1));
			Z2h.creation.slidingLeft(amt);
		} else {
			// slide to right
			amt = parseInt(Z2h.creation._sliding_base * (1 - page));
			Z2h.creation.slidingRight(amt);
		} 
	},
	
	slidingNextPaginator: function(evt) {
		evt.preventDefault(); 
		
		var next_page = 0; 
		var prev_link = dojo.query("div.creation_pagination > ul.pagination > li.previous")[0]; 
		var selected_link = dojo.query("div.creation_pagination > ul.pagination > li.active")[0];
		
		if (selected_link && !dojo.hasClass(selected_link, "last_inactive")) {
			var selected_page = parseInt(selected_link.innerHTML);
			 
			dojo.removeClass(selected_link, "active");
			dojo.addClass(selected_link, "inactive"); 
			
			var pagination_link = document.createElement("a");
			
			dojo.attr(pagination_link, "id", "fanfiction_page_" + selected_page);
			dojo.attr(pagination_link, "href", "#");
			pagination_link.innerHTML = selected_page;
			dojo.connect(pagination_link, "onclick", Z2h.creation.slidingPaginator);
			
			selected_link.innerHTML = "";
			dojo.place(pagination_link, selected_link, "last");
			
			next_page = selected_page + 1;
			
			var next_link = dojo.byId("fanfiction_page_" + next_page); 
			
			if (next_link) {
				var li_parent = next_link.parentNode; 
				
				if (li_parent) {
					dojo.removeClass(li_parent, "inactive");
					dojo.addClass(li_parent, "active");
					li_parent.innerHTML = next_page;
					
					// show/hide next link
					if (dojo.hasClass(li_parent, "last_inactive")) {
						evt.currentTarget.parentNode.style.display = "none"; 
					} else {
						evt.currentTarget.parentNode.style.display = ""; 
					}
				}
				
				// slide to left
				var amt = parseInt(Z2h.creation._sliding_base * (next_page - 1));
				Z2h.creation.slidingLeft(amt); 
			}  
		}
		
		// show prev link
		if (prev_link) {
			prev_link.style.display = "";
		}  
	},
	 
	slidingLeft: function(amt) {
		var creation_content_slider = dojo.byId("creation_content_slider");
		
		if (creation_content_slider) {
			var slideArgs = {
	                node: "creation_content_slider",
	                top: (dojo.coords("creation_content_slider").t).toString(),
	                left: (0 - amt).toString(),
	                unit: "px"
	        };
			
	        dojo.fx.slideTo(slideArgs).play();
		} 
	},
	
	slidingRight: function(amt) {
		var creation_content_slider = dojo.byId("creation_content_slider");
		
		if (creation_content_slider) {
			var slideArgs = {
	                node: "creation_content_slider",
	                top: (dojo.coords("creation_content_slider").t).toString(),
	                left: (0 + amt).toString(),
	                unit: "px"
	        };
			
	        dojo.fx.slideTo(slideArgs).play();
		}  
	}
}

//---------------------- GROUP JS --------------------------------
Z2h.group = { 
	_running: false,
		
	init: function() {  
		// hook onchange event to select vote.
		var group_type_select = dojo.byId('group_type');
		if (group_type_select) {
			dojo.connect(group_type_select, 'onchange', Z2h.group.refreshGroupDescription); 
		}
		
		// hook onclick event to show dialog to leave a group.
		dojo.query("a.leave_group").forEach(function(link) {
			dojo.connect(link, "onclick", Z2h.group.leaveGroupDialog);
		}); 
		
	    // hook onclick event to submit form to search group members or posts
		var group_search_btn = dojo.byId('group_search_btn');
		if (group_search_btn) {
			dojo.connect(group_search_btn, 'onclick', Z2h.group.searchGroup);
		}
		
		// hook onclick event to submit form to search group members or posts
		var group_search_form = dojo.byId('group_search');
		if (group_search_form) {
			dojo.connect(group_search_form, 'onsubmit', Z2h.group.searchGroup); 
		} 
		
		// hook onclick event to submit form to send group invitation
		var group_invitation_btn = dojo.byId('group_invitation_btn');
		if (group_invitation_btn) {
			dojo.connect(group_invitation_btn, 'onclick', Z2h.group.sendInvitation);
		}
		
		// hook onclick event to submit form to send group invitation
		var group_invitation_form = dojo.byId('group_invitation_form');
		if (group_invitation_form) {
			dojo.connect(group_invitation_form, 'onsubmit', Z2h.group.sendInvitation); 
		} 
	},
	
	refreshGroupDescription: function(evt) {
		evt.preventDefault();
		 
		var type = evt.currentTarget.value;
		
		dojo.query(".group_description").forEach(function(p) {
			p.style.display = "none";
		}); 
		  
		var selected_description = dojo.byId("group_description_"+type);
		if (selected_description) {
			selected_description.style.display = "block";
		}
	},
	
	// show overlay form to leave group
	leaveGroupDialog: function(evt) {
		evt.preventDefault();
		
		var href = evt.currentTarget.href;
		
		// only send an ajax request if nothing is running
		if (Z2h.group._running === false) {
			Z2h.group._running = true;
			
			dojo.xhrGet({ 
			 	url: href + "/format/text",  //the relative URL  
			 	handleAs: "text",
//			 	sync: true,
			 	// run this function if the request is successful
		        load : function(response, ioArgs) { 
			 		if (response == "logged_out") { 
			 			window.location.assign("/login-required");
			 		} else {
			 			// close already opend overlay form
			 			var opened_form = dijit.byId("leave_form_overlay");
						
			 			if (opened_form) {
			 				opened_form.hide(); 
			 				opened_form.destroy();
			 			} 
			 			
			 			// initialize dialog
						var leave_form = new dijit.Dialog({id: "leave_form_overlay"}); 
						dojo.style(leave_form.titleBar, "display", "none");  
						
						leave_form.attr("content", response); 
						leave_form.show();
		  
					    // close over flag form
						dojo.query("#leave_cancel_btn, .overlay_leave_close, .popupCancelButton").forEach(function(node, i) {   
							var closeHandle = dojo.connect(node, 
														   "onclick",
														   dojo.hitch(leave_form, 
														     		  function(e){ 
														    				e.preventDefault();
														    				leave_form.attr("content", ""); 
														    				leave_form.hide(); 
														    				leave_form.destroy(); 
														     				dojo.disconnect(closeHandle); 
							})); 
						});  
						
						// overwrite the default esc key event
						var escHandle = dojo.connect(leave_form.domNode, "onkeypress", function(e){
									        var key = e.keyCode || e.charCode;
									        var k = dojo.keys;
						
									        if (key == k.ESCAPE) {
									        	e.preventDefault();
									        	leave_form.attr("content", ""); 
									        	leave_form.hide(); 
									        	leave_form.destroy(); 
							     				dojo.disconnect(escHandle); 
									        }
						}); 
						
						// create a submit button to send the leave form
					    var submitButton = dojo.byId("leave_submit_btn"); 
					    if (submitButton) {  
					    	dojo.connect(submitButton, 
							    		"onclick",
							    		function(e){ 
											e.preventDefault();  
											Z2h.group.submitLeave(submitButton.href);
					    	}); 
					    }  
			 		}
			  
		            return response; //always return the response back 
		        }, 
		        // run this function if the request is not successful
		        error : function(response, ioArgs) { 
		            console.log("failed xhrGet", response, ioArgs); 
		            
		            alert("ERROR: There was an error while submitting your request. Please try again!");
		            
		            /* handle the error... */ 
		            return response; //always return the response back 
		        }
			}); 
			
			Z2h.group._running = false; 
		} 
	},
	
	// submit leave form
	submitLeave: function(href) {
		var form = document.createElement("form");
		form.setAttribute("id", "leaveForm");
		form.setAttribute("method", "POST");
		form.setAttribute("action", href);
		document.getElementsByTagName("body").item(0).appendChild(form);
		form.submit();  
	},
	
	searchGroup: function(evt) {
		evt.preventDefault();
		 
		var form = dojo.byId('group_search');
		var input = dojo.byId('group_search_keyword');
		
		if (form && input) {
			var base_href = form.action;  
			
			// update dom id (make sure there is div id=load_ajax_content_here)
			var update_dom = dojo.byId("load_ajax_content_here");
			
			// while loading (make sure there is div id=load_ajax_content_loading)
			var loading_wait = dojo.byId("load_ajax_content_loading");
			
			// ajax requst url
			var href = base_href+"/keyword/"+input.value; 
			
			if (loading_wait) { 
				update_dom.style.display = "none"; 
				loading_wait.style.display = ""; 
			}
			
			dojo.xhrGet({ 
				url: href + "/format/text/",
				handleAs: "text",
//			 	sync: true,
			 	// run this function if the request is successful
		        load : function(response, ioArgs) { 
		            // set some element's content
					update_dom.innerHTML = response;  
					
					if (loading_wait) { 
						loading_wait.style.display = "none"; 
						update_dom.style.display = ""; 
					}
					
		            // initialize js
					Z2h.global.init(); 
					 
		            return response; //always return the response back 
		        }, 
		        // run this function if the request is not successful
		        error : function(response, ioArgs) { 
		            console.log("failed xhrGet", response, ioArgs); 
		             
		            alert("ERROR: There was an error while submitting your request. Please try again!");
		            /* handle the error... */ 
		            return response; //always return the response back 
		        } 
			});   
		} 
	},
	
	sendInvitation: function(evt) {
		evt.preventDefault();
		
		var form = dojo.byId('group_invitation_form'); 
		
		// count errors
		var errors = 0;
		var error_msg = "";
		
		// validate recipients
		var total = Z2h.inbox.recipients.total(); 
		if (total == 0) {
			errors++;
			
			if (error_msg != "") {
				error_msg += "<br />";
			}
			error_msg += "At lease one recipient is required for the message.";
		}
		
		// validate subject
		var subject = Z2h.string.trimAll(dojo.byId('inbox_title').value); 
		if (subject.length == 0) {
			errors++;
			
			if (error_msg != "") {
				error_msg += "<br />";
			}
			error_msg += "Subject is required.";
		} 
		
		// validate body
		var body = Z2h.string.trimAll(dojo.byId('inbox_compose_textarea').value); 
		if (body.length < 10) {
			errors++;
			
			if (error_msg != "") {
				error_msg += "<br />";
			}
			error_msg += "Your message is too short, it can't be shorter than 10 characters.";
		} 
		
		// validate form
		if (errors > 0) {
			// display error message 
			dojo.byId("inbox_compose_errors").innerHTML = error_msg;
		} else {
			dojo.byId("inbox_compose_errors").innerHTML = "";
			 
			// update dom id (make sure there is div id=load_ajax_content_here)
			var update_dom = dojo.byId("load_ajax_content_here");
			
			// while loading (make sure there is div id=load_ajax_content_loading)
			var loading_wait = dojo.byId("load_ajax_content_loading");
			 
			if (loading_wait) { 
				update_dom.style.display = "none"; 
				loading_wait.style.display = ""; 
			}
			
			if (form) {
				dojo.xhrPost({
					url: form.action + "/format/json", 
					form: "group_invitation_form",  
					handleAs: "json",
//					sync: true,
					headers: {"X-Requested-With": "XMLHttpRequest"},
					load: function(data,ioargs){  
						// refresh the current page
						window.location.reload(true);
							
						return data; //always return the response back 
					},
					// if any error occurs, it goes here:
					error : function(response, ioArgs) { 
						console.log("failed xhrGet", response, ioArgs); 
				            
				        alert("ERROR: There was an error while submitting your request. Please try again!");
				            
				        /* handle the error... */ 
				        return response; //always return the response back 
				   }
				});  
			} 
		}
	}
} 


//---------------------- SIGNUP JS --------------------------------
Z2h.signup = { 
	_running: false,
		
	init: function() {   
		// check username.
	    var username = dojo.byId("signup_username");   
		if (username) {  
			dojo.connect(username, 
		    			"onblur",
		    		    function(e){  
							var checker_msg = dojo.byId('username_checker_msg'); 
							var trimmed_username = Z2h.string.trimAll(username.value);
							
							if (checker_msg) {
								if (trimmed_username.length > 0) {
									if (trimmed_username.length > 2) {
										checker_msg.innerHTML = '<img src="/images/spinner.gif" alt="Please wait ..." style="width:20px;" />';
										
										dojo.xhrGet({ 
											url: "/user/authentication/check-username/username/"+trimmed_username+"/format/json",   
											handleAs: "json",
											//sync: true,
											headers: {"X-Requested-With": "XMLHttpRequest"},
											load: function(data,ioargs){  
												if (data.result == "1") {
													dojo.style(checker_msg, {"color": "#aaaaaa"});
													checker_msg.innerHTML = "This username is available.";
												} else {
													dojo.style(checker_msg, {"color": "#ff0000"});
													checker_msg.innerHTML = "This username is already taken.";
												} 
															
												return data; //always return the response back 
											},
											// if any error occurs, it goes here:
											error: function(response, ioArgs){
												console.log("failed xhrPost", response, ioArgs);
															
												alert("ERROR: There was an error while submitting your form. Please try again!");
													/* handle the error... */ 
												    return response; //always return the response back 
												}
											});  
									} else {   
										dojo.style(checker_msg, {"color": "#ff0000"});
									 	checker_msg.innerHTML = "Username must be at least 3 characters long.";
									} 
								} else {
									dojo.style(checker_msg, {"color": "#ff0000"});
						 			checker_msg.innerHTML = "Username is required.";
						 		}
						} 
				}); 
		}
		
		// check email and verify email.
		var email = dojo.byId("signup_email"); 
		var verify_email = dojo.byId("signup_verify_email"); 
		if (email && verify_email) {
			dojo.connect(email, 
		    			"onblur",
		    		    function(e){  
				            var email_after = dojo.byId("email_after");
				            if (email_after) {
				            	var trimmed_email = Z2h.string.trimAll(email.value); 
				            	if (trimmed_email.length > 0) {
				            		var email_filter  = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
				            		
				            		// validate email.
				            		if(!email_filter.test(trimmed_email)) {
				            			dojo.style(email_after, {"color": "#ff0000"});
										email_after.innerHTML = "This Email address is invalid.";
									} else { 
										// check email is available in system.
										email_after.innerHTML = '<img src="/images/spinner.gif" alt="Please wait ..." style="width:20px;" />';
										
										dojo.xhrGet({ 
											url: "/user/authentication/check-email/email/"+trimmed_email+"/format/json",   
											handleAs: "json",
											sync: true,
											headers: {"X-Requested-With": "XMLHttpRequest"},
											load: function(data,ioargs){  
												if (data.result == "1") {
													dojo.style(email_after, {"color": "#aaaaaa"});
													email_after.innerHTML = "";
												} else {
													dojo.style(email_after, {"color": "#ff0000"});
													email_after.innerHTML = "This email already exists in our system."; 
												} 
															
												return data; //always return the response back 
											},
											// if any error occurs, it goes here:
											error: function(response, ioArgs){
												console.log("failed xhrPost", response, ioArgs);
															
												alert("ERROR: There was an error while submitting your form. Please try again!");
													/* handle the error... */ 
												    return response; //always return the response back 
												}
											});
				            		}  
								} else { 
									dojo.style(email_after, {"color": "#ff0000"});
									email_after.innerHTML = "Your Email is required."; 
								}
				          }
				            
				          var verify_email_after = dojo.byId("verify_email_after");   
						  if (verify_email_after) {  
								if (verify_email.value.length > 0 && email.value != verify_email.value) {
										dojo.style(verify_email_after, {"color": "#ff0000"});
										verify_email_after.innerHTML = "Verify Email doesn't match with Email."; 
								} else {
									dojo.style(verify_email_after, {"color": "#aaaaaa"});
									verify_email_after.innerHTML = ""; 
								} 
						  } 
				}); 
			
				dojo.connect(verify_email, 
					    "onblur",
		    		    function(e){  
							var verify_email_after = dojo.byId("verify_email_after");  
							if (verify_email_after) {  
								if (verify_email.value.length > 0) {
									if (email.value != verify_email.value) {
										dojo.style(verify_email_after, {"color": "#ff0000"});
										verify_email_after.innerHTML = "Verify Email doesn't match with Email."; 
									} else {
										dojo.style(verify_email_after, {"color": "#aaaaaa"});
										verify_email_after.innerHTML = ""; 
									}
								} else {
									dojo.style(verify_email_after, {"color": "#ff0000"});
									verify_email_after.innerHTML = "Please verify your email."; 
								} 
						  }
			});   
		}
	 
		// check password and verify password.
		var passwd = dojo.byId("signup_passwd1");
		var verify_passwd = dojo.byId("signup_passwd2"); 
		if (passwd && verify_passwd) {
			dojo.connect(passwd, 
		    			"onfocus",
		    		    function(e){ 
							var passwd_instruction = dojo.byId("passwd_instruction"); 
							var meter_tag = dojo.byId("meter_tag");
							 
							if (passwd_instruction && meter_tag) {
								passwd_instruction.style.display = ""; 
								meter_tag.style.display = "";
								
								var passwd_after = dojo.byId("password_after");
								if (passwd_after) {
									dojo.style(passwd_after, {"color": "#aaaaaa"});
									passwd_after.innerHTML = ""; 
								} 
							}
			});
			
			dojo.connect(passwd, 
					    "onkeyup",
		    		    function(e){ 
							PWStrength(Z2h.string.trimAll(passwd.value));
			});
			
			dojo.connect(passwd, 
		    			"onblur",
		    		    function(e){  
							var passwd_after = dojo.byId("password_after");
							var passwd_point = dojo.byId("password_points");
							
				            if (passwd_after && passwd_point) {
				            	var passwd_instruction = dojo.byId("passwd_instruction"); 
								var meter_tag = dojo.byId("meter_tag");
								 
								if (passwd_instruction && meter_tag) {
									passwd_instruction.style.display = "none"; 
									meter_tag.style.display = "none"; 
								}
				            	
								if (passwd.value.length > 0) {
									if (passwd_point.value > 1) {  
										dojo.style(passwd_after, {"color": "#aaaaaa"});
										passwd_after.innerHTML = "Your password is strong enough."; 
									} else {  
										dojo.style(passwd_after, {"color": "#ff0000"});
										passwd_after.innerHTML = "Your password is not strong enough.";
									}
								}  else {
									dojo.style(passwd_after, {"color": "#ff0000"});
									passwd_after.innerHTML = "Your password is required."; 
				                } 
				            }
				            
					        var verify_password_after = dojo.byId("verify_password_after");  
							if (verify_password_after) {  
								if (verify_passwd.value.length > 0 && passwd.value != verify_passwd.value) {
									dojo.style(verify_password_after, {"color": "#ff0000"});
									verify_password_after.innerHTML = "Verify Password doesn't match with Password."; 
								} else {
									dojo.style(verify_password_after, {"color": "#aaaaaa"});
			                    	verify_password_after.innerHTML = ""; 
								}
							}
				}); 
			
				dojo.connect(verify_passwd, 
						    "onblur",
			    		    function(e){  
								var verify_password_after = dojo.byId("verify_password_after");  
								if (verify_password_after) {  
									if (verify_passwd.value.length > 0) {
										if (passwd.value != verify_passwd.value) {
											dojo.style(verify_password_after, {"color": "#ff0000"});
											verify_password_after.innerHTML = "Verify Password doesn't match with Password."; 
										} else {
					                    	dojo.style(verify_password_after, {"color": "#aaaaaa"});
					                    	verify_password_after.innerHTML = ""; 
					                    }
									} else {
										dojo.style(verify_password_after, {"color": "#ff0000"});
										verify_password_after.innerHTML = "Please verify your password."; 
									}
							    }
			   });   
		}
		
		// hook onclick event to submit form.
		var sign_btn = dojo.byId('sign_btn');
		if (sign_btn) {
			dojo.connect(sign_btn, 'onclick', Z2h.signup.register);
		}  

		// for safari, hook onsubmit event to submit form.
		var signup_form = dojo.byId('signup');
		if (signup_form) {
			dojo.connect(signup_form, 'onsubmit', Z2h.signup.register);
		} 
	}, 
	 	
	register: function(evt) { 
		evt.preventDefault();
		
		// count errors
		var errors = 0;
		 
		// check username.
		var username = dojo.byId("signup_username");   
		if (username) {  
			var checker_msg = dojo.byId('username_checker_msg'); 
			var trimmed_username = Z2h.string.trimAll(username.value);
			
			if (checker_msg) {
				if (trimmed_username.length > 0) {
					if (trimmed_username.length < 3) { 
						dojo.style(checker_msg, {"color": "#ff0000"});
					 	checker_msg.innerHTML = "Username must be at least 3 characters long.";
					 	errors++;
					} 
				} else {
					dojo.style(checker_msg, {"color": "#ff0000"});
		 			checker_msg.innerHTML = "Username is required.";
		 			errors++;
		 		}
			}
		} 
		 
		// check email.
		var email = dojo.byId("signup_email");  
		if (email) {
			var email_after = dojo.byId("email_after");
			if (email_after) {
				var trimmed_email = Z2h.string.trimAll(email.value); 
				if (trimmed_email.length > 0) {
					var email_filter  = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
				            		
				    // validate email.
				    if(!email_filter.test(trimmed_email)) {
				    	dojo.style(email_after, {"color": "#ff0000"});
						email_after.innerHTML = "This Email address is invalid.";
						errors++;
					}  
				} else { 
					dojo.style(email_after, {"color": "#ff0000"});
					email_after.innerHTML = "Your Email is required.";
					errors++;
				}
			} 
		}
		
		// verify email.
		var verify_email = dojo.byId("signup_verify_email"); 
		if (verify_email && email) {
			var verify_email_after = dojo.byId("verify_email_after");  
			if (verify_email_after) {  
				if (verify_email.value.length > 0) {
					if (email.value != verify_email.value) {
						dojo.style(verify_email_after, {"color": "#ff0000"});
						verify_email_after.innerHTML = "Verify Email doesn't match with Email."; 
						errors++;
					} 
				} else {
					dojo.style(verify_email_after, {"color": "#ff0000"});
					verify_email_after.innerHTML = "Please verify your email."; 
					errors++;
                }
			}
		}
		
		// check password.
		var passwd = dojo.byId("signup_passwd1");
		if (passwd) {
			var passwd_after = dojo.byId("password_after");
			var passwd_point = dojo.byId("password_points");
			
            if (passwd_after && passwd_point) {
            	var passwd_instruction = dojo.byId("passwd_instruction"); 
				var meter_tag = dojo.byId("meter_tag");
				 
				if (passwd_instruction && meter_tag) {
					passwd_instruction.style.display = "none"; 
					meter_tag.style.display = "none"; 
				}
            	
				if (passwd.value.length > 0) {
					if (passwd_point.value <= 1) {  
						dojo.style(passwd_after, {"color": "#ff0000"});
						passwd_after.innerHTML = "Your password is not strong enough.";
						errors++;
					}
				}  else {
					dojo.style(passwd_after, {"color": "#ff0000"});
					passwd_after.innerHTML = "Your password is required."; 
					errors++;
                } 
            }
            
		}
		
		// verify password.
		var verify_passwd = dojo.byId("signup_passwd2");
		if (verify_passwd && passwd) {  
			var verify_password_after = dojo.byId("verify_password_after");  
			if (verify_password_after) {
				if (verify_passwd.value.length > 0) {
					if (passwd.value != verify_passwd.value) {
						dojo.style(verify_password_after, {"color": "#ff0000"});
						verify_password_after.innerHTML = "Verify Password doesn't match with Password."; 
						errors++;
					} 
				} else {
					dojo.style(verify_password_after, {"color": "#ff0000"});
					verify_password_after.innerHTML = "Please verify your password."; 
					errors++;
                }
			}
		} 
		
		// check terms and agreement.
		var signup_agreement = dojo.byId("terms_agree");
		var term_after = dojo.byId("term_after");  
		if (!signup_agreement.checked) { 
			if (term_after) {
				dojo.style(term_after, {"color": "#ff0000"});
				term_after.innerHTML = "You must agree with our Terms of Use and Privacy Policy.";
				errors++;
			} 
		} else {
			if (term_after) {
				dojo.style(term_after, {"color": "#aaaaaa"});
				term_after.innerHTML = ""; 
			} 
		}
		
		// validate form
		if (errors == 0) { 
			var signup_form = dojo.byId('signup');
			if (signup_form) {
				signup_form.submit(); 
			}
		}
	}
} 

//---------------------- LOGIN JS --------------------------------
Z2h.login = { 
	_running: false,
		
	init: function() {   
		// hook onclick event to submit form.
		var login_btn = dojo.byId('login_btn');
		if (login_btn) {
			dojo.connect(login_btn, 'onclick', Z2h.login.submit);
		}  

		// for safari, hook onsubmit event to submit form.
		var login_form = dojo.byId('login');
		if (login_form) {
			dojo.connect(login_form, 'onsubmit', Z2h.login.submit);
		} 
	}, 
	
	submit: function(evt) { 
		evt.preventDefault();
		
		// count errors
		var errors = 0;
		 
		// check username.
		var username = dojo.byId("login_username");   
		if (username) {  
			var trimmed_username = Z2h.string.trimAll(username.value); 
			username.value = trimmed_username;
			if (trimmed_username.length == 0) { 
				errors++;
            }  
		}  
		
		// check password.
		var passwd = dojo.byId("login_passwd");
		if (passwd) {  
			if (passwd.value.length == 0) { 
				errors++;
            } 
		} 
		
		// validate form
		var error_msg = dojo.byId("login_error");
		
		// close over flag form
		dojo.query(".login_session_msg").forEach(function(node, i) {   
			node.style.display = "none";
		}); 
		
		if (errors == 0) { 
			if (error_msg) {
				error_msg.innerHTML = "";
				error_msg.style.display = "none";
			} 
			
			var login_form = dojo.byId('login');
			if (login_form) {
				login_form.submit(); 
			}
		} else { 
			if (error_msg) {
				error_msg.innerHTML = "Both username and password are required.";
				error_msg.style.display = "";
			}
		}
	}
}

//---------------------- FORGOT PASSWORD JS --------------------------------
Z2h.forgot = { 
	_running: false,
		
	init: function() {   
		// hook onclick event to submit form.
		var forgot_btn = dojo.byId('forgot_btn');
		if (forgot_btn) {
			dojo.connect(forgot_btn, 'onclick', Z2h.forgot.submit);
		}  

		// for safari, hook onsubmit event to submit form.
		var forgot_form = dojo.byId('forgot');
		if (forgot_form) {
			dojo.connect(forgot_form, 'onsubmit', Z2h.forgot.submit);
		} 
	}, 
	
	submit: function(evt) { 
		evt.preventDefault();
		
		// count errors
		var errors = 0;
		 
		// check email.
		var email = dojo.byId("forgot_email");   
		var forgot_error_msg = "Please enter the email you signed up with.";
		if (email) {  
			var trimmed_email = Z2h.string.trimAll(email.value); 
			email.value = trimmed_email; 
			if (trimmed_email.length > 0) { 
				var email_filter  = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
        		
			    // validate email.
			    if(!email_filter.test(trimmed_email)) {
			    	forgot_error_msg = "Please enter a valid email address.";
			    	errors++;
			    } 
            } else {
            	errors++;
            }
		}   
		
		// validate form
		var error_msg = dojo.byId("forgot_error");
		 
		dojo.query(".forgot_session_msg").forEach(function(node, i) {   
			node.style.display = "none";
		}); 
		
		if (errors == 0) { 
			if (error_msg) {
				error_msg.innerHTML = "";
				error_msg.style.display = "none";
			} 
			
			var forgot_form = dojo.byId('forgot');
			if (forgot_form) {
				forgot_form.submit(); 
			}
		} else { 
			if (error_msg) {
				error_msg.innerHTML = forgot_error_msg;
				error_msg.style.display = "";
			}
		}
	}
}

//---------------------- RESET PASSWORD JS --------------------------------
Z2h.reset = { 
	_running: false,
		
	init: function() {   
		// check password and verify password.
		var passwd = dojo.byId("reset_new_password");
		var verify_passwd = dojo.byId("reset_verify_password"); 
		if (passwd && verify_passwd) {
			dojo.connect(passwd, 
		    			"onfocus",
		    		    function(e){ 
							var passwd_instruction = dojo.byId("passwd_instruction"); 
							var meter_tag = dojo.byId("meter_tag");
							 
							if (passwd_instruction && meter_tag) {
								passwd_instruction.style.display = ""; 
								meter_tag.style.display = "";
								
								var passwd_after = dojo.byId("password_after");
								if (passwd_after) {
									dojo.style(passwd_after, {"color": "#aaaaaa"});
									passwd_after.innerHTML = ""; 
								} 
							}
			});
			
			dojo.connect(passwd, 
					    "onkeyup",
		    		    function(e){ 
							PWStrength(Z2h.string.trimAll(passwd.value));
			});
			
			dojo.connect(passwd, 
		    			"onblur",
		    		    function(e){  
							var passwd_after = dojo.byId("password_after");
							var passwd_point = dojo.byId("password_points");
							
				            if (passwd_after && passwd_point) {
				            	var passwd_instruction = dojo.byId("passwd_instruction"); 
								var meter_tag = dojo.byId("meter_tag");
								 
								if (passwd_instruction && meter_tag) {
									passwd_instruction.style.display = "none"; 
									meter_tag.style.display = "none"; 
								}
				            	
								if (passwd.value.length > 0) {
									if (passwd_point.value > 1) {  
										dojo.style(passwd_after, {"color": "#aaaaaa"});
										passwd_after.innerHTML = "Your new password is strong enough."; 
									} else {  
										dojo.style(passwd_after, {"color": "#ff0000"});
										passwd_after.innerHTML = "Your new password is not strong enough.";
									}
								}  else {
									dojo.style(passwd_after, {"color": "#ff0000"});
									passwd_after.innerHTML = "Your new password is required."; 
				                } 
				            }
				            
					        var verify_password_after = dojo.byId("verify_password_after");  
							if (verify_password_after) {  
								if (verify_passwd.value.length > 0 && passwd.value != verify_passwd.value) {
									dojo.style(verify_password_after, {"color": "#ff0000"});
									verify_password_after.innerHTML = "Verify Password doesn't match with New Password."; 
								} else {
									dojo.style(verify_password_after, {"color": "#aaaaaa"});
			                    	verify_password_after.innerHTML = ""; 
								}
							}
				}); 
			
				dojo.connect(verify_passwd, 
						    "onblur",
			    		    function(e){  
								var verify_password_after = dojo.byId("verify_password_after");  
								if (verify_password_after) {  
									if (verify_passwd.value.length > 0) {
										if (passwd.value != verify_passwd.value) {
											dojo.style(verify_password_after, {"color": "#ff0000"});
											verify_password_after.innerHTML = "Verify Password doesn't match with New Password."; 
										} else {
					                    	dojo.style(verify_password_after, {"color": "#aaaaaa"});
					                    	verify_password_after.innerHTML = ""; 
					                    }
									} else {
										dojo.style(verify_password_after, {"color": "#ff0000"});
										verify_password_after.innerHTML = "Please verify your new password."; 
									}
							    }
			   });   
		} 
	
	    // hook onclick event to submit form.
		var reset_btn = dojo.byId('reset_btn');
		if (reset_btn) {
			dojo.connect(reset_btn, 'onclick', Z2h.reset.submit);
		}  

		// for safari, hook onsubmit event to submit form.
		var reset_form = dojo.byId('reset');
		if (reset_form) {
			dojo.connect(reset_form, 'onsubmit', Z2h.reset.submit);
		} 
	}, 
	
	submit: function(evt) { 
		evt.preventDefault();
		
		// count errors
		var errors = 0;
		 
		// check password.
		var passwd = dojo.byId("reset_new_password");
		if (passwd) {
			var passwd_after = dojo.byId("password_after");
			var passwd_point = dojo.byId("password_points");
			
            if (passwd_after && passwd_point) {
            	passwd_after.innerHTML = "";
            	var passwd_instruction = dojo.byId("passwd_instruction"); 
				var meter_tag = dojo.byId("meter_tag");
				 
				if (passwd_instruction && meter_tag) {
					passwd_instruction.style.display = "none"; 
					meter_tag.style.display = "none"; 
				}
            	
				if (passwd.value.length > 0) {
					if (passwd_point.value <= 1) {  
						dojo.style(passwd_after, {"color": "#ff0000"});
						passwd_after.innerHTML = "Your new password is not strong enough.";
						errors++;
					}
				}  else {
					dojo.style(passwd_after, {"color": "#ff0000"});
					passwd_after.innerHTML = "Your new password is required."; 
					errors++;
                } 
            } 
		}
		
		// verify password.
		var verify_passwd = dojo.byId("reset_verify_password");
		if (verify_passwd && passwd) {  
			var verify_password_after = dojo.byId("verify_password_after");  
			if (verify_password_after) {
				verify_password_after.innerHTML = "";
				if (verify_passwd.value.length > 0) {
					if (passwd.value != verify_passwd.value) {
						dojo.style(verify_password_after, {"color": "#ff0000"});
						verify_password_after.innerHTML = "Verify Password doesn't match with New Password."; 
						errors++;
					} 
				} else {
					dojo.style(verify_password_after, {"color": "#ff0000"});
					verify_password_after.innerHTML = "Please verify your new password."; 
					errors++;
                }
			}
		}
		
		// validate form 
		dojo.query(".reset_session_msg").forEach(function(node, i) {   
			node.style.display = "none";
		}); 
		
		if (errors == 0) {  
			var reset_form = dojo.byId('reset');
			if (reset_form) {
				reset_form.submit(); 
			}
		}  
	}
}

//---------------------- EVENT JS --------------------------------
Z2h.event = { 
	_running: false,
		
	init: function() {    
	    // hook onclick event to submit form.
		var event_btn = dojo.byId('event_btn');
		if (event_btn) {
			dojo.connect(event_btn, 'onclick', Z2h.event.submit);
		}  

		// for safari, hook onsubmit event to submit form.
		var event_form = dojo.byId('event_form');
		if (event_form) {
			dojo.connect(event_form, 'onsubmit', Z2h.event.submit);
		} 
		
		// based on recurring,  
		dojo.query("[name=recurring]").forEach(function(recurring, i){   
			var special_end_date = dojo.byId("special_end_date");
			
			dojo.connect(recurring, 
			    		 "onchange",
			    		 function(e){  
							 if (recurring.checked) { 
								 if (recurring.value != 'Special') { 
									 if (special_end_date) {
										 special_end_date.style.display = "none";
									 }
								 } else {
									 if (special_end_date) {
										 var end_date_error = dojo.byId("end_date_error");
										 if (end_date_error) { 
											end_date_error.innerHTML = ""; 
										 }
										  
										 var event_date = dijit.byId("event_date");
										 var event_end_date = dijit.byId("event_end_date");
										 if (event_date && event_end_date) { 
											 event_end_date.attr('value', event_date.attr('value')); 
										 }
										 
										 special_end_date.style.display = "block";
									 }
								 }
							 }  
			 }); 
		}); 
		
		var country_select = dojo.byId('country_select');
		var ca_regions = dojo.byId('ca_region_select');
		var us_regions = dojo.byId('us_region_select');
		var jamaica_regions = dojo.byId('jamaica_region_select');
		var no_regions = dojo.byId('no_region_select');
		var region_label_select = dojo.byId('region_label_select');
		
		if (country_select && ca_regions && us_regions && jamaica_regions && no_regions && region_label_select) {
			dojo.connect(country_select, 
			    		"onchange",
			    		 function(e){  
							var country_id = parseInt(dojo.byId('country_select').value);
 
							if (country_id == 42) {
								no_regions.style.display = "none";
								us_regions.style.display = "none";
								jamaica_regions.style.display = "none";
								ca_regions.style.display = "block";
								ca_regions.value = 0; 
								region_label_select.innerHTML = "Province:";
								
								dojo.attr(ca_regions, "name", "region_id");
								dojo.attr(us_regions, "name", "us_region_id");
								dojo.attr(no_regions, "name", "no_region_id");
								dojo.attr(jamaica_regions, "name", "jamaica_region_id");
							} else if (country_id == 245) {
								no_regions.style.display = "none";
								ca_regions.style.display = "none";
								us_regions.style.display = "block";
								jamaica_regions.style.display = "none";
								us_regions.value = 0; 
								region_label_select.innerHTML = "State:";

								dojo.attr(ca_regions, "name", "ca_region_id");
								dojo.attr(us_regions, "name", "region_id");
								dojo.attr(no_regions, "name", "no_region_id");
								dojo.attr(jamaica_regions, "name", "jamaica_region_id");
							} else if (country_id == 116) {
								no_regions.style.display = "none";
								ca_regions.style.display = "none";
								us_regions.style.display = "none";
								jamaica_regions.style.display = "block";
								jamaica_regions.value = 0; 
								region_label_select.innerHTML = "Parish:";

								dojo.attr(ca_regions, "name", "ca_region_id");
								dojo.attr(us_regions, "name", "us_region_id");
								dojo.attr(no_regions, "name", "no_region_id");
								dojo.attr(jamaica_regions, "name", "region_id");
							} else {
								ca_regions.style.display = "none";
								us_regions.style.display = "none"; 
								jamaica_regions.style.display = "none";
								no_regions.style.display = "block";
								no_regions.value = 0;
								region_label_select.innerHTML = "Province/State/Parish:";
								
								dojo.attr(ca_regions, "name", "ca_region_id");
								dojo.attr(us_regions, "name", "us_region_id");
								dojo.attr(jamaica_regions, "name", "jamaica_region_id");
								dojo.attr(no_regions, "name", "region_id");
							} 
						});
		} 
	}, 
	
	syncDate: function(event_date) { 
		 var event_end_date = dijit.byId("event_end_date");
		 if (event_end_date) { 
			 event_end_date.attr('value', event_date.attr('value')); 
		 }
	},
	
	submit: function(evt) { 
		evt.preventDefault();
		
		// count errors
		var errors = 0;
		 
		// check title.
		var title = dojo.byId("event_title");
		if (title) {
			var event_title = Z2h.string.trimAll(title.value);
			title.value = event_title;
			
			var title_error = dojo.byId("title_error"); 
			
			if (event_title.length > 0) {
				if (title_error) { 
					title_error.innerHTML = ""; 
				}
			} else {
				if (title_error) { 
					title_error.innerHTML = "Title is required."; 
				} 
				
				errors++;
            }  
		}
		
		// check description.
		var description = dojo.byId("event_description_textarea");
		if (description) {
			var event_description = Z2h.string.trimAll(description.value);  
			var description_error = dojo.byId("description_error"); 
			
			if (event_description.length > 0) {
				if (description_error) { 
					description_error.innerHTML = ""; 
				}
			} else {
				if (description_error) { 
					description_error.innerHTML = "Description is required."; 
				} 
				
				errors++;
            }  
		}
		 
		// check minimum age.
		var minimum_age = dojo.byId("event_minimum_age"); 
		if (minimum_age) {
			var event_minimum_age = minimum_age.value;
			var age_error = dojo.byId("age_error"); 
			
			if (event_minimum_age == "0") {
				if (age_error) { 
					age_error.innerHTML = "Please select a minimum age."; 
				}
				
				errors++;
			} else {
				if (age_error) { 
					age_error.innerHTML = ""; 
				}
			}
		}
		 
		// check venue name.
		var venue_name = dojo.byId("event_venue_name");
		if (venue_name) {
			var event_venue_name = Z2h.string.trimAll(venue_name.value);
			venue_name.value = event_venue_name;
			
			var venue_name_error = dojo.byId("venue_name_error"); 
			
			if (event_venue_name.length > 0) {
				if (venue_name_error) { 
					venue_name_error.innerHTML = ""; 
				}
			} else {
				if (venue_name_error) { 
					venue_name_error.innerHTML = "Venue name is required."; 
				} 
				
				errors++;
            }  
		}
		
		// check country.
		var country_select = dojo.byId("country_select"); 
		var region_error = dojo.byId("region_error");
		
		if (country_select) {
			var country_id = country_select.value;
			var country_error = dojo.byId("country_error"); 
			
			if (country_id == "0") {
				if (country_error) { 
					country_error.innerHTML = "Please select a country."; 
				}
				
				var no_region_select = dojo.byId("no_region_select"); 
				if (no_region_select) {
					var region_id = no_region_select.value;
					 
					if (region_id == "0") {
						if (region_error) { 
							region_error.innerHTML = "Please select a state/province.";
						} 
						
						errors++;
					} else {
						if (region_error) { 
							region_error.innerHTML = ""; 
						}
					}
				}
				
				errors++;
			} else {
				if (country_error) { 
					country_error.innerHTML = ""; 
				}
				
				if (country_id == "42") {
					var ca_region_select = dojo.byId("ca_region_select"); 
					if (ca_region_select) {
						var region_id = ca_region_select.value;
						 
						if (region_id == "0") {
							if (region_error) { 
								region_error.innerHTML = "Please select a state/province.";
							} 
							
							errors++;
						} else {
							if (region_error) { 
								region_error.innerHTML = ""; 
							}
						}
					}
				} else if (country_id == "245") {
					var us_region_select = dojo.byId("us_region_select"); 
					if (us_region_select) {
						var region_id = us_region_select.value;
						 
						if (region_id == "0") {
							if (region_error) { 
								region_error.innerHTML = "Please select a state/province.";
							} 
							
							errors++;
						} else {
							if (region_error) { 
								region_error.innerHTML = ""; 
							}
						}
					}
				}
			} 
		} 
		
		// check city.
		var city = dojo.byId("event_city");
		if (city) { 
			var event_city = Z2h.string.trimAll(city.value);
			city.value = event_city;
			
			var city_error = dojo.byId("city_error"); 
			
			if (event_city.length > 0) {
				if (city_error) { 
					city_error.innerHTML = ""; 
				}
			} else {
				if (city_error) { 
					city_error.innerHTML = "City is required."; 
				} 
				
				errors++;
            }  
		}
		
		// check street address.
		var street_address = dojo.byId("event_street_address");
		if (street_address) {
			var event_street_address = Z2h.string.trimAll(street_address.value);
			street_address.value = event_street_address;
			
			var street_address_error = dojo.byId("street_address_error"); 
			
			if (event_street_address.length > 0) {
				if (street_address_error) { 
					street_address_error.innerHTML = ""; 
				}
			} else {
				if (street_address_error) { 
					street_address_error.innerHTML = "Street address is required."; 
				} 
				
				errors++;
            }  
		}
		
		// check flyer.
		var flyer = dojo.byId("event_flyer");
		if (flyer) {
			var event_flyer = Z2h.string.trimAll(flyer.value); 
			var flyer_error = dojo.byId("flyer_error"); 
			
			if (flyer.value.length > 0) {
				if (flyer_error) { 
					flyer_error.innerHTML = ""; 
				}
			} else {
				if (flyer_error) { 
					flyer_error.innerHTML = "Please select an image to upload."; 
				} 
				
				errors++;
            }  
		}
		
		// check date.
		var event_date = dojo.byId("event_date");
		if (event_date) { 
			var date_error = dojo.byId("date_error"); 
			var date_value = dojo.query("[name=date]")[0].value;
			 
			if (date_value.length > 0) {
				if (date_error) { 
					date_error.innerHTML = ""; 
				}
			} else {
				if (date_error) { 
					date_error.innerHTML = "Please select a date from calender."; 
				} 
				
				errors++;
            }  
		}
		 
		// validate url 
		var website_url = dojo.byId("event_website_url");
		var url_filter  = /^www.[A-Za-z0-9\.-]{3,}\.[A-Za-z]{2,}/;

		if (website_url) {
			var event_website_url = Z2h.string.trimAll(website_url.value); 
			var url_error = dojo.byId("url_error"); 
			
			if (event_website_url.length > 0 && !url_filter.test(event_website_url)){
				if (url_error) { 
					url_error.innerHTML = "Please provide a valid url. (eg: www.abc.com)"; 
				}
				
				errors++;
			} else {
				if (url_error) { 
					url_error.innerHTML = ""; 
				}  
            }  
		}  
		 
		var checked_recurring = "";
		dojo.query("[name=recurring]").forEach(function(recurring, i){  
			 if (recurring.checked) {
				 checked_recurring = recurring.value;
			 } 
		});
		
		var recurring_error = dojo.byId("recurring_error"); 
		var end_date_error = dojo.byId("end_date_error"); 
		
		if (end_date_error) { 
			end_date_error.innerHTML = ""; 
		}
		
		if (checked_recurring == 'Weekly') { 
			var weekly_select = dojo.byId("weekly_recurring_day_select"); 
			if (weekly_select) {  
				if (weekly_select.value == "x") {
					if (recurring_error) { 
						recurring_error.innerHTML = "Please select a day of week."; 
					}
					
					errors++;
				} else {
					if (recurring_error) { 
						recurring_error.innerHTML = ""; 
					}
				}
			} 
		} else if (checked_recurring == 'Monthly') {
			var when_select = dojo.byId("monthly_recurring_when_select"); 
			var day_select = dojo.byId("monthly_recurring_day_select"); 
			if (when_select && day_select) {  
				if (when_select.value == "x" || day_select.value == "x") {
					if (recurring_error) { 
						recurring_error.innerHTML = "Please select which week of month and a day."; 
					}
					
					errors++;
				} else {
					if (recurring_error) { 
						recurring_error.innerHTML = ""; 
					}
				}
			}
		} else {
			if (recurring_error) { 
				recurring_error.innerHTML = ""; 
			} 

			// check end date for special event.
			var event_end_date = dojo.byId("event_end_date");
			if (event_end_date) {  
				var date_value = dojo.query("[name=end_date]")[0].value;
				 
				if (date_value.length > 0) {
					if (end_date_error) { 
						end_date_error.innerHTML = ""; 
					}
				} else {
					if (end_date_error) { 
						end_date_error.innerHTML = "Please select an end date from calender. If it's a day event, select same date as the start date."; 
					} 
					
					errors++;
	            }  
			} 
		}
		 
		var submit_error = dojo.byId("submit_error");
		if (errors == 0) {  
			if (submit_error) {
				submit_error.innerHTML = "";
			}
			var event_form = dojo.byId('event_form');
			if (event_form) {
				event_form.submit(); 
			}
		} else {
			if (submit_error) {
				submit_error.innerHTML = "Please review the form prior to submitting.";
			}
		}
	}
}
 
//---------------------- LINKS JS --------------------------------
Z2h.links = { 
	_running: false,
		
	init: function() {    
	    // hook onclick link to submit form.
		var link_btn = dojo.byId('link_btn');
		if (link_btn) {
			dojo.connect(link_btn, 'onclick', Z2h.links.submit);
		}  

		// for safari, hook onsubmit link to submit form.
		var link_form = dojo.byId('link_form');
		if (link_form) {
			dojo.connect(link_form, 'onsubmit', Z2h.links.submit);
		} 
	},  
	 
	submit: function(evt) { 
		evt.preventDefault();
		
		// count errors
		var errors = 0;
		 
		// check title.
		var title = dojo.byId("link_title");
		if (title) {
			var link_title = Z2h.string.trimAll(title.value);
			title.value = link_title;
			
			var title_error = dojo.byId("title_error"); 
			
			if (link_title.length > 0) {
				if (title_error) { 
					title_error.innerHTML = ""; 
				}
			} else {
				if (title_error) { 
					title_error.innerHTML = "Title is required."; 
				} 
				
				errors++;
            }  
		}
		
		// check description.
		/*var description = dojo.byId("link_description_textarea");
		if (description) {
			var link_description = Z2h.string.trimAll(description.value);  
			var description_error = dojo.byId("description_error"); 
			
			if (link_description.length > 0) {
				if (description_error) { 
					description_error.innerHTML = ""; 
				}
			} else {
				if (description_error) { 
					description_error.innerHTML = "Description is required."; 
				} 
				
				errors++;
          }  
		}*/
		
		// validate url 
		var website_url = dojo.byId("link_website_url");
		var url_filter  = /^www.[A-Za-z0-9\.-]{3,}\.[A-Za-z]{2,}/;

		if (website_url) {
			var link_website_url = Z2h.string.trimAll(website_url.value); 
			var url_error = dojo.byId("url_error"); 
			
			if (link_website_url.length == 0 || !url_filter.test(link_website_url)){
				if (url_error) { 
					url_error.innerHTML = "Please provide a valid url. (eg: www.abc.com)"; 
				}
				
				errors++;
			} else {
				if (url_error) { 
					url_error.innerHTML = ""; 
				}  
            }  
		}  
		 
		// check since year.
		/*var year_select = dojo.byId("since_year_select");  
		if (year_select) {
			var year = year_select.value;
			var since_year_error = dojo.byId("since_year_error"); 
			
			if (year == "0") {
				if (since_year_error) { 
					since_year_error.innerHTML = "Please select a year."; 
				} 
				
				errors++;
			} else {
				if (since_year_error) { 
					since_year_error.innerHTML = ""; 
				} 
			} 
		} */
		
		// check category.
		var category_select = dojo.byId("category_select");  
		if (category_select) {
			var category_id = category_select.value;
			var category_error = dojo.byId("category_error"); 
			
			if (category_id == "0") {
				if (category_error) { 
					category_error.innerHTML = "Please select a category."; 
				} 
				
				errors++;
			} else {
				if (category_error) { 
					category_error.innerHTML = ""; 
				} 
			} 
		}
		
		// check country.
		var country_select = dojo.byId("country_select");  
		if (country_select) {
			var country_id = country_select.value;
			var country_error = dojo.byId("country_error"); 
			
			if (country_id == "0") {
				if (country_error) { 
					country_error.innerHTML = "Please select a country."; 
				} 
				
				errors++;
			} else {
				if (country_error) { 
					country_error.innerHTML = ""; 
				} 
			} 
		} 
		 
		// check thumbnail.
		var thumbnail = dojo.byId("link_thumbnail");
		if (thumbnail) {
			var link_thumbnail = Z2h.string.trimAll(thumbnail.value); 
			var thumbnail_error = dojo.byId("thumbnail_error"); 
			
			if (link_thumbnail.length > 0) {
				if (thumbnail_error) { 
					thumbnail_error.innerHTML = ""; 
				}
			} else {
				if (thumbnail_error) { 
					thumbnail_error.innerHTML = "Please select an image to upload."; 
				} 
				
				errors++;
            }  
		}  
		
		var submit_error = dojo.byId("submit_error");
		if (errors == 0) {  
			if (submit_error) {
				submit_error.innerHTML = "";
			}
			var link_form = dojo.byId('link_form');
			if (link_form) {
				link_form.submit(); 
			}
		} else {
			if (submit_error) {
				submit_error.innerHTML = "Please review the form prior to submitting.";
			}
		}
	}
}

//---------------------- PAGE ONLOND -------------------------
dojo.addOnLoad(function() {  
	Z2h.global.init();  
	
	dojo.behavior.apply();
	
	var editor_iframe = dojo.byId("dojo_editor_textarea_iframe"); 
	
	if (editor_iframe) {
		editor_iframe.style.width = "479px";
		editor_iframe.style.padding = "0";
	}
	 
	var sidebar = dojo.byId("side_banner");
	
	if (sidebar) {  
		var browserWidth = document.documentElement.clientWidth;
		
		// show/hide sidebar on load
		if (browserWidth < 1365) { 
			sidebar.style.display = "none";
		} else {
			sidebar.style.display = "block";
		}
		
		// show/hide sidebar on resize
		dojo.connect(window, "onresize", function(e) {
			var updatedBrowserWidth = document.documentElement.clientWidth;
						
			if (updatedBrowserWidth < 1365) {
				sidebar.style.display = "none";
			} else { 
				sidebar.style.display = "block";
			} 
		});
	}
});

