/*
	Copyright (c) Zeros 2 Heroes All Rights Reserved. 
*/ 

dojo.require("dojo.parser");

//---------------------- DOJO WIDGETS -------------------------------- 

dojo.require("dijit.Dialog");
dojo.require("dijit.form.Form"); 
dojo.require("dijit.form.Button"); 
dojo.require("dijit.form.TextBox"); 
dojo.require("dijit.form.FilteringSelect");
dojo.require("dijit.form.ValidationTextBox");
dojo.require("dijit.form.CheckBox");
dojo.require("dijit.form.ComboBox");
dojo.require("dijit.form.FilteringSelect");
dojo.require("dijit.form.Textarea");
dojo.require("dojo.number");
dojo.require("dojo.data.ItemFileWriteStore");
dojo.require("dojo.dnd.Source"); 
dojo.require("dojo.dnd.move");
dojo.require("dojo.io.iframe");

dojo.declare("Z2hFilteringSelect", dijit.form.FilteringSelect, {
    _startSearchFromInput: function() {
        if (this.focusNode.value.length >= 2) {
            this._startSearch(this.focusNode.value);
        }
    }
});

//---------------------- 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);
	}
});


//---------------------- POST DELETE FUNCTION ------------------------- 

// send a request as post form submission only after confirmation.
function doPostDelete(link, msg, is_ajax, redirect){    
	if (confirm(msg)) { 
		if (is_ajax) {
			// submit the form.
			dojo.xhrPost({
				url: link.href+"/format/json",  
				handleAs: "json",
				sync: true,
				headers: {"X-Requested-With": "XMLHttpRequest"},
				load: function(data,ioargs){  
					if(data.result == "1"){ 
						if(redirect){
							window.location.assign(redirect);
						}else{
							// reload the page.
							window.location.reload(true);
						}  
					}else{
						for(var k in data.errors){ 
							alert(data.errors[k]); 
						}
					} 
				},
				// 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 request. 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",link.href);
			document.getElementsByTagName("body").item(0).appendChild(form);
			form.submit();
		} 
	} 
	
	return false;
}  

//---------------------- STRING FUNCTION -------------------------  

// trim empty string from front.
function leftTrim(sString) {
	while (sString.substring(0,1) == ' ') {
		sString = sString.substring(1, sString.length);
	}
	return sString;
}

// trim empty string from end.
function rightTrim(sString) {
	while (sString.substring(sString.length-1, sString.length) == ' '){
		sString = sString.substring(0,sString.length-1);
	}
	return sString;
}

// trim empty string from front-end.
function trimAll(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)
function countTextarea(txtNode, updateId, submitBtn, max) { 
	var numChars = dojo.number.parse(txtNode.value.length);
    var remainingChars = dojo.byId(updateId);
    
    var currentValue = parseInt(max) - numChars;
    
    if (currentValue < 0) { 
    	txtNode.value = txtNode.value.slice(0, max);
    	dojo.attr(submitBtn, "disabled", "disabled");  
    	remainingChars.innerHTML = "0 characters remaining";  
    } else {
    	dojo.removeAttr(submitBtn, "disabled"); 
    	remainingChars.innerHTML = currentValue + " characters remaining";  
    }  
    
	return;
}

//---------------------- DISCUSSION/FORUM/BLOG FUNCTIONS -------------------------  

// show overlay flag submission form.
function showFlagForm(link) { 
	 // get flag link.
	 var href = dojo.attr(link, "href"); 
	 var alt = dojo.attr(link, "alt");
	 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) { 
		 		// 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(".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();  
									sendFlagForm(href, alt);
			    	}); 
			    } 
			    
			    // hook text character length aid.
			    var reason = dojo.byId('reason'); 
			    if (reason) {  
			    	dojo.connect(reason, 
					    		"onkeyup",
					    		function(){  
									countTextarea(reason, "flag_characters_remaining", submitButton, 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 
	        }
	});   
}

// send flag form.
function sendFlagForm(link, parent_id) { 
	var reason = dojo.byId("reason");
	var reason_error = dojo.byId("reason_error"); 
	var loading_div = dojo.byId("overlay_please_wait");
	var form_div = dojo.byId("overlay_flag_form");
	var submit_btn = dojo.byId("flag_submit_btn");
	var cancel_btn = dojo.byId("flag_cancel_btn");
	
	// validate reason.
	if (reason.value.length > 10) {
		if (reason_error) {
			reason_error.innerHTML = "";
		}
		
		form_div.style.display = "none";
		submit_btn.style.display = "none";
		cancel_btn.style.display = "none"; 
		loading_div.style.display = "block";
		
		// submit the form.
		dojo.xhrPost({
			url: link+"/format/json", 
			form: "flag_post_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(); 

					// disable flag link.
    				//console.log(parent_id);
					dojo.byId(parent_id).innerHTML = '<p id="awaiting_moderation">This post has been flagged and is awaiting moderation.</p>'; 
				}else{
					// show the signup form with the error message.
					form_div.style.display = "block"; 
					submit_btn.style.display = "block";
					cancel_btn.style.display = "block";  
					loading_div.style.display = "none";
					
					for(var k in data.errors){ 
						dojo.byId(k).innerHTML = data.errors[k]; 
					} 
					
					// set focus on textarea.
				    reason.focus();
				} 
			},
			// 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 request. Please try again!"); 
				
				/* handle the error... */ 
	            return response; //always return the response back 
			}
		}); 
	} else { 
		if (reason.value.length == 0) {
			reason_error.innerHTML = "Your reason is required.";
		} else {
			reason_error.innerHTML = "Your reason is too short, it can't be shorter than 10 characters.";
		} 
		
		form_div.style.display = "block"; 
		submit_btn.style.display = "block";
		cancel_btn.style.display = "block";  
		loading_div.style.display = "none";
	} 
}

// thumbs up/down a post.
function ratePost(link, rate) { 
	 // get rating link and parent class.
	 var href = dojo.attr(link, "href");
	 var alt = dojo.attr(link, "alt");
	 
	 dojo.xhrGet({ 
		    url: href+"/format/json",  
			handleAs: "json",
			sync: true,
			headers: {"X-Requested-With": "XMLHttpRequest"},
			load: function(data,ioargs){  
				if(data.result == "1"){ 
					// update all the rating status for this post. (save extra ajax call)
					updateRatings(alt, rate); 
				}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 
			} 
	});  
}

// update all the ratings whose parent node has given class name.
function updateRatings(parent_class, rate) {  
	// update rating number. 
	dojo.query('ul.'+parent_class+' > li.rating_number > p').forEach(function(node, i){  
		// get the current rating number.
		var current_rating_number = node.innerHTML;
		 
		// update rating_number (with + or -)  
		current_rating_number = parseInt(current_rating_number) + parseInt(rate); 
		 
		if (current_rating_number > 0) {
			node.innerHTML = "+"+current_rating_number;
		} else {
			node.innerHTML = current_rating_number;
		}  
	}); 
	 
	var theID = parent_class.replace("post_ratings_","");
	 
	// disable thumb up link.
	dojo.query('li#big_rate_link_up_'+theID+'.'+parent_class+'_up').forEach(function(node, i){  
		 node.innerHTML = '<img src="/images/icons/thumbs_up_gray.jpg" alt="+" />';
	});
	
	// disable thumb down link.
	dojo.query('li#big_rate_link_down_'+theID+'.'+parent_class+'_down').forEach(function(node, i){  
		 node.innerHTML = '<img src="/images/icons/thumbs_down_gray.jpg" alt="-" />';
	});
}

function showEditor(e){
	e.preventDefault();
	var small = dojo.byId("discussion_editor_small");
	var big = dojo.byId("discussion_editor_full");
	small.style.display = "none";
	big.style.display = "block";
}

function hideEditor(){
	var small = dojo.byId("discussion_editor_small");
	var big = dojo.byId("discussion_editor_full");
	small.style.display = "block";
	big.style.display = "none";
}

//---------------------- MY PROFILE VIEW FUNCTIONS -------------------------  

// show edit status form.
function showStatusForm() { 
	dojo.xhrGet({ 
	 	url: "/user/profile/edit-status/format/text",  //the relative URL  
	 	handleAs: "text",
	 	sync: true,
	 	// run this function if the request is successful 
        load : function(response, ioArgs) { 
            // set some element's content... 
            dojo.byId("user_status_info").innerHTML= response; 
            
            // initiate edit status form submit.
    		initializeEditStatusForm();
    		
            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 form. Please try again!");
            /* handle the error... */ 
            return response; //always return the response back 
        } 
	});   
}

// initialize edit status form on profile page.
function initializeEditStatusForm() { 
	// submit form by ajax.
	var update_submit = dojo.byId('edit_status_submit');  

	// only connect the js action if the submit button is available.
	if (update_submit) { 
		dojo.connect(update_submit,
				    "onclick",
				    function(e){ 
						e.preventDefault(); 
						dojo.attr(update_submit, "disabled", "disabled");
						sendStatusForm(); 
		}); 
	} 

	// view status by ajax.
	var update_cancel = dojo.byId('edit_status_cancel');  
	
	// only connect the js action if the cancel button is available.
	if (update_cancel) {
		dojo.connect(update_cancel, 
				   "onclick",
				    function(e){ 
						e.preventDefault(); 
						dojo.attr(update_cancel, "disabled", "disabled");
						showStatus(); 
		});  
	}  
	
	// hook text character length aid.
    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);
				    }  
	    }); 
    } 
}

// cancel edit status form and return to view status.
function showStatus(){ 
	var uid = dojo.byId('status_info_uid').value;
	 
	dojo.xhrGet({ 
	 	url: "/user/profile/view-status/uid/"+uid+"/format/text",  //the relative URL  
	 	handleAs: "text",
	 	sync: true,
	 	// run this function if the request is successful 
        load : function(response, ioArgs) { 
            // set some element's content... 
            dojo.byId("user_status_info").innerHTML= response;  
            
            // initiate ajax edit link to edit status info.
        	var edit_status_link = dojo.byId('edit_status_link'); 
        	
        	// only connect the js action if the edit status link is available.
        	if (edit_status_link) { 
        		dojo.connect(edit_status_link,
        				 "onclick",
        				 function(e){ 
        					e.preventDefault();
        					dojo.attr(edit_status_link, "disabled", "disabled");
        					showStatusForm(); 
        		});
        	}  
    		
            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 form. Please try again!");
            
            /* handle the error... */ 
            return response; //always return the response back 
        } 
	});  
} 

// send edit status form after validation.
function sendStatusForm() {   
	var errors = 0;
	
	// validate status. 
	var status_info = trimAll(dojo.byId('edit_status_info').value);  
	if (status_info.length > 255) {
		dojo.byId('status_info_error').innerHTML = "Maximum 255 characters are allowed."; 
		errors++;  
	} else {  
		dojo.byId('status_info_error').innerHTML = ""; 
	}
	dojo.byId('edit_status_info').value = status_info;
	
	// validate form.
	if (errors == 0) { 
		dojo.xhrPost({
			url: "/user/profile/edit-status/format/json", 
			form: "user_status_update",  
			handleAs: "json",
			sync: true,
			headers: {"X-Requested-With": "XMLHttpRequest"},
			load: function(data,ioargs){  
				if(data.result == "1"){ 
					showStatus(); 
				}else{
					for(var k in data.errors){ 
						if(k == 'logged_out'){
							window.location.assign(data.errors[k]);
						} else {
							dojo.byId(k).innerHTML = data.errors[k];
						}
					}
					
					// if submit button was disabled, remove the attribute.
					var update_submit = dojo.byId('edit_status_submit'); 
					if (update_submit && dojo.hasAttr(update_submit, "disabled")) {
						dojo.removeAttr(update_submit, "disabled");
					}
				} 
				
				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 status form. Please try again!");
				/* handle the error... */ 
	            return response; //always return the response back 
			}
		});
	} else {
		// if submit button was disabled, remove the attribute.
		var update_submit = dojo.byId('edit_status_submit'); 
		if (update_submit && dojo.hasAttr(update_submit, "disabled")) {
			dojo.removeAttr(update_submit, "disabled");
		}
	}
	
	return false;
}

// valide personal info field.
function isValid(category_id, description_id) {
	var errors = 0;
	
	// validate category and description. 
	var category = dojo.byId(category_id);
	var description = dojo.byId(description_id); 
	
	if (dojo.hasClass(category, 'profile_details_empty')) {
		dojo.byId(category_id+'_error').innerHTML = "Topic is required.";
		errors++;
	} else {
		if(category.value.length > 255){
			dojo.byId(category_id+'_error').innerHTML = "Maximum 255 characters are allowed."; 
			errors++;  
		}else{  
			dojo.byId(category_id+'_error').innerHTML = ""; 
		}
	}
	
	if (dojo.hasClass(description, 'profile_details_empty')) {
		dojo.byId(description_id+'_error').innerHTML = "Description is required";
		errors++;
	} else {
		if(description.length > 1000){
			dojo.byId(description_id+'_error').innerHTML = "Maximum 1000 characters are allowed."; 
			errors++;  
		}else{  
			dojo.byId(description_id+'_error').innerHTML = ""; 
		} 
	}
 
	// validate form.
	if(errors == 0){  
		return true;
	} else {
		return false;
	}
}

// send add profile info form after validation.
function sendAddProfileForm(){    
	if (isValid('profile_category', 'description')) { 
		dojo.xhrPost({
			url: "/user/profile/add-personal/format/json", 
			form: "user_profile_create",  
			handleAs: "json",
			sync: true,
			headers: {"X-Requested-With": "XMLHttpRequest"},
			load: function(data,ioargs){  
				if(data.result == "1"){ 
					showProfileInfo();
				}else{
					for(var k in data.errors){ 
						if(k == 'logged_out'){
							window.location.assign(data.errors[k]);
						} else {
							dojo.byId(k).innerHTML = data.errors[k];
						}
					}
					
					// if submit button was disabled, remove the attribute.
					var create_submit = dojo.byId('add_profile_submit');   
					if (create_submit && dojo.hasAttr(create_submit, "disabled")) {
						dojo.removeAttr(create_submit, "disabled");
					} 
				} 
				
				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 {
		// if submit button was disabled, remove the attribute.
		var create_submit = dojo.byId('add_profile_submit');   
		if (create_submit && dojo.hasAttr(create_submit, "disabled")) {
			dojo.removeAttr(create_submit, "disabled");
		}
	}
	
	return false; 
}

//cancel edit profile form and return to view status.
function initializeViewProfileInfo() { 
	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 default_topic  = "Enter a Topic you'd like to talk about!";
    
	var profile_body = dojo.byId('description');
	var profile_topic = dojo.byId('profile_category');
	
	if (profile_body) {
		profile_body.value = default_profile;
		dojo.addClass(profile_body, "profile_details_empty");
		
		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");
						}
						
		});
	}

	if (profile_topic) {
		profile_topic.value = default_topic;
		dojo.addClass(profile_topic, "profile_details_empty");
		
		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");
						}
						
		});
	}
	
    dojo.query(".delete_personal_info").forEach(function(node, i){  
		var pid = dojo.attr(node, "alt");
		dojo.connect(node, 
				   "onclick",
				    function(e){ 
						e.preventDefault(); 
						dojo.attr(node, "disabled", "disabled"); 
						deletePersonalInfo("/user/profile/delete-personal/pid/"+pid, pid); 
				    });
		
	});
    
    dojo.query(".edit_personal_info").forEach(function(node, i){ 
		var pid = dojo.attr(node, "alt");
		dojo.connect(node, 
				   "onclick",
				    function(e){ 
						e.preventDefault(); 
						dojo.attr(node, "disabled", "disabled"); 
						editPersonalInfo("/user/profile/edit-each-personal/pid/"+pid, pid); 
				    });
		
	});
	
    var create_submit = dojo.byId('add_profile_submit');   
	dojo.connect(create_submit,
			   "onclick",
			    function(e){ 
					e.preventDefault(); 
					dojo.attr(create_submit, "disabled", "disabled"); 
					sendAddProfileForm(); 
			    }); 
}

// cancel edit profile form and return to view status.
function showProfileInfo() {  
	var uid = dojo.byId('profile_info_uid').value;
	 
	dojo.xhrGet({ 
	 	url: "/user/profile/view-personal/uid/"+uid+"/format/text",  //the relative URL  
	 	handleAs: "text",
	 	sync: true,
	 	// run this function if the request is successful 
        load : function(response, ioArgs) { 
            // set some element's content... 
            dojo.byId("user_profile_info").innerHTML= response;  
           
            if (dijit.byId("profile_category")) {
            	dijit.byId("profile_category").destroy(); 
            }
            
            dojo.parser.parse(dojo.byId('user_profile_info'));
            
            initializeViewProfileInfo();
    		
            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 form. Please try again!");
            /* handle the error... */ 
            return response; //always return the response back 
        } 
	});  
}

// delete a personal info.
function deletePersonalInfo(link, pid){ 
	if (confirm("Are you sure you want to delete this profile information?")) { 
		dojo.xhrGet({ 
			url: link+"/format/json",   
			handleAs: "json",
			sync: true,
			headers: {"X-Requested-With": "XMLHttpRequest"},
			load: function(data,ioargs){  
				if(data.result == "1"){  
					//dojo.byId("info_"+pid).style.display = "none";  
					showProfileInfo();
				}else{
					for(var k in data.errors){ 
						if(k == 'logged_out'){
							window.location.assign(data.errors[k]);
						} else {
							
						}
					} 
					
					// disable the delete link while ajax call is made. 
					var delete_link = dojo.byId('delete_profile_'+pid); 
					if (delete_link) { 
						dojo.attr(delete_link, "disabled", "disabled");  
					} 
				} 
				
				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 
			}
		});
	} 
	
	return false; 
} 

// edit a personal info.
function editPersonalInfo(link, pid){ 
	// disable the edit link while ajax call is made. 
	dojo.attr(dojo.byId('edit_profile_'+pid), "disabled", "disabled");  
	
	dojo.xhrGet({ 
	 	url: link+"/format/text",  //the relative URL  
	 	handleAs: "text",
	 	sync: true,
	 	// run this function if the request is successful 
        load : function(response, ioArgs) { 
            // set some element's content... 
            dojo.byId("info_"+pid).innerHTML= response; 
            
            if (dijit.byId("new_category_name_"+pid)) {
            	dijit.byId("new_category_name_"+pid).destroy(); 
            }
            
            dojo.parser.parse(dojo.byId("info_"+pid));
            
            // initiate edit profile info form submit.
    		initializeEditProfileInfoForm(pid);
    		
            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 form. Please try again!");
            /* handle the error... */ 
            return response; //always return the response back 
        } 
	});   
	 
	return false; 
} 

// initialize edit profile info form on profile page.
function initializeEditProfileInfoForm(pid) {  
	// submit form by ajax.
	var update_submit = dojo.byId('edit_profile_submit_'+pid); 

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

	// only connect the js action if the cancel button is available.
	if (update_cancel) { 
		dojo.connect(update_cancel, 
				   "onclick",
				    function(e){ 
						e.preventDefault();
						dojo.attr(update_cancel, "disabled", "disabled");
						showEachProfileInfo(pid); 
		});
	} 
} 

// send edit profile info form after validation.
function sendEditProfileForm(pid) { 
	if (isValid('new_category_name_'+pid, 'description_'+pid)) { 
		dojo.xhrPost({
			url: "/user/profile/edit-each-personal/format/json", 
			form: "user_profile_update_"+pid,  
			handleAs: "json",
			sync: true,
			headers: {"X-Requested-With": "XMLHttpRequest"},
			load: function(data,ioargs){  
				if(data.result == "1"){ 
					showEachProfileInfo(pid);
				}else{
					for(var k in data.errors){ 
						if(k == 'logged_out'){
							window.location.assign(data.errors[k]);
						} else {
							dojo.byId(k).innerHTML = data.errors[k];
						}
					} 
					
					// if submit button was disabled, remove the attribute.
					var update_submit = dojo.byId('edit_profile_submit_'+pid);  
					if (update_submit && dojo.hasAttr(update_submit, "disabled")) {
						dojo.removeAttr(update_submit, "disabled");
					}
				} 
				
				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 {
		// if submit button was disabled, remove the attribute.
		var update_submit = dojo.byId('edit_profile_submit_'+pid);  
		if (update_submit && dojo.hasAttr(update_submit, "disabled")) {
			dojo.removeAttr(update_submit, "disabled");
		}
	}
	
	return false; 
}

// cancel edit each profile form and return to view status.
function showEachProfileInfo(pid) {   
	var uid = dojo.byId('profile_info_uid').value;
	 
	dojo.xhrGet({ 
	 	url: "/user/profile/view-each-personal/uid/"+uid+"/pid/"+pid+"/format/text",  //the relative URL  
	 	handleAs: "text",
	 	sync: true,
	 	// run this function if the request is successful 
        load : function(response, ioArgs) { 
            // set some element's content... 
		    dojo.byId("info_"+pid).innerHTML= response;
             
		    dojo.connect(dojo.byId('delete_profile_'+pid), 
					   "onclick",
					    function(e){ 
							e.preventDefault();  
							dojo.attr(dojo.byId('delete_profile_'+pid), "disabled", "disabled"); 
							deletePersonalInfo("/user/profile/delete-personal/pid/"+pid, pid);
					    });
		    
		    dojo.connect(dojo.byId('edit_profile_'+pid),
					   "onclick",
					    function(e){ 
							e.preventDefault(); 
							dojo.attr(dojo.byId('edit_profile_'+pid), "disabled", "disabled"); 
							editPersonalInfo("/user/profile/edit-each-personal/pid/"+pid, pid);  
					    }); 
			
            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 form. Please try again!");
            /* handle the error... */ 
            return response; //always return the response back 
        } 
	});  
}

//---------------------- EDIT MY ACCOUNT FUNCTIONS -------------------------  

// update avatar in signup form.
function updateAvatar(name) { 
	var current_name = dojo.byId('profile_selected_avatar').value;
	var new_avatar_node = dojo.byId(name+'_img');
	var current_avatar_node = dojo.byId(current_name+'_img');
	
	if(current_name!=name){
		dojo.byId('profile_selected_avatar').value = name;
		dojo.addClass(new_avatar_node, "selected_avatar");
		dojo.removeClass(current_avatar_node, "selected_avatar");
	} 
} 

// profile account edit form submission.
function sendEditAccountForm() {   
	var errors = 0;
	
	// validate email.
	var email_field = dojo.byId('profile_email'); 
	if (email_field) {  
		if (!validateEmail(email_field.value, true, 'profile_email_error')) {
			errors++;
			dojo.byId("profile_email_valid").style.display = "none";
			dojo.byId("profile_email_invalid").style.display = "block";
			
			email_field.focus();
		} else {
			dojo.byId("profile_email_invalid").style.display = "none";
			dojo.byId("profile_email_valid").style.display = "block";
		}
	} 
	 
	// validate new password.
	var passwd_field = dojo.byId('profile_passwd'); 
	
	if(passwd_field.value.length == 0){
		// no new password is entered.
		dojo.byId('profile_password_error').innerHTML = '<span>Leave blank to keep the same password</span>';
		dojo.removeClass(dojo.byId('profile_password_error'), "field_error");
		
		dojo.byId("profile_password_invalid").style.display = "none";
		dojo.byId("profile_password_valid").style.display = "none";
		
		dojo.byId('profile_verify_error').innerHTML = "";
		dojo.byId("profile_verify_invalid").style.display = "none";
		dojo.byId("profile_verify_valid").style.display = "none";
	}else{
		if (!validatePassword(passwd_field.value, false, 'profile_password_error')) {
			if (errors == 0) { 
				passwd_field.focus();
			}
			
			errors++;
			dojo.addClass(dojo.byId('profile_password_error'), "field_error");
			dojo.byId("profile_password_invalid").style.display = "block";
			dojo.byId("profile_password_valid").style.display = "none"; 
		} else {
			dojo.byId("profile_password_invalid").style.display = "none";
			dojo.byId("profile_password_valid").style.display = "block";
			
			// continue validating verify password.
			var verify_passwd = dojo.byId('profile_verify').value;
			var passwd2_p = dojo.byId('profile_verify_error');
			if(verify_passwd.length == 0){
				if (errors == 0) {
					dojo.byId('profile_verify').focus();
				}
				
				errors++;  
				passwd2_p.innerHTML = "Please verify your password."; 
				
				dojo.byId("profile_verify_invalid").style.display = "block";
				dojo.byId("profile_verify_valid").style.display = "none";
			}else{  
				if(verify_passwd!=passwd_field.value){
					if (errors == 0) {
						dojo.byId('profile_verify').focus();
					}
					
					errors++; 
					passwd2_p.innerHTML = "Password doesn't match! CAPS might be on! Please re-enter your new password to verify.";
					
					dojo.byId("profile_verify_invalid").style.display = "block";
					dojo.byId("profile_verify_valid").style.display = "none";
				}else{ 
					passwd2_p.innerHTML = ""; 
					
					dojo.byId("profile_verify_invalid").style.display = "none";
					dojo.byId("profile_verify_valid").style.display = "block";
				}
			}
		} 
	} 
	 
	// validate form.
	if(errors > 0){ 
		return false;
	}else{ 
		return true;
	} 
} 

//---------------------- SIDEBAR (BEFORE LOGIN)::LOGIN/FORGOT-PASSWORD FUNCTIONS -------------------------

// show forgot password form.
function showForgotForm() {  
	var email = dojo.byId('forgot_email');
	
	if (email) {
		email.value = "";
	}
	
	dojo.byId('login_form_section').style.display = "none"; 
	dojo.byId('forgotpasswd_form_section').style.display = "block"; 
	dojo.byId("forgot_form_field").style.display = "block";
	
	dojo.byId("forgot_form_success_container").style.display = "none"; 					
	dojo.byId('forgot_form_error_msg').innerHTML = "";
	dojo.byId('forgot_form_success_msg').innerHTML = ""; 
} 

// show login form.
function showLoginForm() {  
	dojo.byId('login_passwd').value = "";
	
	dojo.byId('forgotpasswd_form_section').style.display = "none"; 
	dojo.byId('login_form_section').style.display = "block";
	
	dojo.byId('login_form_error_msg').innerHTML = ""; 
	dojo.query(".login_error").innerHTML = ""; 
}

// forgot password form submission.
function sendForgotForm() {   
	var errors = 0; 
	
	dojo.byId("forgot_form_success_msg").innerHTML = "";
	
	// validate email.
	var email = dojo.byId('forgot_email').value;
	var email_filter  = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
	if(email=='' || !email_filter.test(email)){
		errors++; 
		
		if(email==''){
			dojo.byId('forgot_form_error_msg').innerHTML = "Please enter the email you signed up with.";
		}else if(!email_filter.test(email)){
			dojo.byId('forgot_form_error_msg').innerHTML = "Please enter a valid email address.";
		}
		dojo.byId('forgot_form_error_msg').style.display = "block";
	}else{ 
		dojo.byId('forgot_form_error_msg').innerHTML = "";
	} 
	
	// validate form.
	if(errors == 0){ 
		dojo.byId("forgot_form_error_msg").innerHTML = "";
		
		dojo.xhrPost({
			url: "/user/authentication/forgot-password/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{
					for(var k in data.errors){ 
						if(k == 'general'){
							dojo.byId('forgot_form_error_msg').innerHTML = data.errors[k];
							dojo.byId('forgot_form_error_msg').style.display = "block";
						}else{ 
							dojo.byId(k+"_after").innerHTML = data.errors[k];
							dojo.byId(k+"_after").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 
	        }
		});
	} 
}

//---------------------- SIGN-UP OVERLAY FORM FUNCTIONS -------------------------
 
// calculate age.
function getAge(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; 
}

// update number of days based on selected year and month.
function calenderDays(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"); 
	} 
}

// update avatar in signup form.
function selectAvatar(name) { 
	var current_name = dojo.byId('signup_avatar').value;
	var new_avatar_node = dojo.byId(name+'_img');
	var current_avatar_node = dojo.byId(current_name+'_img');
	
	if(current_name!=name){
		dojo.byId('signup_avatar').value = name;
		dojo.addClass(new_avatar_node, "selected_avatar");
		dojo.removeClass(current_avatar_node, "selected_avatar");
	} 
}  

// validate username field.
function validateUsername(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;
	}  
}

// validate email field.
function validateEmail(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;
	} 
}

// validate password field.
function validatePassword(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;
	}  
}

// validate parent email field.
function validateSignupParent() {  
	var errors = 0;
	
	var email = dojo.byId('signup_email').value;
	var parent_email = dojo.byId('signup_parent_email').value; 
	var email_filter  = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
	var parent_email_p = dojo.byId('signup_parent_email_after'); 
	if(parent_email=='' || !email_filter.test(parent_email) || (parent_email == email)){
		errors++;
		 
		if(parent_email==''){ 
			parent_email_p.innerHTML = "A parent's email is required."; 
		}else if(!email_filter.test(parent_email)){
			parent_email_p.innerHTML = "Please enter a valid email address.";
		}else if(parent_email!='' && parent_email == email){
			parent_email_p.innerHTML = "You entered the same email for yourself and your parents.";
		}
		
		parent_email_p.style.display = "block";
		//dojo.byId("signup_parent_invalid").style.display = "block";
		//dojo.byId("signup_parent_valid").style.display = "none";
	}else{ 
		parent_email_p.innerHTML = "";
		parent_email_p.style.display = "none";
		//dojo.byId("signup_parent_invalid").style.display = "none";
		//dojo.byId("signup_parent_valid").style.display = "block";
	} 
	
	// validate form.
	if(errors > 0){
		return false;
		 
	}else{
		return true;
	}
}

// validate birthday
var validateSignupBirthday = function(){  
	var errors = 0;
	
	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;
	var birth_p = dojo.byId('signup_birth_p'); 
	
	if(birth_m != '00' && birth_d != '00' && birth_y != '0000'){  
		dojo.byId("signup_birthday_after").innerHTML = ""; 
		
		//dojo.byId("signup_birth_invalid").style.display = "none";
		//dojo.byId("signup_birth_valid").style.display = "block";
		
		// check age. 
		var current_age = getAge(parseInt(birth_y), parseInt(birth_m), parseInt(birth_d));  
		var parent_email_p = dojo.byId('signup_parent_email_after'); 
		
		//dojo.byId("signup_parent_invalid").style.display = "none";
		//dojo.byId("signup_parent_valid").style.display = "none";
		
		if(current_age <= 13){
			dojo.byId("parent_email").style.display = "";
			
			// validate parent_ email.
			if (!validateSignupParent()) {
				errors++;
			} 
		}else{  
			dojo.byId("parent_email").style.display = "none"; 

			dojo.byId('signup_parent_email').value = ""; 
			parent_email_p.innerHTML = ""; 
		}  
	} else {
		errors++;   
		dojo.byId("signup_birthday_after").innerHTML = "Your birthday is required."; 
		
		//dojo.byId("signup_birth_invalid").style.display = "block";
		//dojo.byId("signup_birth_valid").style.display = "none";
	} 
	
	// validate form.
	if(errors > 0){
		return false; 
	}else{
		return true;
	} 
}
 
//---------------------- RESET-PASSWORD FUNCTIONS -------------------------

// reset password form submission.
function sendResetPasswordForm() {   
	// count errors.
	var errors = 0;
    
	// get reset password form.
	var resetForm = dojo.byId('reset_password_form');
	
	// validate password.
	var passwd_field = dojo.byId('reset_new_password'); 
	if (passwd_field) {  
		if (!validatePassword(passwd_field.value, true, 'reset_new_password_after')) {
			errors++;
			dojo.byId("reset_new_password_valid").style.display = "none";
			dojo.byId("reset_new_password_invalid").style.display = "block";
		} else {
			dojo.byId("reset_new_password_invalid").style.display = "none";
			dojo.byId("reset_new_password_valid").style.display = "block";
			
			// continue validating verify password.
			var verify_passwd = dojo.byId('reset_verify_password').value;
			var passwd2_p = dojo.byId('reset_verify_password_after');
			if(verify_passwd.length == 0){
				errors++;  
				passwd2_p.innerHTML = "Please verify your new password.";
				
				dojo.byId("reset_verify_password_invalid").style.display = "block";
				dojo.byId("reset_verify_password_valid").style.display = "none";
			}else{  
				if(verify_passwd!=passwd_field.value){
					errors++; 
					passwd2_p.innerHTML = "Password doesn't match! CAPS might be on! Please re-enter your new password to verify.";
					
					dojo.byId("reset_verify_password_invalid").style.display = "block";
					dojo.byId("reset_verify_password_valid").style.display = "none";
				}else{ 
					passwd2_p.innerHTML = ""; 
					
					dojo.byId("reset_verify_password_invalid").style.display = "none";
					dojo.byId("reset_verify_password_valid").style.display = "block";
				}
			}
		}
	}
	 
	// validate form.
	if(errors > 0){
		return false;	 
	}else{ 
		if (resetForm) {
			resetForm.submit();
		} 
	} 
}

//---------------------- PARENT CONSENT FUNCTIONS -------------------------

// allow child to log in the site.
function sendYesParentForm()
{  
	dojo.byId('parent_agreement').value = 1;
	
    var parentForm = dojo.byId('parent_consent_form');
	parentForm.submit();
}

// disallow child to log in the site.
function sendNoParentForm()
{  
	dojo.byId('parent_agreement').value = 0;
	
	var parentForm = dojo.byId('parent_consent_form');
	parentForm.submit();
} 

//---------------------- PRIVATE MESSAGE COMPOSE FUNCTIONS -------------------------
 
//remove a recipient.
function removeRecipient(xClick)
{
	var remove_id = xClick.target.id;
    var remove_user = dojo.byId(remove_id); 
	var remove_username = dojo.attr(remove_user, "alt");
	 
	var total = totalRecipients();
		
	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';
		} else {
			select.promptMessage = '';
			select.invalidMessage = '';
		} 
		
  		select.setDisabled(false); 
  		select.textbox.value = '';
  		select.focus();
   	}  
}

// add a recipient.
function addRecipient(id, username)
{
	// add to hidden recipients list.
	var hiddenRecipients = dojo.byId('hidden_recipients');
		
    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');
 
	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", removeRecipient);
			    
	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');
				}  
			} 
		}  
	}); 
}

// count total recipients added to the message.
function totalRecipients()
{
   var total = 0;
    	 
   // check the maximum recipients. 
   dojo.query("div#hidden_recipients input.hidden_to").forEach(function(node, i){
   		total++;
   });

   return total;
}

// clear username input field.
function clearUsername(select)
{ 
    if (!select.isValid()) {
    	select.textbox.value = "";
    } else {
    	select.focus();
    }
}

// check username is available from the options.
function checkUsername(select)
{ 
	var user_id = select.getValue();
	var username = select.textbox.value; 
	var total = totalRecipients();
		 
    if (user_id && username) {   
	   	if (total < 20) { 
	   		// add the user to recipient container. 
	  		addRecipient(user_id, username);
	  		select.promptMessage = '';
			select.invalidMessage = '';
			total++;  
	   	} 

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

	  	if (total >= 20) {
	  		select.promptMessage = 'You\'ve added the maximum recipients';
	  		select.setDisabled(true);
	  	}
    }
} 

//---------------------- COMMENT FUNCTIONS -------------------------

// send comment form after validation.
function sendCommentForm() {   
	var errors = 0;
	
	// validate status. 
	var comment_input = trimAll(dojo.byId('comment_input').value); 
	dojo.byId('coment_error_list').innerHTML = ""; 
	
	if (comment_input.length < 10) {
		var errorItem = document.createElement('li');
		errorItem.innerHTML = "Your comment is too short. (10 characters minimum)";
		dojo.byId('coment_error_list').appendChild(errorItem); 
		errors++;  
	}
	
	// validate form.
	if (errors == 0) {  
		dojo.xhrPost({
			url: "/messaging/comment/add/format/json", 
			form: "comment_form", 
			handleAs: "json",
			sync: true,
			headers: {"X-Requested-With": "XMLHttpRequest"},
			load: function(data,ioargs){  
				if(data.result == "1"){ 
					// clear the field.
					dojo.byId('comment_input').value = "";
					dojo.byId('coment_error_list').innerHTML = "";
					dojo.byId('comment_characters_remaining').innerHTML = "1000 characters remaining";
					
					// load the updated comment list. 
					loadComments('comment_list', '/messaging/comment/list'); 
				}else{
					var comment_errors = dojo.byId('coment_error_list');
					
					if (comment_errors) {
						comment_errors.innerHTML = "";
						
						for(var k in data.errors){ 
							var errorItem = document.createElement('li');
							errorItem.innerHTML = data.errors[k];
							comment_errors.appendChild(errorItem); 
						}
					} 
					
					// if submit button was disabled, remove the attribute.
					var update_submit = dojo.byId('submit_btn');   
					if (update_submit && dojo.hasAttr(update_submit, "disabled")) {
						dojo.removeAttr(update_submit, "disabled");
					}
				} 
				
				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 status form. Please try again!");
				/* handle the error... */ 
	            return response; //always return the response back 
			}
		});
	} else {
		// if submit button was disabled, remove the attribute.
		var update_submit = dojo.byId('submit_btn');   
		if (update_submit && dojo.hasAttr(update_submit, "disabled")) {
			dojo.removeAttr(update_submit, "disabled");
		}
	}
	
	return false;
}

// load comments.
function loadComments(list_id, href) {   
	var commentList = dojo.byId(list_id);
	
	if (commentList) {
		dojo.xhrGet({ 
			url: href+"/format/json/",
			handleAs: "text",
		 	sync: true,
		 	// run this function if the request is successful 
	        load : function(response, ioArgs) { 
	            // set some element's content... 
				commentList.innerHTML = response; 
				
				dojo.query(".comment_paginator").forEach(function(node, i){  
					var page = dojo.attr(node, "alt");  
					var href = '/messaging/comment/list/page/'+page;
					dojo.connect(node, 
							   "onclick",
							    function(e){ 
									e.preventDefault();
									loadComments('comment_list', 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 
	        } 
		});
	}
	 
	return false;
}

// hook event to add comment.
function addComment() { 
	// submit form by ajax.
	var update_submit = dojo.byId('blog_submit_comment_btn');  

	// only connect the js action if the submit button is available.
	if (update_submit) { 
		dojo.connect(update_submit,
				    "onclick",
				    function(e){ 
						e.preventDefault(); 
						dojo.attr(update_submit, "disabled", "disabled");
						sendAjaxCommentForm(); 
		}); 
	}  
	
	// hook text character length aid.
    var comment_input = dojo.byId('comment_input'); 
    if (comment_input) {   
    	dojo.connect(comment_input, 
		    		"onkeyup",
		    		function(){  
						countTextarea(comment_input, "comment_characters_remaining", update_submit, 1000);
    	}); 
    	
    	var numChars = dojo.number.parse(comment_input.value.length);
    	var remainingChars = dojo.byId('comment_characters_remaining');  
        var currentValue = parseInt(1000) - numChars; 
        
    	remainingChars.innerHTML = currentValue + " characters remaining"; 
    }
}

// view comments.
function loadAjaxComments(list_id, href, loading) {   
	var commentList = dojo.byId(list_id);
	
	if (commentList) { 
		// hide comment list.
		if (loading) {
			dojo.byId("the_comment_list_thing").style.display = "none"; 
			dojo.byId("comments_please_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... 
				commentList.innerHTML = response; 
				
				dojo.query(".comment_paginator").forEach(function(node, i){  
					var href = dojo.attr(node, "alt"); 
					dojo.connect(node, 
							   "onclick",
							    function(e){ 
									e.preventDefault();
									loadAjaxComments('comment_load_ajax', href, true);
							    }); 
				});
				
				// initiate ajax link to thumb up a post.
				dojo.query(".rate_up").forEach(function(node, i){  
					dojo.connect(node, 
							   "onclick",
							    function(e){ 
									e.preventDefault(); 
									dojo.attr(node, "disabled", "disabled"); 
									ratePost(node, 1); 
							    }); 
				});

				// initiate ajax link to thumb down a post.
				dojo.query(".rate_down").forEach(function(node, i){  
					dojo.connect(node, 
							   "onclick",
							    function(e){ 
									e.preventDefault(); 
									dojo.attr(node, "disabled", "disabled");
									ratePost(node, -1);
							    }); 
				});
				
				addComment();
				
				if (loading) {
					dojo.byId("the_comment_list_thing").style.display = ""; 
					dojo.byId("comments_please_wait").style.display = "none"; 
				}
				
	            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); 
	            
	            if (loading) {
					dojo.byId("the_comment_list_thing").style.display = ""; 
					dojo.byId("comments_please_wait").style.display = "none"; 
				}
	            
	            alert("ERROR: There was an error while submitting your request. Please try again!");
	            /* handle the error... */ 
	            return response; //always return the response back 
	        } 
		});
	}
	 
	return false;
}

//send comment form after validation.
function sendAjaxCommentForm() {   
	var errors = 0;
	
	// validate status. 
	var comment_input = trimAll(dojo.byId('comment_input').value); 
	dojo.byId('comment_form_errors').innerHTML = ""; 
	
	if (comment_input.length < 10) {
		var errorItem = document.createElement('li');
		errorItem.innerHTML = "Your comment is too short. (10 characters minimum)";
		dojo.byId('comment_form_errors').appendChild(errorItem); 
		errors++;  
	}
	
	// validate form.
	if (errors == 0) {  
		dojo.byId("comment_form_section").style.display = "none"; 
		dojo.byId("comment_submit_please_wait").style.display = "";  
		
		dojo.xhrPost({
			url: "/messaging/comment/add-comment/format/json", 
			form: "comment_form", 
			handleAs: "json",
			sync: true,
			headers: {"X-Requested-With": "XMLHttpRequest"},
			load: function(data,ioargs){  
				if(data.result == "1"){ 
					// clear the field.
					dojo.byId('comment_input').value = "";
					dojo.byId('comment_form_errors').innerHTML = "";
					dojo.byId('comment_characters_remaining').innerHTML = "1000 characters remaining";
					
					var parent_id = dojo.byId('parent_id').value;
					var parent_type_id = dojo.byId('parent_type_id').value;
						
					dojo.byId('comment_input').value = "";
					
					dojo.byId("comment_form_section").style.display = ""; 
					dojo.byId("comment_submit_please_wait").style.display = "none";  
					
					// load the updated comment list. 
					loadAjaxComments('comment_load_ajax', '/messaging/comment/get-comments/parent_type_id/'+parent_type_id+'/parent_id/'+parent_id, false); 
				}else{
					dojo.byId("comment_form_section").style.display = ""; 
					dojo.byId("comment_submit_please_wait").style.display = "none";  
					
					var comment_errors = dojo.byId('comment_form_errors');
					
					if (comment_errors) {
						comment_errors.innerHTML = "";
						
						for(var k in data.errors){ 
							var errorItem = document.createElement('li');
							errorItem.innerHTML = data.errors[k];
							comment_errors.appendChild(errorItem);  
						}
					} 
					
					// if submit button was disabled, remove the attribute.
					var update_submit = dojo.byId('blog_submit_comment_btn');   
					if (update_submit && dojo.hasAttr(update_submit, "disabled")) {
						dojo.removeAttr(update_submit, "disabled");
					}
				} 
				
				return data; //always return the response back 
			},
			// if any error occurs, it goes here:
			error: function(response, ioArgs){
				dojo.byId("comment_form_section").style.display = ""; 
				dojo.byId("comment_submit_please_wait").style.display = "none";  
				
				console.log("failed xhrPost", response, ioArgs);
				 
				alert("ERROR: There was an error while submitting your status form. Please try again!");
				/* handle the error... */ 
	            return response; //always return the response back 
			}
		});
	} else {
		// if submit button was disabled, remove the attribute.
		var update_submit = dojo.byId('blog_submit_comment_btn');   
		if (update_submit && dojo.hasAttr(update_submit, "disabled")) {
			dojo.removeAttr(update_submit, "disabled");
		}
	}
	
	return false;
}

//---------------------- BUG REPORT FUNCTIONS -------------------------

// bug report form submission.
function sendBugReportForm() {   
	var errors = 0;
	
	// validate body.
	var body = trimAll(dojo.byId('BugReportDescription').value); 
	if (body.length == 0) {
		errors++;
		dojo.byId('description_after').innerHTML = "Bug description is required.";
	} else {
		dojo.byId('description_after').innerHTML = "";
	}
	 
	// validate form.
	if(errors > 0){ 
		return false;
	}else{ 
		return true;
	} 
} 

//---------------------- FEEDBACK FUNCTIONS -------------------------

// feedback form submission.
function sendFeedbackForm() {   
	var errors = 0;
	
	// validate body.
	var body = trimAll(dojo.byId('FeedbackDescription').value); 
	if (body.length == 0) {
		errors++;
		dojo.byId('description_after').innerHTML = "Please write something first.";
	} else {
		dojo.byId('description_after').innerHTML = "";
	}
	 
	// validate form.
	if(errors > 0){ 
		return false;
	}else{ 
		return true;
	} 
} 

//---------------------- CONTENT FUNCTIONS -------------------------
 
// toggle newsletter
function toggleNewsletter(value) {  
	dojo.xhrGet({ 
	 	url: "/user/profile/toggle-newsletter/new_value/"+value+"/format/text",  //the relative URL  
	 	handleAs: "text",
	 	sync: true,
	 	// run this function if the request is successful 
        load : function(response, ioArgs) { 
			if ( value == 1 ){
				try {
				var googleTracker = _gat._getTracker(Z2h.tracking_id);
				googleTracker._trackPageview('/form/newsletter/confirm/');
				} catch (err){}
			}
            // set some element's content... 
            dojo.byId("toggle_newsletter").innerHTML= response; 
            
            // connect the onclick even again.
            dojo.query('input[name=newsletter]').forEach(function(obj) {
        		dojo.connect(obj, 'onclick', function(evt) {
        			toggleNewsletter(evt.target.value); 
        		});
        	});
            
            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 form. Please try again!");
            /* handle the error... */ 
            return response; //always return the response back 
        } 
	});   
	 
	return false; 
}

// @todo: plan to create a generic z2h widgets
Z2h = {};

//initialize application-wide js functions
Z2h.global = {
	init: function() {
		Z2h.link.init(); 
		Z2h.inbox.init();
		Z2h.inbox.recipients.init(); 
	}
}

//---------------------- CONTENT RATING FUNCTIONS -------------------------

Z2h.rating = {
	isShown: false,	
	
	init: function() {  
		dojo.query('.hidden_show').forEach(function(node){
			dojo.connect(node, 'onmouseover', Z2h.rating.show);
		});
		
		dojo.query('.hidden_hide').forEach(function(node){
			dojo.connect(node, 'onmouseout', Z2h.rating.hide);
		});

		dojo.query('.send_rating').forEach(function(node){
			dojo.connect(node, 'onclick', Z2h.rating.vote);
		}); 
	}, 
		
	show: function(e) {
		e.preventDefault();
	 
		var number = e.target.title;
		if ( number == "" ){
			number = e.target.parentNode.title;
		}
		
		dojo.query(".rating_image").forEach(function(node){
			if ( parseInt(node.alt) <= parseInt(number) ) {
				node.src = "/images/icons/star_15x15.gif";
			}
		});
		
		var showNumber = dojo.byId("rating_change");
		if ( showNumber ) {
			showNumber.innerHTML = number;
		}	
		if ( !Z2h.rating.isShown ) {
			dojo.byId('rating_top').style.display = "none";
			dojo.byId('rating_bottom').style.display = "block";
			Z2h.rating.isShown = true;
		} 
	},
	
	hide: function(e) {
		e.preventDefault();
	 
		if ( Z2h.rating.isShown ) {
			dojo.byId('rating_top').style.display = "block";
			dojo.byId('rating_bottom').style.display = "none";
			Z2h.rating.isShown = false;
		}
		
		dojo.query(".rating_image").forEach(function(node){
				node.src = "/images/icons/star_gray_15x15.gif";
		}); 
	},
	
	vote: function(e) {
		e.preventDefault(); 
		
		var clicked = e.target;
		while ( clicked.localName != "A" ) {
			clicked = clicked.parentNode;
		}

		var rating = clicked.title;

		dojo.xhrPost({
			url: clicked.href + "/format/json",
			handleAs: 'json',
			headers: {"X-Requested-With": "XMLHttpRequest"},
			load: function(response,ioArgs){
				if ( response.result == "1") {
					var ratingDiv = dojo.byId("rating_bottom");
					ratingDiv.innerHTML = '\n<ul class="rating_container" style="margin:0px;">';
					for ( var i=1; i<=5; i++ ) {
						if ( i<=rating ) {
							ratingDiv.innerHTML += '<li><a class="hidden_hide" title="'+i+'.0"><img class="hidden_hide" src="/images/icons/star_15x15.gif" /></a></li>';
						} else {
							ratingDiv.innerHTML += '<li><a class="hidden_hide" title="'+i+'.0"><img class="hidden_hide" src="/images/icons/star_gray_15x15.gif" /></a></li>';
						}				
					}
					ratingDiv.innerHTML += '\n</ul>\n\t\t<p class="number_rating">'+rating+'</p>';				
				} else {
					var errorDiv = dojo.byId("rating_errors");
					errorDiv.style.display = "block";
					errorDiv.innerHTML = response.errors;
				}
				return false;
			},
			error: function(err,ioArgs){
				alert("Unable to rate item, please try again!");
				//console.log(err);
				//console.log(ioArgs);
				return false;
			}	
		});
		
		return false; 
	}
}
//---------------------- CREATIONS COMMENT FUNCTIONS -------------------------
Z2h.creations = {
	_running: false,
		
	init: function() {  
		var thumb_editor = dojo.byId('fanfiction_thumb_editor');
		var title_editor = dojo.byId('fanfiction_title_editor');
	
		var thumb_editor_link = dojo.byId('update_fanfiction_thumb');
		if (thumb_editor_link) {
			dojo.connect(thumb_editor_link, 
			    		"onclick",
			    		function(e){ 
							e.preventDefault(); 
							
							if (thumb_editor && title_editor) {
								title_editor.style.display = "none"; 
								thumb_editor.style.display = ""; 
							} 
	    	});  
		}
		
		var title_editor_link = dojo.byId('update_fanfiction_title');
		if (title_editor_link) { 
			dojo.connect(title_editor_link, 
			    		"onclick",
			    		function(e){ 
							e.preventDefault(); 
						 
							if (thumb_editor && title_editor) {
								thumb_editor.style.display = "none"; 
								title_editor.style.display = ""; 
							} 
			}); 
		}
		
		// hook onclick event to submit form to update fan fiction thumb form.
		var update_thumb_btn = dojo.byId('fanfiction_thumb_submit');
		if (update_thumb_btn) {
			dojo.connect(update_thumb_btn, 'onclick', Z2h.creations.updateThumb);
		}  
	
		// for safari, hook onsubmit event to submit form to update fan fiction thumb form.
		var update_thumb_form = dojo.byId('update_fanfiction_thumb_form');
		if (update_thumb_form) {
			dojo.connect(update_thumb_form, 'onsubmit', Z2h.creations.updateThumb);
		} 
		
		// hook onclick event to submit form to update fan fiction title form.
		var update_title_btn = dojo.byId('fanfiction_title_submit');
		if (update_title_btn) {
			dojo.connect(update_title_btn, 'onclick', Z2h.creations.updateTitle);
		}  
	
		// for safari, hook onsubmit event to submit form to update fan fiction title form.
		var update_title_form = dojo.byId('update_fanfiction_title');
		if (update_title_form) {
			dojo.connect(update_title_form, 'onsubmit', Z2h.creations.updateTitle);
		} 
	
		// hook onchange event to select vote.
		var character_select_link = dojo.byId('story_character_select');
		if (character_select_link) {
			dojo.connect(character_select_link, 'onchange', Z2h.creations.refreshCharacterPage); 
		}
	
		dojo.query('a.load_story_page').forEach(function(link) {
			dojo.connect(link, 'onclick', Z2h.creations.loadStoryPage); 
		});
	 
		dojo.query('a.load_story_page_btn').forEach(function(link) {  
			dojo.connect(link, 'onclick', Z2h.creations.loadStoryPageBtn); 
		});
		
		// change font size.
		var fanfic_box_content = dojo.byId("fanfic_container_content");
		if (fanfic_box_content) {
			dojo.query('.font_size_option').forEach(function(change_size_link) {
				dojo.connect(change_size_link, '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(fanfic_box_content, 'text_size_'+current_font_size)) { 
							dojo.removeClass(fanfic_box_content, 'text_size_'+current_font_size);
						}
					}
					
					var new_font_size = dojo.attr(change_size_link, "title");
					dojo.addClass(change_size_link, 'selected_font_size'); 
					dojo.addClass(fanfic_box_content, 'text_size_'+new_font_size); 
			    });  
			});
		}
		
		var fanfic_box = dojo.byId("fanfic_container");
		if (fanfic_box) {
			// change background color. 
			dojo.query('.fanfic_dark_option').forEach(function(make_dark_link) {
				dojo.connect(make_dark_link, 'onclick', function(e){  
					e.preventDefault();
					dojo.addClass(fanfic_box, 'fanfic_dark'); 
			    });  
			});
			
			dojo.query('.fanfic_light_option').forEach(function(make_light_link) {
				dojo.connect(make_light_link, 'onclick', function(e){  
					e.preventDefault();
					if (dojo.hasClass(fanfic_box, 'fanfic_dark')) { 
						dojo.removeClass(fanfic_box, 'fanfic_dark');
					}
			    }); 
			});
		} 
	
		// hook submit comment event.
		var submitButton = dojo.byId("creations_add_comment");
		if (submitButton) {
			dojo.connect(submitButton, 'onclick', Z2h.creations.submitComment);
		}  
		
		// hook text character length aid.
		var creations_comment = dojo.byId('creations_comment_textarea'); 
		if (creations_comment) { 
		    dojo.connect(creations_comment, 
				    	"onkeyup",
				    	function(){  
							countTextarea(creations_comment, "comment_characters_remaining", submitButton, 1000);
		    }); 
		} 
		
		// display overlay form to flag a post. 
		dojo.query(".flag_link").forEach(function(node, i){  
			dojo.connect(node, 
					   "onclick",
					    function(e){ 
							e.preventDefault(); 
							dojo.attr(node, "disabled", "disabled");
							Z2h.creations.showAjaxFlagForm(node);
					    }); 
		}); 
		
		dojo.query(".flag_creation_link").forEach(function(node,i){
			dojo.connect(node,
						"onclick",
						function(e){
							e.preventDefault();
							Z2h.creations.showFlagForm(node);
						});
		});
	}, 
	
	hideThumbEditor: function() {
		var thumb_editor = dojo.byId('fanfiction_thumb_editor');
		var title_editor = dojo.byId('fanfiction_title_editor');
	
		if (thumb_editor && title_editor) {
			thumb_editor.style.display = "none"; 
			title_editor.style.display = ""; 
		} 
	},
	
	updateThumb: function(evt) {
		evt.preventDefault();
		
		var thumb_form = dojo.byId('update_fanfiction_thumb_form');
		var wait_section = dojo.byId("update_thumb_please_wait"); 
		var form_section = dojo.byId("update_thumb_form_section");
		var file_input = dojo.byId('fileToUpload');
		var error_msg = dojo.byId('fanfiction_thumb_error');
		
		if (thumb_form && file_input) {
			if (file_input.value) {
				if (error_msg) { 
					error_msg.innerHTML = "";
					error_msg.style.display = "none"; 
				} 
				
				if (wait_section && form_section) { 
					form_section.style.display = "none"; 
					wait_section.style.display = ""; 
				}
				 
				dojo.io.iframe.send({  
	                method: "post", 
	                url: thumb_form.action+'/format/text', 
					form: "update_fanfiction_thumb_form",  
				    timeout: 10000, 
					handleAs: "text",  
					load : function(response, ioArgs) { 
						if (response == 0) {
							// need to login.
							window.location.assign('/login-required');
						} else if (response == -1) {
							// error. reload the page.
							window.location.reload(true); 
						} else {
							// new thumbnail is returned.
							dojo.query('img.fanfiction_thumbnail_filename').forEach(function(thumb) {
								if (dojo.hasAttr(thumb, "src")) {
									dojo.attr(thumb, "src", response);
								}
							}); 
							
							if (wait_section && form_section) { 
								wait_section.style.display = "none"; 
								form_section.style.display = ""; 
							}
						} 
				
			            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 
			        }  
	            }); 
			} else {
				if (error_msg) {
					error_msg.innerHTML = "You must upload a thumbnail for your fan fiction.";
					error_msg.style.display = "block";
				} 
			}  
		} 
	}, 
	
	updateTitle: function(evt) {
		evt.preventDefault();
		
		var title_form = dojo.byId('update_fanfiction_title');
		var wait_section = dojo.byId("update_title_please_wait"); 
		var form_section = dojo.byId("update_title_form_section");
		
		if (title_form) {
			if (wait_section && form_section) { 
				form_section.style.display = "none"; 
				wait_section.style.display = ""; 
			}
			 
			dojo.xhrPost({
				url: title_form.action+'/format/json', 
				form: "update_fanfiction_title",  
				handleAs: "json",
//				sync: true,
				headers: {"X-Requested-With": "XMLHttpRequest"},
				load: function(data,ioargs){  
					var error_msg = dojo.byId('fanfiction_title_error');
					
					if(data.result == "-1"){ 
						window.location.assign(data.redirect); 
					} else if (data.result == "0") {  
						if (error_msg) {
							error_msg.innerHTML = data.title_error;
							error_msg.style.display = "inline";
						} 
					} else { 
						if (error_msg) {
							error_msg.style.display = "none"; 
							error_msg.innerHTML = "";
						}
					}
					
					if (wait_section && form_section) { 
						wait_section.style.display = "none"; 
						form_section.style.display = ""; 
					}
					
					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 
		        }
			});  
		} 
	},
	
	refreshCharacterPage: function(evt) {
		evt.preventDefault();
		 
		if (parseInt(evt.currentTarget.value) != 0) {
			// update dom id. (make sure there is div id=load_ajax_content_here)
			var update_dom = dojo.byId("story_page_ajax");
			
			// while loading. (make sure there is div id=load_ajax_content_loading)
			var loading_wait = dojo.byId("story_please_wait");
			var content = dojo.byId("story_content_refresh");
			
			// ajax requst url.
			var href = evt.currentTarget.name+"/element_id/"+evt.currentTarget.value;
			
			// only send an ajax request if nothing is running and the dom exists. 
			if (update_dom && Z2h.creations._running === false) {
				Z2h.creations._running = true; 
				 
				if (loading_wait && content) { 
					content.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;  
						
			            // initialize paginator js.
						Z2h.creations.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.creations._running = false; 
			}  
		} 
	},
	
	loadStoryPage: function(evt) {
		evt.preventDefault();
		
		// update dom id. (make sure there is div id=load_ajax_content_here)
		var update_dom = dojo.byId("story_page_ajax");
		
		// while loading. (make sure there is div id=load_ajax_content_loading)
		var loading_wait = dojo.byId("story_please_wait");
		var content = dojo.byId("story_content_refresh");
		
		// 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.creations._running === false) {
			Z2h.creations._running = true; 
			 
			if (loading_wait && content) { 
				content.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;  
					
		            // initialize paginator js.
					Z2h.creations.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.creations._running = false; 
		}  
	},
	
	loadStoryPageBtn: function(evt) {
		evt.preventDefault();
		
		// update dom id. (make sure there is div id=load_ajax_content_here)
		var update_dom = dojo.byId("story_page_ajax");
		
		// while loading. (make sure there is div id=load_ajax_content_loading)
		var loading_wait = dojo.byId("story_please_wait");
		var content = dojo.byId("story_content_refresh");
		
		// ajax requst url.
		var href = evt.currentTarget.href; 
		
		dojo.query('.fanfic_section_selected').forEach(function(selected) {
			dojo.removeClass(selected, 'fanfic_section_selected');
		});

		dojo.addClass(evt.currentTarget, 'fanfic_section_selected');
		
		// only send an ajax request if nothing is running and the dom exists. 
		if (update_dom && Z2h.creations._running === false) {
			Z2h.creations._running = true; 
			 
			if (loading_wait && content) { 
				content.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;  
					
		            // initialize paginator js.
					Z2h.creations.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.creations._running = false; 
		}  
	},
	
	// send flag form.
	sendAjaxFlagForm: function(link, parent_id){  
		var reason = dojo.byId("reason");
		var reason_error = dojo.byId("reason_form_errors"); 
		var loading_div = dojo.byId("overlay_please_wait");
		var form_div = dojo.byId("overlay_flag_form");
		var submit_btn = dojo.byId("flag_submit_btn");
		var cancel_btn = dojo.byId("flag_cancel_btn");
		
		if (reason_error) {
			reason_error.innerHTML = "";
		}
		
		// validate reason.
		if (reason.value.length > 10) { 
			form_div.style.display = "none";
			submit_btn.style.display = "none";
			cancel_btn.style.display = "none"; 
			loading_div.style.display = "block";
			
			// submit the form.
			dojo.xhrPost({
				url: link+"/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(); 

						// disable flag link.
						dojo.byId(parent_id).innerHTML = '<p id="awaiting_moderation">This post has been flagged and is awaiting moderation.</p>'; 
					}else{
						// show the signup form with the error message.
						form_div.style.display = "block"; 
						submit_btn.style.display = "block";
						cancel_btn.style.display = "block";  
						loading_div.style.display = "none";
						
						for(var k in data.errors){ 
							var errorItem = document.createElement('li');
							errorItem.innerHTML = data.errors[k];
							reason_error.appendChild(errorItem); 
						} 
						
						// set focus on textarea.
					    reason.focus();
					} 
				},
				// if any error occurs, it goes here:
				error: function(response, ioArgs){
					console.log("failed xhrPost", response, ioArgs);
					
					// show the signup form with the error message.
					form_div.style.display = "block"; 
					submit_btn.style.display = "block";
					cancel_btn.style.display = "block";  
					loading_div.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 
				}
			}); 
		} else { 
			var errorItem = document.createElement('li');
			errorItem.innerHTML = "Your reason is too short (min 10 characters)"; 
			reason_error.appendChild(errorItem);  
			
			form_div.style.display = "block"; 
			submit_btn.style.display = "block";
			cancel_btn.style.display = "block";  
			loading_div.style.display = "none";
		} 
	},

	//show overlay flag submission form.
	showAjaxFlagForm: function(link){ 
		 // get flag link.
		 var href = dojo.attr(link, "href"); 
		 var alt = dojo.attr(link, "alt");
		  
		// only send an ajax request if nothing is running.
		if (Z2h.creations._running === false) {
			Z2h.creations._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 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(".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.creations.sendAjaxFlagForm(href, alt);
					    	}); 
					    } 
					    
					    // hook text character length aid.
					    var reason = dojo.byId('reason'); 
					    if (reason) {  
					    	dojo.connect(reason, 
							    		"onkeyup",
							    		function(){  
											countTextarea(reason, "flag_characters_remaining", submitButton, 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.creations._running = false;
		} 
	},

	showFlagForm: function(link){
		// get flag link.
		var href = dojo.attr(link, "href"); 
		var alt = dojo.attr(link, "alt");
		var title = dojo.attr(link, "title");
	 
		// only send an ajax request if nothing is running.
		if (Z2h.creations._running === false) {
			Z2h.creations._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 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(".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.creations.sendFlagForm(href, alt, title);
				    	}); 
				    } 
				    
				    // hook text character length aid.
				    var reason = dojo.byId('reason'); 
				    if (reason) {  
				    	dojo.connect(reason, 
						    		"onkeyup",
						    		function(){  
										countTextarea(reason, "flag_characters_remaining", submitButton, 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.creations._running = false;
		} 
	},
	
	sendFlagForm: function(link,parent_id, content){
		var reason = dojo.byId("reason");
		var reason_error = dojo.byId("reason_error"); 
		var loading_div = dojo.byId("overlay_please_wait");
		var form_div = dojo.byId("overlay_flag_form");
		var submit_btn = dojo.byId("flag_submit_btn");
		var cancel_btn = dojo.byId("flag_cancel_btn");
		
		// validate reason.
		if (reason.value.length > 10) {
			if (reason_error) {
				reason_error.innerHTML = "";
			}
			
			form_div.style.display = "none";
			submit_btn.style.display = "none";
			cancel_btn.style.display = "none"; 
			loading_div.style.display = "block";
			
			// submit the form.
			dojo.xhrPost({
				url: link+"/format/json", 
				form: "flag_creation_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(); 
	
						// disable flag link.
	    				var update_dom = dojo.byId(parent_id);
	    				update_dom.innerHTML = '<p id="awaiting_moderation">This '+content+' is awaiting moderation.</p>'; 
	    				dojo.removeClass(update_dom, "creations_flag_inappropriate");
	    				dojo.addClass(update_dom, "flag_creation_inappropriate");
					}else{
						// show the signup form with the error message.
						form_div.style.display = "block"; 
						submit_btn.style.display = "block";
						cancel_btn.style.display = "block";  
						loading_div.style.display = "none";
						
						for(var k in data.errors){ 
							dojo.byId(k).innerHTML = data.errors[k]; 
						} 
						
						// set focus on textarea.
					    reason.focus();
					} 
				},
				// 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 request. Please try again!"); 
					
					/* handle the error... */ 
		            return response; //always return the response back 
				}
			}); 
		} else { 
			if (reason.value.length == 0) {
				reason_error.innerHTML = "Your reason is required.";
			} else {
				reason_error.innerHTML = "Your reason is too short, it can't be shorter than 10 characters.";
			} 
			
			form_div.style.display = "block"; 
			submit_btn.style.display = "block";
			cancel_btn.style.display = "block";  
			loading_div.style.display = "none";
		} 
	},
		
	submitComment: function(evt) {
		evt.preventDefault();
	 alert('sf');
		var errors = 0;
		var form = dojo.byId('creations_comment_form');
		
		// validate status. 
		var comment_input = trimAll(dojo.byId('creations_comment_textarea').value); 
		dojo.byId('creations_comment_errors').innerHTML = ""; 
			
		if (comment_input.length == 0) {
			var errorItem = document.createElement('li');
			errorItem.innerHTML = "Please write your comment first!";
			dojo.byId('creations_comment_errors').appendChild(errorItem); 
			errors++;  
		}
			
		// validate form.
		if (errors == 0) {  
			dojo.xhrPost({
				url: form.action+"/format/json",
				form: form.id,
				handleAs: "json",
				sync: true,
				headers: {"X-Requested-With": "XMLHttpRequest"},
				load: function(data,ioargs){  
					if(data.result == "1"){ 
						// clear the field.
						dojo.byId("creations_comment_textarea").value = "";
						dojo.byId("creations_comment_errors").innerHTML = ""; 
						dojo.byId('comment_characters_remaining').innerHTML = "1000 characters remaining";
							
						// load the updated comment list. 
						Z2h.creations.loadComments(1);  
					}else{ 
						var comment_errors = dojo.byId('creations_comment_errors');
							
						if (comment_errors) {
							comment_errors.innerHTML = "";
								
							for(var k in data.errors){ 
								var errorItem = document.createElement('li');
								errorItem.innerHTML = data.errors[k];
								comment_errors.appendChild(errorItem); 
							}
						} 
						 
						// if submit button was disabled, remove the attribute.
						var submitButton = dojo.byId("creations_add_comment");  
						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 xhrPost", response, ioArgs);
						 
					alert("ERROR: There was an error while submitting your status form. Please try again!");
					/* handle the error... */ 
			        return response; //always return the response back 
				}
			});
		} else {
			// if submit button was disabled, remove the attribute.
			var submitButton = dojo.byId("creations_add_comment");  
			if (submitButton && dojo.hasAttr(submitButton, "disabled")) {
				dojo.removeAttr(submitButton, "disabled");
			}
		}
			
		return false;
	},
	 
	loadComments: function(page) {		
		var commentList = dojo.byId("creations_comments");
		var theURL = dojo.byId("getmore").value;
//		console.log(theURL);
		
		if (commentList) {
			dojo.xhrGet({ 
				 url: theURL +"/format/text/page/"+page,
				 handleAs: "text",
				 sync: true,
				 	// run this function if the request is successful 
			        load : function(response, ioArgs) { 
			            // set some element's content... 
						if (page == 1) {
							commentList.innerHTML = response;  
						} else if (page > 1) {
							dojo.byId("paginator_"+(page-1)).style.display = "none"; 
							commentList.innerHTML += response;
						} 
						
			            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 
			        } 
			});
		} 
	}
}

//---------------------- CONTENT GALLERY COMMENT FUNCTIONS -------------------------

Z2h.gallery = {
		
	init: function() { 
		// hook submit comment event.
		var submitButton = dojo.byId("wall_add_post_button");
		if (submitButton) {
			dojo.connect(submitButton, 'onclick', Z2h.gallery.submitComment);
		}  
		
		// hook text character length aid.
		var gallery_comment = dojo.byId('gallery_comment_textarea'); 
		if (gallery_comment) { 
		    dojo.connect(gallery_comment, 
				    	"onkeyup",
				    	function(){  
							countTextarea(gallery_comment, "comment_characters_remaining", submitButton, 1000);
		    }); 
		}  
	}, 
		
	submitComment: function(evt) {
		evt.preventDefault();
	 
		var errors = 0;
		var form = dojo.byId('gallery_comment_form');
		
		// validate status. 
		if (dojo.byId('gallery_comment_textarea')) {
			var comment_input = trimAll(dojo.byId('gallery_comment_textarea').value); 
		}
		
		if (dojo.byId('gallery_comment_errors')) {
			dojo.byId('gallery_comment_errors').innerHTML = ""; 
		} 
			
		if (comment_input.length == 0) {
			var errorItem = document.createElement('li');
			errorItem.innerHTML = "Please write your comment first!";
			dojo.byId('gallery_comment_errors').appendChild(errorItem); 
			errors++;  
		}
			
		// validate form.
		if (errors == 0) {  
			dojo.xhrPost({
				url: form.action+"/format/json",
				form: form.id,
				handleAs: "json",
				sync: true,
				headers: {"X-Requested-With": "XMLHttpRequest"},
				load: function(data,ioargs){  
					if(data.result == "1"){ 
						// clear the field.
						dojo.byId("gallery_comment_textarea").value = "";
						dojo.byId("gallery_comment_errors").innerHTML = ""; 
						dojo.byId('comment_characters_remaining').innerHTML = "1000 characters remaining";
							
						// load the updated comment list. 
						Z2h.gallery.loadComments(1);  
					}else{ 
						var comment_errors = dojo.byId('gallery_comment_errors');
							
						if (comment_errors) {
							comment_errors.innerHTML = "";
								
							for(var k in data.errors){ 
								var errorItem = document.createElement('li');
								errorItem.innerHTML = data.errors[k];
								comment_errors.appendChild(errorItem); 
							}
						} 
						 
						// if submit button was disabled, remove the attribute.
						var submitButton = dojo.byId("wall_add_post_button");  
						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 xhrPost", response, ioArgs);
						 
					alert("ERROR: There was an error while submitting your status form. Please try again!");
					/* handle the error... */ 
			        return response; //always return the response back 
				}
			});
		} else {
			// if submit button was disabled, remove the attribute.
			var submitButton = dojo.byId("wall_add_post_button");  
			if (submitButton && dojo.hasAttr(submitButton, "disabled")) {
				dojo.removeAttr(submitButton, "disabled");
			}
		}
			
		return false;
	},
	 
	loadComments: function(page) {		
		var commentList = dojo.byId("gallery_comments");
		//console.log(commentList);
		if (commentList) {
			dojo.xhrGet({ 
				 url: "/content/index/gallery-comment-page/format/text/page/"+page,
				 handleAs: "text",
				 sync: true,
				 	// run this function if the request is successful 
			        load : function(response, ioArgs) { 
			            // set some element's content... 
						if (page == 1) {
							commentList.innerHTML = response;  
						} else if (page > 1) {
							dojo.byId("paginator_"+(page-1)).style.display = "none"; 
							commentList.innerHTML += response;
						} 
						
			            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 
			        } 
			});
		} 
	}
}

//---------------------- CONNECTIONS FUNCTIONS -------------------------

Z2h.connections = {
	
	init: function() {
		dojo.query('a.connections_remove').forEach(function(link) {
			dojo.connect(link, 'onclick', Z2h.connections.confirmRemove);
		});

        dojo.query('a.connections_connect').forEach(function(link) {
			dojo.connect(link, 'onclick', Z2h.connections.reasonDialog);
		});
	},
	
	confirmRemove: function(evt) {		
		var ans = confirm("Are you sure?");
		if (! ans) {
			evt.preventDefault();	
		}
	},
	
	reasonDialog: function(evt) {
		evt.preventDefault();
 
		var dialog = new dijit.Dialog({id:'reason_dialog'});
		dojo.style(dialog.titleBar, "display", "none");  

		dojo.xhrGet({
			url:'/connections/network/reasonsdialog/target/'+evt.currentTarget.rel,
			load: function(html) {
				// console.log(html);
				dialog.attr('content', html);
				dialog.show();

				dojo.query('.dijitDialogCloseIcon, #reason_dialog_cancel').forEach(
					function(o) {
						var handle = dojo.connect(o, 'onclick', dojo.hitch(dialog, function(e) {
							e.preventDefault();
							dialog.attr('content', ''),
							dialog.hide();
							dialog.destroy();
							dialog.disconnect(handle);
						}));
					}
				);

				// override escape button to trigger the reason dialog close button
				dojo.connect(dialog.domNode, 'onkeypress', function(e) {
					var k = e.keyCode || e.keyChar;
					if (k == dojo.keys.ESCAPE) {
						dojo.byId('reason_dialog_cancel').click();
						dojo.stopEvent(e);
					}
				});

				dojo.byId("ref").value = window.location;
				var otherText = dojo.byId('othertext');
				var otherRadio = dojo.byId('otherradio');
				if (otherText.value.length == 0) {
					otherText.disabled = true;
				}

				dojo.query('input[name=reason]').forEach(function(obj) {
					dojo.connect(obj, 'onclick', function(evt) {
						//console.log(obj);
						//console.log(evt.target.id);
						if (evt.target.id != 'otherradio') {
							otherText.value = "";
							otherText.disabled = true;
						}
					});
				});

				// attach radio button
				dojo.connect(otherRadio, 'onclick', function(e) {
					otherText.disabled = false;
					otherText.focus();
				});
				dojo.connect(otherText, 'onclick', function(e) {
					otherRadio.checked = true;
					otherText.disabled = false;
				});
			}
		});
	}
}

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

Z2h.user = {
	_running: false, 
		
	init: function() {  
		// hook onclick event to show dialog to sign up.
		dojo.query('a.show_signup').forEach(function(link) {
			dojo.connect(link, 'onclick', Z2h.user.showSignup); 
		});
		
		// hook onclick event to show dialog to send email to friend.
		dojo.query('a.send_friend').forEach(function(link) {
			dojo.connect(link, 'onclick', Z2h.user.sendEmailDialog);
		});
		
		// hook onclick event to toggle checkbox
		dojo.query(".toggle_checkbox").forEach(function(link) {
			dojo.connect(link, "onclick", Z2h.user.toggleSelect);  
		});
	
		var validate_checkbox = dojo.byId('validate_checkbox');
		if (validate_checkbox) {
			dojo.connect(validate_checkbox, 'onclick', Z2h.user.validateSelect); 
		}
		
		var send_invites_form = dojo.byId('send_invites_form');
		if (send_invites_form) {
			dojo.connect(send_invites_form, 'onsubmit', Z2h.user.validateSelect); 
		}
	}, 
	
	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'); 
		} 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');
			
			if (dojo.hasAttr(evt.currentTarget, "checked")) {
				dojo.removeAttr(evt.currentTarget, "checked");
			} 
		} 
	},
	 
	// login form submission.
	sendLoginForm: function() {  
		var errors = 0;
		
		// validate username.
		var username = dojo.byId('login_username').value; 
		if(username==''){
			errors++;  
			dojo.byId('login_form_error_msg').innerHTML = "Username is required."; 
		}else{ 
			dojo.byId('login_form_error_msg').innerHTML = ""; 
		} 
		
		// validate password.
		var passwd = dojo.byId('login_passwd').value; 
		if(passwd.length == 0){
			if(errors == 0){
				// no username error.
				dojo.byId('login_form_error_msg').innerHTML = "Password is required."; 
			}else{
				dojo.byId('login_form_error_msg').innerHTML = "Username and Password are required."; 
			}
			
			errors++;  
		}else{  
			if(errors == 0){
				dojo.byId('login_form_error_msg').innerHTML = "";
			}
		}
		
		// validate form.
		if(errors == 0){ 
			dojo.byId("login_form_error_msg").style.display = "none";
			
			// only send an ajax request if nothing is running.
			if (Z2h.user._running === false) {
				Z2h.user._running = true;
				
				// hide the login form.
				dojo.byId("login_form_submit").style.display = "none";
				dojo.byId("login_please_wait").style.display = "";  
				
				dojo.xhrPost({
					url: "/user/authentication/login/format/json", 
					form: "login_form",  
					handleAs: "json",
					sync: true,
					headers: {"X-Requested-With": "XMLHttpRequest"},
					load: function(data,ioargs){  
						if(data.result == "1"){
							try {
								var googleTracker = _gat._getTracker(Z2h.tracking_id);
								googleTracker._setCustomVar(1,"Status","Member",1);
								googleTracker._trackPageview('/form/login/confirm/');
							} catch (err){}

							if (data.target == "/") {
								window.location.reload(true);
							} else {
								window.location.assign(data.target);
							} 
						}else{
							for(var k in data.errors){ 
								if(k == 'general'){
									dojo.byId('login_form_error_msg').innerHTML = data.errors[k];
									dojo.byId('login_form_error_msg').style.display = "block";
								}else{ 
									dojo.byId(k+"_after").innerHTML = data.errors[k];
									dojo.byId(k+"_after").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!");
			            
			            /* handle the error... */ 
			            return response; //always return the response back 
			        }
				});
				
				Z2h.user._running = false; 
			} 
		} else {
			dojo.byId('login_form_error_msg').style.display = "block";
		}
	}, 
	
	// 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.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) { 
			 		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.user.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.user.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.user._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 (!validateEmail(email_field.value, true, 'to_email_after')) {
				errors++;
				dojo.byId("to_email_valid").style.display = "none";
				dojo.byId("to_email_invalid").style.display = "block";
			} else {
				dojo.byId("to_email_invalid").style.display = "none";
				dojo.byId("to_email_valid").style.display = "block";
			}
		}
		
		// validate body.
		var body = 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.";
			dojo.byId("body_email_valid").style.display = "none";
			dojo.byId("body_email_invalid").style.display = "block";
		} else {
			dojo.byId('body_email_after').innerHTML = "";
			dojo.byId("body_email_invalid").style.display = "none";
			dojo.byId("body_email_valid").style.display = "block";
		}
		 
		// 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 = ""; 
			
			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"; 
								
								// show invalid mark.
								dojo.byId(k+"_valid").style.display = "none";
								dojo.byId(k+"_invalid").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 
		        }
			});
		} 
	}, 
	
	// show overlay form to sign up.
	showSignup: function(evt) {
		evt.preventDefault();
		 
		// only send an ajax request if nothing is running.
		if (Z2h.user._running === false) {
			Z2h.user._running = true;
			
			dojo.xhrGet({ 
				url: "/user/authentication/signup/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";
				    }
				    
				    // set avatar. 
					dojo.query(".avatar_link").forEach(function(node, i){  
						var avatar = dojo.attr(node, "alt");
						
						dojo.connect(node, 
									 "onclick",
									 function(e){ 
										e.preventDefault(); 
										selectAvatar(avatar);
						});  
					}); 

					// 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();
				    	}); 
				    }  
			  
		            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) { 
				// count errors.
				var errors = 0;
				
				// validate username.
				var username_field = dojo.byId('signup_username');
				if (username_field) {
					if (!validateUsername(username_field.value, true, 'signup_username_after')) {
						errors++;
						//dojo.byId("signup_username_valid").style.display = "none";
						//dojo.byId("signup_username_invalid").style.display = "block";
					} else {
						//dojo.byId("signup_username_invalid").style.display = "none";
						//dojo.byId("signup_username_valid").style.display = "block";
					}
				} 
				
				// validate email.
				var email_field = dojo.byId('signup_email'); 
				if (email_field) {  
					if (!validateEmail(email_field.value, true, 'signup_email_after')) {
						errors++;
						//dojo.byId("signup_email_valid").style.display = "none";
						//dojo.byId("signup_email_invalid").style.display = "block";
					} else {
						//dojo.byId("signup_email_invalid").style.display = "none";
						//dojo.byId("signup_email_valid").style.display = "block";
					}
				}
				
				// validate password.
				var passwd_field = dojo.byId('signup_passwd1'); 
				if (passwd_field) {  
					if (!validatePassword(passwd_field.value, true, 'signup_password_after')) {
						errors++;
						//dojo.byId("signup_password_valid").style.display = "none";
						//dojo.byId("signup_password_invalid").style.display = "block";
					} else {
						//dojo.byId("signup_password_invalid").style.display = "none";
						//dojo.byId("signup_password_valid").style.display = "block";
						
						// continue validating verify password.
						var verify_passwd = dojo.byId('signup_passwd2').value;
						var passwd2_p = dojo.byId('signup_verify_password_after');
						if(verify_passwd.length == 0){
							errors++;  
							passwd2_p.innerHTML = "Please verify your password.";
							
							//dojo.byId("signup_verify_invalid").style.display = "block";
							//dojo.byId("signup_verify_valid").style.display = "none";
						}else{  
							if(verify_passwd!=passwd_field.value){
								errors++; 
								passwd2_p.innerHTML = "Password doesn't match! CAPS might be on! Please re-enter your password to verify.";
								
								//dojo.byId("signup_verify_invalid").style.display = "block";
								//dojo.byId("signup_verify_valid").style.display = "none";
							}else{ 
								passwd2_p.innerHTML = ""; 
								
								//dojo.byId("signup_verify_invalid").style.display = "none";
								//dojo.byId("signup_verify_valid").style.display = "block";
							}
						}
					}
				}
				
				// validate birthday.
				if (!validateSignupBirthday(true)) {
					errors++;
				} 
				
				// validate form.
				if(errors > 0){
					// display error message.
					dojo.byId("signup_error_notice").style.display = "block";
					
					// if submit button was disabled, remove the attribute.
					var submitButton = dojo.byId('signup_submit'); 
					if (submitButton && dojo.hasAttr(submitButton, "disabled")) {
						dojo.removeAttr(submitButton, "disabled");
					}
				}else{
					dojo.byId("signup_error_notice").style.display = "none";
					
					// hide the signup form.
					dojo.byId("overlay_signup_form").style.display = "none";
					dojo.byId("overlay_signup_position").style.display = "none";
					dojo.byId("overlay_please_wait").style.display = "";
					
					dojo.xhrPost({
						url: "/user/authentication/signup/format/json", 
						form: "signup_form",  
						handleAs: "json",
						sync: true,
						headers: {"X-Requested-With": "XMLHttpRequest"},
						load: function(data,ioargs){  
							if(data.result == "1"){
								try {
								var googleTracker = _gat._getTracker(Z2h.tracking_id);
								googleTracker._setCustomVar(1,"Status","Member",1);
								googleTracker._trackPageview('/form/registration/confirm/');
								} catch (err){}
								window.location.assign(data.redirect); 
							}else{
								// show the signup form with the error message.
								dojo.byId("overlay_signup_form").style.display = "";
								dojo.byId("overlay_signup_position").style.display = "";
								dojo.byId("overlay_please_wait").style.display = "none";
								
								for(var k in data.errors){ 
									if(k == 'general'){
										dojo.byId('general_signup_error').innerHTML = data.errors[k];
										dojo.byId('signup_error_notice').style.display = "block";
									}else{ 
										dojo.byId(k+"_after").innerHTML = data.errors[k];
										dojo.byId(k+"_after").style.display = "block";
										
										// show invalid mark.
										//dojo.byId(k+"_valid").style.display = "none";
										//dojo.byId(k+"_invalid").style.display = "block";
									} 
								} 
								
								// if submit button was disabled, remove the attribute.
								var submitButton = dojo.byId('signup_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.user._running = false; 
		}
	} 
}

Z2h.contest = {
	_running: false, 
			
	init: function() {  
		// hook onclick event to show confirm dialog to delete item.
		dojo.query('a.contest_leave, a.vote_remove').forEach(function(link) {
			dojo.connect(link, 'onclick', Z2h.contest.doPostLeave);
		});
		
		// hook onclick event to show next contest winner.
		dojo.query('a.next_contest_winner').forEach(function(link) {
			dojo.connect(link, 'onclick', Z2h.contest.showNextWinner);
		});
		
		// hook onclick event to show previous contest winner.
		dojo.query('a.previous_contest_winner').forEach(function(link) {
			dojo.connect(link, 'onclick', Z2h.contest.showPrevWinner);
		});
		
		// hook onclick event to move vote up.
		dojo.query('a.contests_manage_vote_up').forEach(function(link) {
			dojo.connect(link, 'onclick', Z2h.contest.voteUp);
		});
		
		// hook onclick event to move vote down.
		dojo.query('a.contests_manage_vote_down').forEach(function(link) {
			dojo.connect(link, 'onclick', Z2h.contest.voteDown);
		});
		
		// hook onchange event to select vote.
		var contest_select_link = dojo.byId('my_vote_select');
		if (contest_select_link) {
			dojo.connect(contest_select_link, 'onchange', Z2h.contest.refreshVotes); 
		}
    },
    
    voteUp: function(evt) {
		evt.preventDefault();  
		
		// only send an ajax request if nothing is running.
		if (Z2h.contest._running === false) {
			Z2h.contest._running = true;
			
			var href = evt.currentTarget.href;
			
			dojo.xhrGet({ 
			 	url: href+"/format/json",  //the relative URL  
			 	handleAs: "json",
			 	sync: true,
			 	// run this function if the request is successful 
			 	load: function(data,ioargs){  
					if(data.result == '1'){ 
						var li_parent = evt.currentTarget.parentNode.parentNode;
						var current_position = li_parent.id;
						var total_allowed_votes = dojo.attr(evt.currentTarget, "alt");
						
						if (parseInt(current_position) > 1) {
							var new_position = parseInt(current_position) - 1;
							
							if (new_position == 1) {
								// hide up button.
								evt.currentTarget.style.display = "none";
							} 
							
							if (current_position == total_allowed_votes) {
								// show down button.  
								var current_down_btn = dojo.query('div.contests_manage_vote_btns > a.contests_manage_vote_down', li_parent)[0];
								current_down_btn.style.display = "block"; 
							} 
							 
							var current_dom = li_parent.innerHTML; 
							
							var existing_vote = dojo.query('ul.contests_myVotes_items > li#'+new_position)[0];
							var existing_vote_dom = '';
							
						    if (dojo.hasClass(existing_vote, 'contests_votes_empty')) {
						    	dojo.removeClass(existing_vote, 'contests_votes_empty');
						    	dojo.addClass(li_parent, 'contests_votes_empty');
						    	
						    	switch (parseInt(current_position)) {
									case 1:
										existing_vote_dom = '<p>1st Place</p>';
										break;
										
									case 2:
										existing_vote_dom = '<p>2nd Place</p>';
										break;
										
									case 3:
										existing_vote_dom = '<p>3rd Place</p>';
										break;
										
									default:
										existing_vote_dom = '<p>'+parseInt(current_position)+'th Place</p>';
								}
							} else {
								var existing_up_btn = dojo.query('div.contests_manage_vote_btns > a.contests_manage_vote_up', existing_vote)[0];
								existing_up_btn.style.display = "block"; 
								
								if (current_position == total_allowed_votes) {
									// hide down button.  
									var existing_down_btn = dojo.query('div.contests_manage_vote_btns > a.contests_manage_vote_down', existing_vote)[0];
									existing_down_btn.style.display = "none"; 
								} 
								
								existing_vote_dom = existing_vote.innerHTML;  
							} 
						    
						    existing_vote.innerHTML = current_dom;
						    li_parent.innerHTML = existing_vote_dom; 
						    
						    dojo.query('a.contests_manage_vote_up').forEach(function(link) {
								dojo.connect(link, 'onclick', Z2h.contest.voteUp);
							});
						    
						    // hook onclick event to show confirm dialog to delete item.
							dojo.query('a.contest_leave, a.vote_remove').forEach(function(link) {
								dojo.connect(link, 'onclick', Z2h.contest.doPostLeave);
							});
							 
							// hook onclick event to move vote down.
							dojo.query('a.contests_manage_vote_down').forEach(function(link) {
								dojo.connect(link, 'onclick', Z2h.contest.voteDown);
							});
						} 
			 		} 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 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.contest._running = false; 
		} 
	},
	
	voteDown: function(evt) {
		evt.preventDefault();  
		
		// only send an ajax request if nothing is running.
		if (Z2h.contest._running === false) {
			Z2h.contest._running = true;
			
			var href = evt.currentTarget.href;
			
			dojo.xhrGet({ 
			 	url: href+"/format/json",  //the relative URL  
			 	handleAs: "json",
			 	sync: true,
			 	// run this function if the request is successful 
			 	load: function(data,ioargs){  
					if(data.result == '1'){ 
						var li_parent = evt.currentTarget.parentNode.parentNode;
						var current_position = li_parent.id;
						var total_allowed_votes = dojo.attr(evt.currentTarget, "alt");
						
						if (parseInt(current_position) < total_allowed_votes) {
							var new_position = parseInt(current_position) + 1;
							
							if (new_position == total_allowed_votes) {
								// hide down button.
								evt.currentTarget.style.display = "none";
							} 
							
							if (current_position == 1) {
								// show up button.  
								var current_up_btn = dojo.query('div.contests_manage_vote_btns > a.contests_manage_vote_up', li_parent)[0];
								current_up_btn.style.display = "block"; 
							} 
							
							var current_dom = li_parent.innerHTML; 
							
							var existing_vote = dojo.query('ul.contests_myVotes_items > li#'+new_position)[0];
							var existing_vote_dom = '';
							
						    if (dojo.hasClass(existing_vote, 'contests_votes_empty')) {
						    	dojo.removeClass(existing_vote, 'contests_votes_empty');
						    	dojo.addClass(li_parent, 'contests_votes_empty');
						    	
						    	switch (parseInt(current_position)) {
									case 1:
										existing_vote_dom = '<p>1st Place</p>';
										break;
										
									case 2:
										existing_vote_dom = '<p>2nd Place</p>';
										break;
										
									case 3:
										existing_vote_dom = '<p>3rd Place</p>';
										break;
										
									default:
										existing_vote_dom = '<p>'+parseInt(current_position)+'th Place</p>';
								}
							} else {
								var existing_down_btn = dojo.query('div.contests_manage_vote_btns > a.contests_manage_vote_down', existing_vote)[0];
								existing_down_btn.style.display = "block"; 
								
								if (current_position == 1) {
									// hide up button.  
									var existing_up_btn = dojo.query('div.contests_manage_vote_btns > a.contests_manage_vote_up', existing_vote)[0];
									existing_up_btn.style.display = "none"; 
								} 
								
								existing_vote_dom = existing_vote.innerHTML;  
							} 
						    
						    existing_vote.innerHTML = current_dom;
						    li_parent.innerHTML = existing_vote_dom; 
						    
						    dojo.query('a.contests_manage_vote_up').forEach(function(link) {
								dojo.connect(link, 'onclick', Z2h.contest.voteUp);
							});
						    
						    // hook onclick event to show confirm dialog to delete item.
							dojo.query('a.contest_leave, a.vote_remove').forEach(function(link) {
								dojo.connect(link, 'onclick', Z2h.contest.doPostLeave);
							});
							 
							// hook onclick event to move vote down.
							dojo.query('a.contests_manage_vote_down').forEach(function(link) {
								dojo.connect(link, 'onclick', Z2h.contest.voteDown);
							});
						}  
			 		} 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 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.contest._running = false; 
		} 
	},
	
    refreshVotes: function(evt) {
		evt.preventDefault(); 
		window.location.assign(evt.currentTarget.name+"/id/"+evt.currentTarget.value);
	},
    
    doPostLeave: function(evt) {
		evt.preventDefault();
			
		if (confirm(evt.currentTarget.title)) { 
			var form = document.createElement('form');
			form.setAttribute("id","leaveContestForm");
			form.setAttribute("method","POST");
			form.setAttribute("action",evt.currentTarget.href);
			document.getElementsByTagName("body").item(0).appendChild(form);
			form.submit();
		}
	},
	
	 showNextWinner: function(evt) {
		evt.preventDefault();
		 
		var next_id = dojo.attr(evt.currentTarget, "alt");
		var total_winners = dojo.attr(evt.currentTarget, "title");
		var dom_id = dojo.attr(evt.currentTarget, "name");
		
		if (next_id < total_winners) { 
			var prev_id = parseInt(next_id) - 1;
			
			if (prev_id >= 0) {
				// hide current dom.
				var prev_dom_left = dojo.byId('left_'+dom_id+'_'+prev_id);
				var prev_dom_right = dojo.byId('right_'+dom_id+'_'+prev_id);
				
				if (prev_dom_left) {
					prev_dom_left.style.display ="none";
				}
				
				if (prev_dom_right) {
					prev_dom_right.style.display ="none";
				} 
			}
			
			// show next dom.
			var next_dom_left = dojo.byId('left_'+dom_id+'_'+next_id);
			var next_dom_right = dojo.byId('right_'+dom_id+'_'+next_id);
			
			if (next_dom_left) {
				next_dom_left.style.display ="block";
			}
			
			if (next_dom_right) {
				next_dom_right.style.display ="block";
			}
			
			// show previous link.
			var prev_link = dojo.byId('prev_'+dom_id);
			if (prev_link) {
				dojo.attr(prev_link, 'alt', prev_id);
				prev_link.style.display = "block";
			}
			
			// show/hide next link.
			var next_next_id = parseInt(next_id) + 1; 
			
			if (next_next_id < total_winners) {
				// update alt.
				dojo.attr(evt.currentTarget, 'alt', next_next_id);
			} else {
				evt.currentTarget.style.display ="none";
			}
		} 
	},
	
	 showPrevWinner: function(evt) {
		evt.preventDefault();
		 
		var prev_id = dojo.attr(evt.currentTarget, "alt");
		var total_winners = dojo.attr(evt.currentTarget, "title");
		var dom_id = dojo.attr(evt.currentTarget, "name");
		
		if (prev_id >= 0) { 
			var next_id = parseInt(prev_id) + 1;
			
			if (next_id < total_winners) {
				// hide current dom.
				var next_dom_left = dojo.byId('left_'+dom_id+'_'+next_id);
				var next_dom_right = dojo.byId('right_'+dom_id+'_'+next_id);
				
				if (next_dom_left) {
					next_dom_left.style.display ="none";
				}
				
				if (next_dom_right) {
					next_dom_right.style.display ="none";
				} 
			}
			
			// show prev dom.
			var prev_dom_left = dojo.byId('left_'+dom_id+'_'+prev_id);
			var prev_dom_right = dojo.byId('right_'+dom_id+'_'+prev_id);
			
			if (prev_dom_left) {
				prev_dom_left.style.display ="block";
			}
			
			if (prev_dom_right) {
				prev_dom_right.style.display ="block";
			}
			
			// show next link.
			var next_link = dojo.byId('next_'+dom_id);
			if (next_link) {
				dojo.attr(next_link, 'alt', next_id);
				next_link.style.display = "block";
			}
			
			// show/hide prev link.
			var prev_prev_id = parseInt(prev_id) - 1; 
			
			if (prev_prev_id >= 0) {
				// update alt.
				dojo.attr(evt.currentTarget, 'alt', prev_prev_id);
			} else {
				evt.currentTarget.style.display ="none";
			}
		} 
	}
}

//------------------------NEW ADDITION---------------------------------------

//---------------------- 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 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) {
			dojo.connect(link, "onclick", function(e) { 
				e.preventDefault();  
				Z2h.link.rate(link, 1); 
			});  
		});
		
		// hook onclick event to rate down creation item
		dojo.query("a.rate_down_link").forEach(function(link) {
			dojo.connect(link, "onclick", function(e) { 
				e.preventDefault();  
				Z2h.link.rate(link, -1); 
			});  
		});
	
		// 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);
		});
	},
	
	// 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) {
		// get rating link and parent class
		var href = dojo.attr(link, "href");
		var update_dom_id = dojo.attr(link, "alt");
		
		// remove the rating links
		dojo.query("." + update_dom_id + "_link").forEach(function(node, i) {  
			 node.innerHTML = "";
		}); 
		
		dojo.xhrGet({ 
		    url: href + "/format/json",  
			handleAs: "json",
			sync: true,
			headers: {"X-Requested-With": "XMLHttpRequest"},
			load: function(data,ioargs) {  
				if (data.result == "1") {  
					// 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 
			} 
		});  
	},
	
	// 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) {
		// 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");  
	    pMessage.innerHTML = msg; 
	     
	    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 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.addClass(yesBtn, "popupYesButton");
		    yesBtn.innerHTML = "<span>Ok</span>";
		    	
			var yesHandle = dojo.connect(yesBtn, 
			    						 "onclick",
			    						  dojo.hitch(confirm_form, 
			    						     		function(e){
					    							    e.preventDefault();
											    		confirm_form.attr("content", ""); 
											    		confirm_form.hide(); 
											    		confirm_form.destroy(); 
			    						     			dojo.disconnect(yesHandle); 
			    						     			
			    						     			okCallback();
			    						 }));
			    
			dojo.place(yesBtn, divButtons, "last"); 
			
			// create no button
		    var noBtn = document.createElement("a"); 
		    dojo.addClass(noBtn, "popupCancelButton");
		    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, "last");
	    } else {
	    	// create yes button.
		    var yesBtn = document.createElement("button");
		    dojo.attr(yesBtn, "type", "submit");
		    dojo.addClass(yesBtn, "popupYesButton");
		    yesBtn.innerHTML = "<span>Ok</span>";
		    	
			var yesHandle = dojo.connect(yesBtn, 
			    						 "onclick",
			    						  dojo.hitch(confirm_form, 
			    						     		function(e){
					    							    e.preventDefault();
					    							    confirm_form.attr("content", ""); 
											    		confirm_form.hide(); 
											    		confirm_form.destroy(); 
			    						     			dojo.disconnect(yesHandle);  
			    						 }));
			    
			dojo.place(yesBtn, divButtons, "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, 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", submitButton, 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>Waiting for moderation</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";
			}
		} 
	}
}


//---------------------- 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();
		   	} 
	    } 
	}
}


//---------------------- GLOBAL PAGE ONLOAD FUNCTIONS -------------------------

dojo.addOnLoad(function() {   
	Z2h.global.init(); 
	
	Z2h.connections.init();
	
	Z2h.creations.init();
	
	Z2h.gallery.init();
	
	Z2h.rating.init();
	
	Z2h.contest.init();
	
	Z2h.user.init();
	
        var sidebar = dojo.byId("side_banner");
	
	if (sidebar) {  
		var browserWidth = document.documentElement.clientWidth;
		
		// show/hide sidebar on load (old limit: 1365)
		if (browserWidth < 1340) { 
			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 < 1340) {
				sidebar.style.display = "none";
			} else { 
				sidebar.style.display = "block";
			} 
		});
	} 	

	// display confirm box before deleting a creation.
	dojo.query(".creation_delete").forEach(function(node, i){  
		var msg = dojo.attr(node, "title");
		
		dojo.connect(node, 
					 "onclick",
					 function(e){ 
						e.preventDefault(); 
						doPostDelete(node, msg, false);
		}); 
	});
}); 


function showTour(video) {  
	 dojo.xhrGet({ 
		 	url: "/index/tour/video/"+ video +"/format/text",  //the relative URL  
		 	handleAs: "text",
		 	sync: true,
		 	// run this function if the request is successful 
	        load : function(response, ioArgs) { 
		 		// initialize dialog.
				var tour = new dijit.Dialog({id: "tour_overlay"}); 
				dojo.style(tour.titleBar, "display", "none");  
				
				tour.attr('content', response);
				
				swfobject.embedSWF("/flash/jw/player.swf","tour_video","640", "360","9.0.0","/flash/expressInstall.swf",
					{ file: 'http://www.iloveheartland.com:8000/video/' + video + '.m4v' },
					{
						menu: "false",
						allowfullscreen: "true",
						allowscriptaccess: "always"
					},
					{ id: "tour_video" }
				);

				
				tour.show();

			    // close over flag form. 
				dojo.query(".overlay_video_close").forEach(function(node, i){  
					var closeHandle = dojo.connect(node, 
												   "onclick",
												   dojo.hitch(tour, 
												     		  function(e){ 
												    				e.preventDefault();
												    				tour.attr('content', ''); 
												    				tour.hide(); 
												    				tour.destroy(); 
												     				dojo.disconnect(closeHandle); 
												     		   })); 
				});  
				
				// overwrite the default esc key event.
				var escHandle = dojo.connect(tour.domNode, "onkeypress", function(e){
					var key = e.keyCode || e.charCode;
					var k = dojo.keys;
				
					if (key == k.ESCAPE) {
						e.preventDefault();
					   	tour.attr('content', ''); 
					   	tour.hide(); 
					   	tour.destroy(); 
						dojo.disconnect(escHandle); 
					}
				}); 

				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 
	        }
	});   
}
