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

dojo.require("dijit.ProgressBar");

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

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

dojo.require("dijit.dijit");
dojo.require("dijit._Calendar");
dojo.require("dojox.widget.Toaster");
dojo.require("dijit.Tooltip");

dojo.registerModulePath("Z2h","/js/extensions/Z2h");
dojo.require("Z2h.Toast");
dojo.require("Z2h.Slideshow");
dojo.require("Z2h.Slide");
dojo.require("Z2h.Slide.Video");
dojo.require("Z2h.Slide.Image");
dojo.require("Z2h.Slide.Contest");
dojo.require("Z2h.VotingWidget");
dojo.require("Z2h.Notification");
dojo.require("Z2h.VideoWidget");

Object.size = function(obj) {
    var size = 0, key;
    for (key in obj) {
        if (obj.hasOwnProperty(key)) size++;
    }
    return size;
};

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

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

dojo.extend(dojox.editor.plugins.UploadImage, {
		onComplete: function(data) {
		    data = data[0];
		    var tmpImgNode = dojo.withGlobal(this.editor.window, "byId", dojo, [this.currentImageId]);

		    if (data.error || data.name == "") {
			if (data.error) {
			    Z2h.link.error(data.error);
			} else {
			    Z2h.link.error("Unknown error occured, please try again.");
			}

			var editor = dijit.byId("dojo_editor_textarea");

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

			for (var i in paragraph.children) {
			    if (paragraph.children[i].localName == "IMG") {
				var node = paragraph.children[i];
				var src = dojo.attr(node, "src");

				if (src == "") {
				    paragraph.removeChild(node);
				    editor.attr("value", paragraph.innerHTML);
				}
			    }
			}

			dojo.destroy(tmpImgNode);
		    } else {
			// image is ready to insert
			var file;

			// downloadPath is mainly used so we can access a PHP script
			// not relative to this file. The server *should* return a qualified path
			if (this.downloadPath) {
			    file = this.downloadPath + data.name
			} else {
			    file = data.file;
			}

			tmpImgNode.src = file;
			dojo.attr(tmpImgNode,'_djrealurl',file);

			if (data.width) {
			    tmpImgNode.width = data.width;
			    tmpImgNode.height = data.height;
			}
		    }
		},

		insertTempImage: function(){
		    this.button.fileInputs.pop();
		    // inserting a "busy" image to show something is hapening
		    //	during upload and download of the image.
		    this.currentImageId = "img_"+(new Date().getTime());
		    var iTxt = '<img id="'+this.currentImageId+'" src="/images/editor-loader.gif" width="32" height="32" />';
		    this.editor.execCommand('inserthtml', iTxt);
		},

		createFileInput: function(){
		    var node = dojo.create('span', {innerHTML:"."}, document.body);
		    dojo.style(node, {
				   width:"40px",
				   height:"20px",
				   paddingLeft:"8px",
				   paddingRight:"8px"
			       });
		    this.button = new dojox.form.FileUploader({
								  isDebug:false,
								  force:"html",
								  uploadUrl:this.uploadUrl,
								  uploadOnChange:true,
								  selectMultipleFiles:true,
								  baseClass:"dojoxEditorUploadNorm",
								  hoverClass:"dojoxEditorUploadHover",
								  activeClass:"dojoxEditorUploadActive",
								  disabledClass:"dojoxEditorUploadDisabled"
							      }, node);

		    this.connect(this.button, "onChange", "insertTempImage");
		    this.connect(this.button, "onComplete","onComplete");
		}
	    });

//---------------------- 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) {
										//need to also check and see if the new search matches the old search at all, instead
										//of just keyword lengths
										var match1 = _this.lastKeyword.indexOf(keysearch);
										var match2 = keysearch.indexOf(_this.lastKeyword);

										var doSearch = ( match1 < 0 ) && ( match2 <= 0 );

										if ( doSearch ) {
										    _this.lastKeyword = keysearch;
										    _this.store = null;
										    _this._startSearch(keysearch);
										} else {
										    _this._openResultList(a, b);
										}
									    } else {
										//set the store to null and retry the search
										_this.lastKeyword = keysearch;
										_this.store = null;
										_this._startSearch(keysearch);
									    }
									} else {
									    _this._openResultList(a, b);
									}
								    },
								    onError: function(errText) {
									console.error("dijit.form.ComboBox: " + errText);
									dojo.hitch(_this, "_hideResultList")();
								    },
								    start: 0,
								    count: this.pageSize
								};

								dojo.mixin(fetch, _this.fetchProperties);

								var dataObject = _this.store.fetch(fetch);
								var nextSearch = function(dataObject, direction) {
								    dataObject.start += dataObject.count * direction;
								    // #4091:
								    // tell callback the direction of the paging so the screen
								    // reader knows which menu option to shout
								    dataObject.direction = direction;
								    this.store.fetch(dataObject);
								};

								this._nextSearch = this._popupWidget.onPage = dojo.hitch(this, nextSearch, dataObject);
							    }, query, this), this.searchDelay);
		 }
	     });

//---------------------- GLOBAL VARIABLES & FUNCTIONS --------------------------------
Z2h = {}; // initialize z2h

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

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

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

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

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

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

// get usernames and creation tags
var creation_tags =
    new dojo.data.ItemFileReadStore({
					url: "/creation/index/get-tags/format/json"
				    });

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

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

var usernames =
    new dojo.data.ItemFileReadStore({
					url: "/user/index/get-usernames/format/json"
				    });

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

var message_topic =
    new dojo.data.ItemFileReadStore({
					url: "/community/discussion/get-topics/format/json"
				    });

// initialize application-wide js functions
Z2h.global = {
    init: function() {
	Z2h.mailing.init();
	Z2h.link.init();
	Z2h.comment.init();
	Z2h.inbox.init();
	Z2h.inbox.recipients.init();
	Z2h.user.init();
	Z2h.user.profile.init();
	Z2h.user.hovercard.init();
	Z2h.autocomplete.init();
	Z2h.connection.init();
	Z2h.editor.init();
	Z2h.social.init();
	Z2h.creation.init();
	Z2h.group.init();
	Z2h.admin.init();
	Z2h.excls.init();
	Z2h.isMature.init();
	Z2h.video.init();
	Z2h.contest.init();
	Z2h.quiz.init();
    }
}

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

Z2h.sleep = function(naptime){
    naptime = naptime * 1000;
    var sleeping = true;
    var now = new Date();
    var start = now.getTime();
    while ( sleeping ) {
	alarm = new Date();
	if ( alarm.getTime() - start > naptime ){ sleeping = false; }
    }
};


//---------------------- STRING FUNCTIONS --------------------------------
Z2h.string = {
    // trim empty string from front
    leftTrim: function(sString) {
	while (sString.substring(0,1) == " ") {
	    sString = sString.substring(1, sString.length);
	}

	return sString;
    },

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

	return sString;
    },

    // trim empty string from front-end
    trimAll: function(sString) {
	while (sString.substring(0,1) == " ") {
	    sString = sString.substring(1, sString.length);
	}

	while (sString.substring(sString.length-1, sString.length) == " ") {
	    sString = sString.substring(0,sString.length-1);
	}

	return sString;
    },

    // count total characters entered in textarea (max 1000 characters)
    countTextarea: function(txtNode, updateId, max) {
	var numChars = dojo.number.parse(txtNode.value.length);
	var remainingChars = dojo.byId(updateId);

	var currentValue = parseInt(max) - numChars;

	if (currentValue > 0) {
	    //dojo.removeAttr(submitBtn, "disabled");
	    dojo.style(remainingChars, "color", "#222222");
	    remainingChars.innerHTML = currentValue + " characters remaining";
	} else {
	    txtNode.value = txtNode.value.slice(0, max);
	    //dojo.attr(submitBtn, "disabled", "disabled");
	    dojo.style(remainingChars, "color", "#cc0000");
	    remainingChars.innerHTML = "You have run out characters";
	}

	return;
    }
}

//---------------------- VALIDATOR FUNCTIONS --------------------------------
Z2h.validator = {
    email: function(email, required, error_id) {
	var errors = 0;
	var email_p = dojo.byId(error_id);
	var email_filter  = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;

	// validate email
	if (required && email.length == 0) {
	    errors++;

	    if (email_p) {
		email_p.innerHTML = "Email is required.";
	    }
	}

	if (errors == 0) {
	    // continue validate email
	    if (!email_filter.test(email)) {
		errors++;

		if (email_p) {
		    email_p.innerHTML = "Please enter a valid email address.";
		}
	    }
	}

	// validate form
	if (errors > 0) {
	    return false;
	} else {
	    if (email_p) {
		email_p.innerHTML = "";
	    }

	    return true;
	}
    },

    username: function(username, required, error_id) {
	var errors = 0;
	var username_p = dojo.byId(error_id);;
	var username_filter  = /^([a-zA-Z0-9])+([a-zA-Z0-9\s])*([a-zA-Z0-9])+$/;

	// validate username
	if (required && username.length == 0) {
	    errors++;

	    if (username_p) {
		username_p.innerHTML = "Username is required.";
	    }
	}

	if (errors == 0) {
	    // continue validate username
	    if (username.length < 3 || username.length > 16) {
		errors++;

		if (username_p) {
		    username_p.innerHTML = "Username must be between 3 and 16 characters long.";
		}
	    } else if (!username_filter.test(username)) {
		// username should be a-zA-Z0-9 and spaces between characters, but leading/trailing space
		errors++;

		if (username_p) {
		    username_p.innerHTML = "Username should contain only letters, numbers and spaces (no leading or trailing).";
		}
	    }
	}

	// validate form
	if (errors > 0) {
	    return false;
	} else {
	    if (username_p) {
		username_p.innerHTML = "";
	    }

	    return true;
	}
    },

    password: function(password, required, error_id) {
	var errors = 0;
	var password_p = dojo.byId(error_id);
	var password_filter  = /^(\S)+$/;

	// validate password
	if (required && password.length == 0) {
	    errors++;

	    if (password_p) {
		password_p.innerHTML = "Password is required.";
	    }
	}

	if (errors == 0) {
	    // continue validate password
	    if (!password_filter.test(password)) {
		// check password contains any white space
		errors++;

		if (password_p) {
		    password_p.innerHTML = "No white space characters are allowed in the password.";
		}
	    } else if (password.length < 6) {
		// username should be a-zA-Z0-9 and spaces between characters, but leading/trailing space
		errors++;

		if (password_p) {
		    password_p.innerHTML = "Password must be at least 6 characters long.";
		}
	    }
	}

	// validate form
	if (errors > 0) {
	    return false;
	} else {
	    if (password_p) {
		password_p.innerHTML = "";
	    }

	    return true;
	}
    }
}

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

Z2h.mailing = {
    _running: false,

    // input value messages.
    _success: "Thank You!",
    _error: "Invalid Email Address",
    _default: "Email Address",

    init: function() {
	// hook event to show/clear default value.
	var email = dojo.byId('mailing_list_email');
	if (email) {
	    dojo.connect(email,
			 "onfocus",
			 function(e){
			     e.preventDefault();

			     if (email.value == Z2h.mailing._default || email.value == Z2h.mailing._success || email.value == Z2h.mailing._error) {
				 email.value = "";
			     }

			 });

	    dojo.connect(email,
			 "onblur",
			 function(e){
			     e.preventDefault();

			     if (email.value == "") {
				 email.value = Z2h.mailing._default;
			     }

			 });
	}

	// hook onclick event to submit form.
	var mailing_btn = dojo.byId('mailing_list_submit');
	if (mailing_btn) {
	    dojo.connect(mailing_btn, 'onclick', Z2h.mailing.subscribe);
	}

	// for safari, hook onsubmit event to submit form.
	var mailing_form = dojo.byId('mailing_list');
	if (mailing_form) {
	    dojo.connect(mailing_form, 'onsubmit', Z2h.mailing.subscribe);
	}
    },

    subscribe: function(evt) {
	evt.preventDefault();

	// only send an ajax request if nothing is running.
	if (Z2h.mailing._running === false) {
	    var mailing_form = dojo.byId('mailing_list');
	    var email = dojo.byId('mailing_list_email');
	    var email_filter  = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;

	    if (mailing_form && email) {
		Z2h.mailing._running = true;

		// validate email.
		if (!email_filter.test(email.value)) {
		    email.value = Z2h.mailing._error;
		    Z2h.mailing._running = false;
		} else {
		    dojo.xhrPost({
				     url: mailing_form.action+'/format/json',
				     form: "mailing_list",
				     handleAs: "json",
				     sync: true,
				     headers: {"X-Requested-With": "XMLHttpRequest"},
				     load: function(data,ioargs){
					 if(data.result == '1'){
					     if (Z2h.tracking_id) {
						 try {
						     var googleTracker = _gat._getTracker(Z2h.tracking_id);
						     googleTracker._trackPageview('/form/newsletter/confirm/');
						 } catch (err) {}
					     }
					     email.value = Z2h.mailing._success;
					 } else {
					     email.value = data.error;
					 }

					 Z2h.mailing._running = false;

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

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

				         /* handle the error... */
				         return response; //always return the response back
				     }
				 });
		}
	    }

	    // lose focus from input box.
	    email.blur();
	}
    }
}

//---------------------- LINK JS --------------------------------
Z2h.link = {
    _running: false,

    _href: null,

    _refresh: false,

    init: function() {
	// hook event to bug report.
	var contactus_submit = dojo.byId('contactus_submit');
	if (contactus_submit) {
	    dojo.connect(contactus_submit,'onclick',Z2h.link.sendContact);
	}

	var contactus_form = dojo.byId('contactus_form');
	if (contactus_form) {
	    dojo.connect(contactus_form,'onsubmit',Z2h.link.sendContact);
	}

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

	// hook event to bug report.
	var bugReport_submit = dojo.byId('bugReport_submit');
	if (bugReport_submit) {
	    dojo.connect(bugReport_submit,'onclick',Z2h.link.bugReport);
	}

	var bug_form = dojo.byId('bug_form');
	if (bug_form) {
	    dojo.connect(bug_form,'onsubmit',Z2h.link.bugReport);
	}

	// 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) {
						 var connected = dojo.connect(link, "onclick", function(e) {
										  e.preventDefault();
										  Z2h.link.rate(link, 1, connected);
									      });
					     });

	// hook onclick event to rate down creation item
	dojo.query("a.rate_down_link").forEach(function(link) {
						   var connected = dojo.connect(link, "onclick", function(e) {
										    e.preventDefault();
										    Z2h.link.rate(link, -1, connected);
										});
					       });

	// hook onclick event to show confirm dialog to delete item
	dojo.query("a.delete").forEach(function(link) {
					   dojo.connect(link, "onclick", Z2h.link.doPostDelete);
				       });

	// hook onclick event to show dialog to send email to friend
	dojo.query("a.send_friend").forEach(function(link) {
						dojo.connect(link, "onclick", Z2h.link.sendEmailDialog);
					    });

	// hook onclick event to show dialog to flag a content
	dojo.query("a.flag").forEach(function(link) {
					 var flagHandle = dojo.connect(link, "onclick", function(e) {
									   Z2h.link.flagDialog(e, flagHandle); // need to pass flag handle to disconnect after flagging item
								       });
				     });

	// hook onclick event to show dialog to flag a content
	dojo.query("a.load_ajax").forEach(function(link) {
					      dojo.connect(link, "onclick", Z2h.link.loadAjax);
					  });

	// hook onclick event to call manage member function as ajax.
	dojo.query("a.call_ajax").forEach(function(link) {
					      dojo.connect(link, "onclick", Z2h.link.callAjax);
					  });

	// hook onclick event to select an avatar from predefined set.
	dojo.query("a.avatar_link").forEach(function(link) {
						dojo.connect(link, "onclick", Z2h.link.selectAvatar);
					    });

	var linkBehavior = {
	    ".has_tooltip": {
		onmouseover: function(evt){
	    	    var tooltipMesgDiv = dojo.byId(evt.target.id.replace("launch","tooltip"));
	    	    if ( tooltipMesgDiv ){
	    		dijit.showTooltip(tooltipMesgDiv.innerHTML, evt.target,["above","below"]);

	    	    }
		},

		onmouseout: function(evt){
		    dijit.hideTooltip(evt.target);
		}
	    }
	};

	dojo.behavior.add(linkBehavior);
    },

    // reset contact
    resetContact: function(evt) {
	var flash_msg_wide = dojo.byId('flash_msg_wide');
	if (flash_msg_wide) {
	    flash_msg_wide.style.display = "none";
	}

	var name_field = dojo.byId('contactus_name');
	if (name_field) {
	    name_field.style.border = "solid 1px #666666";
	}

	var nameError = dojo.byId("contactus_name_error");
	if (nameError) {
	    nameError.innerHTML = "";
	}

	var email_field = dojo.byId('contactus_email');
	if (email_field) {
	    email_field.style.border = "solid 1px #666666";
	}

	var emailError = dojo.byId("contactus_email_error");
	if (emailError) {
	    emailError.innerHTML = "";
	}

	var comment_field = dojo.byId('contactus_comment');
	if (comment_field) {
	    comment_field.style.border = "solid 1px #666666";
	}

	var commentError = dojo.byId("contactus_comment_error");
	if (commentError) {
	    commentError.innerHTML = "";
	}
    },

    // send contact
    sendContact: function(evt) {
	evt.preventDefault();

	var flash_msg_wide = dojo.byId('flash_msg_wide');
	if (flash_msg_wide) {
	    flash_msg_wide.style.display = "none";
	}

	// login form fields.
	var contactus_form = dojo.byId('contactus_form');
	var errors = 0;

	if (contactus_form) {
	    // validate name.
	    var name_field = dojo.byId('contactus_name');
	    if (name_field) {
		// validate username.
		var name = Z2h.string.trimAll(name_field.value);
		var nameError = dojo.byId("contactus_name_error");

		if (name.length == 0) {
		    errors++;
		    name_field.style.border = "solid 1px red";
		    if (nameError) {
			nameError.innerHTML = "Your name is required.";
		    }
		} else {
		    name_field.style.border = "solid 1px #666666";
		    if (nameError) {
			nameError.innerHTML = "";
		    }
		}
	    }

	    // validate email.
	    var email_field = dojo.byId('contactus_email');
	    var email_filter  = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
	    if (email_field) {
		var emailError = dojo.byId("contactus_email_error");

		if (email_field.value.length == 0) {
		    errors++;
		    email_field.style.border = "solid 1px red";
		    if (emailError) {
			emailError.innerHTML = "Your contact email is required.";
		    }
		} else if(!email_filter.test(email_field.value)) {
		    errors++;
		    email_field.style.border = "solid 1px red";
		    if (emailError) {
			emailError.innerHTML = "Please enter a valid email address.";
		    }
		} else {
		    email_field.style.border = "solid 1px #666666";
		    if (emailError) {
			emailError.innerHTML = "";
		    }
		}
	    }

	    // validate comment.
	    var comment_field = dojo.byId('contactus_comment');
	    if (comment_field) {
		var commentError = dojo.byId("contactus_comment_error");

		// validate username.
		var comment = Z2h.string.trimAll(comment_field.value);
		if (comment.length == 0) {
		    errors++;
		    comment_field.style.border = "solid 1px red";
		    if (commentError) {
			commentError.innerHTML = "Please provide your comment.";
		    }
		} else {
		    comment_field.style.border = "solid 1px #666666";
		    if (commentError) {
			commentError.innerHTML = "";
		    }
		}
	    }

	    // validate form.
	    if(errors == 0){
		contactus_form.submit();
	    }
	}
    },

    // send bug report
    bugReport: function(evt) {
	evt.preventDefault();

	var flash_msg_wide = dojo.byId('flash_msg_wide');
	if (flash_msg_wide) {
	    flash_msg_wide.style.display = "none";
	}

	// login form fields.
	var bug_form = dojo.byId('bug_form');
	var description_field = dojo.byId('BugReportDescription');
	var errors = 0;

	if (bug_form && description_field) {
	    // validate quote.
	    var descError = dojo.byId("bug_description_error");
	    var body = Z2h.string.trimAll(description_field.value);

	    if (body.length == 0) {
		errors++;
		description_field.style.border =  "solid 1px red";

		if (descError) {
		    dojo.style(descError, "color", "red");
		}
	    } else {
		description_field.style.border = "solid 1px black";

		if (descError) {
		    dojo.style(descError, "color", "black");
		}
	    }

	    // validate form.
	    if(errors == 0){
		bug_form.submit();
	    }
	}
    },

    // select an avatar from predefined set for signup or edit profile.
    selectAvatar: function(evt) {
	evt.preventDefault();

	var signup_avatar_field = dojo.byId('signup_avatar');

	if (signup_avatar_field) {
	    var current_avatar_name = signup_avatar_field.value;
	    var current_avatar_node = dojo.byId(current_avatar_name.split(".", 1)+'_img');

	    var new_avatar_name = evt.currentTarget.id;
	    var new_avatar_node = dojo.byId(new_avatar_name+'_img');

	    if (current_avatar_name != new_avatar_name) {
		var profile_picture = dojo.attr(new_avatar_node, "alt");

		signup_avatar_field.value = profile_picture;
		dojo.addClass(new_avatar_node, "selected_avatar");

		if (current_avatar_node) {
		    dojo.removeClass(current_avatar_node, "selected_avatar");
		}
	    }
	}
    },

    validateSelect: function(evt) {
	var checked_count = 0;
	var error_p = dojo.byId('validate_checkbox_error');

	dojo.query("input.form_checkbox").forEach(function(chk) {
						      if (chk.checked) {
							  checked_count++;
						      }
						  });

	if (checked_count > 0) {
	    if (error_p) {
		error_p.innerHTML = "";
	    }
	} else {
	    evt.preventDefault();

	    if (error_p) {
		error_p.innerHTML = "Please select users to invite or create a connection.";
	    }
	}
    },

    // select/unselect all checkbox.
    toggleSelect: function(evt) {
	evt.preventDefault();

	var checkbox_class = evt.currentTarget.id;

	if (dojo.hasClass(evt.currentTarget, 'select_all')) {
	    dojo.query("."+checkbox_class+"_checkbox").forEach("item.checked = true");

	    dojo.removeClass(evt.currentTarget, 'select_all');
	    dojo.addClass(evt.currentTarget, 'unselect_all');
	    evt.currentTarget.innerHTML = "Unselect all";
	} else if (dojo.hasClass(evt.currentTarget, 'unselect_all')) {
	    dojo.query("."+checkbox_class+"_checkbox").forEach("item.checked = false");

	    dojo.removeClass(evt.currentTarget, 'unselect_all');
	    dojo.addClass(evt.currentTarget, 'select_all');
	    evt.currentTarget.innerHTML = "Select all";
	}
    },

    // thumbs up/down a creation item
    rate: function(link, point, connection) {
	// get rating link and parent class
	var href = dojo.attr(link, "href");
	var update_dom_id = dojo.attr(link, "alt");
	var classes = dojo.attr(link,'class');

	if ( point == 1 ){
	    classes = classes.replace("rate_up_link ","");
	} else {
	    classes = classes.replace("rate_down_link ","");
	}

	dojo.xhrGet({
			url: href + "/format/json",
			handleAs: "json",
			sync: true,
			headers: {"X-Requested-With": "XMLHttpRequest"},
			load: function(data,ioargs) {
			    if (data.result == "1") {
				if (data.pointsMesg != null) {
				    Z2h.tooltip.popups(data.pointsMesg,'points');
				}

				var list = dojo.byId(update_dom_id + "_list");
				list.innerHTML = "<li><p class='"+classes+" chosen_rating'>" + ((point == 1)?"Rated Up":"Rated Down") + "</p></li>";
				// update rating number
				var rating_dom = dojo.byId(update_dom_id);

				if (rating_dom) {
				    var rating_node = dojo.query("p > span.rated_up", rating_dom)[0];

				    if (!rating_node) {
					rating_node = dojo.query("p > span.rated_down", rating_dom)[0];
				    }

				    /*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;
				    var rating_description = "";

				    if (current_rating_number.search(/ Like This/i) != -1) {
					rating_description = " Like This";
					current_rating_number.replace(/ Like This/i, "");
				    } else if (current_rating_number.search(/Dislike This/i) != -1) {
					rating_description = " Dislike This";
					current_rating_number.replace(/ Dislike This/i, "");
					current_rating_number = parseInt(current_rating_number) * -1;
				    }

				    // update rating_number (with + or -)
				    current_rating_number = parseInt(current_rating_number) + parseInt(point);

				    if (current_rating_number >= 0) {
					if (rating_description != "") {
					    rating_node.innerHTML = current_rating_number + " Like This";
					} else {
					    if (current_rating_number > 0) {
						rating_node.innerHTML = "+" + current_rating_number;
					    } else {
						rating_node.innerHTML = current_rating_number;
					    }
					}

					dojo.removeClass(rating_node, "rated_down");
					dojo.addClass(rating_node, "rated_up");
				    } else {
					if (rating_description != "") {
					    rating_node.innerHTML = (current_rating_number * -1)+ " Dislike This";
					} else {
					    rating_node.innerHTML = current_rating_number;
					}

					dojo.removeClass(rating_node, "rated_up");
					dojo.addClass(rating_node, "rated_down");
				    }
				}

				// also update ratings count for today
				var stats_box = dojo.byId("logged_in_stats");
				if (stats_box) {
				    var rating_count_node = dojo.query("ul > li.logged_in_rating_stat > p", stats_box)[0];

				    // get the current rating count
				    var current_rating = rating_count_node.innerHTML;
				    var current_rating_count = current_rating.replace(" rating", "");
				    current_rating_count = current_rating_count.replace("s", "");

				    // update rating count
				    current_rating_count = parseInt(current_rating_count) + 1;

				    if (current_rating_count != 1) {
					rating_count_node.innerHTML = current_rating_count + " ratings";
				    } else {
					rating_count_node.innerHTML = current_rating_count + " rating";
				    }
				}
			    } else {
				// reload the page
				window.location.reload(true);
			    }

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

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

			    /* handle the error... */
			    return response; //always return the response back
			}
		    });

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

    // load action by ajax call
    callAjax: function(evt) {
	evt.preventDefault();

	dojo.xhrGet({
			url: evt.currentTarget.href+"/format/json",
			handleAs: "json",
			sync: true,
			headers: {"X-Requested-With": "XMLHttpRequest"},
			load: function(data,ioargs){
			    if (data.result == "1") {
		 		var call_back = dojo.byId('do_after_callback');
				if (call_back) {
				    if (document.createEvent) {
					// Firefox etc.
					event = document.createEvent("HTMLEvents");
					event.initEvent("click", false, true);
					call_back.dispatchEvent(event);
				    } else {
					// IE
					call_back.fireEvent("onclick");
				    }
				} else {
				    // refresh the current page
				    window.location.reload(true);
				}
		 	    } else {
		 		// refresh the current page
				window.location.reload(true);
		 	    }

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

			    alert("ERROR: There was an error while submitting your form. Please try again!");
			    /* handle the error... */
			    return response; //always return the response back
			}
		    });
    },

    // load content by ajax call
    loadAjax: function(evt) {
	evt.preventDefault();

	// update dom id (make sure there is div id=load_ajax_content_here)
	var update_dom = dojo.byId("load_ajax_content_here");

	// while loading (make sure there is div id=load_ajax_content_loading)
	var loading_wait = dojo.byId("load_ajax_content_loading");

	// ajax requst url
	var href = evt.currentTarget.href;

	// only send an ajax request if nothing is running and the dom exists
	if (update_dom && Z2h.link._running === false) {
	    Z2h.link._running = true;

	    if (loading_wait) {
		update_dom.style.display = "none";
		loading_wait.style.display = "";
	    }

	    dojo.xhrGet({
			    url: href + "/format/text/",
			    handleAs: "text",
			    //			 	sync: true,
			    // run this function if the request is successful
		            load : function(response, ioArgs) {
				// set some element's content
				update_dom.innerHTML = response;

				if (loading_wait) {
				    loading_wait.style.display = "none";
				    update_dom.style.display = "";
				}

				// initialize js
				Z2h.global.init();
				dojo.behavior.apply();

				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", 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";
	    }
	}
    }
}

//---------------------- COMMUNITY COMMENT JS --------------------------------
Z2h.comment = {
    _running: false,

    init: function() {
	Z2h.comment.initEditor();
	Z2h.comment.initAjax();
    },

    initEditor: function() {
	dojo.query(".reply_text").forEach(function(textarea) {
					      var errors = 0;
					      dojo.query("div.error_msg", textarea.parentNode).forEach(function(err) {
													   errors++;
												       });

					      if (textarea.value.length == 0 && errors == 0) {
						  dojo.style(textarea, "height", "14px");
					      }

					      dojo.connect(textarea, "onfocus", Z2h.comment.expand);
					      dojo.connect(textarea, "onblur", Z2h.comment.shrink);
					  });

	dojo.query(".text_length_aid").forEach(function(aid) {
						   var id = aid.id;
						   var textarea_dom = dojo.byId(id + "_textarea");
						   //var submitButton = dojo.byId(id + "_submit");

						   var length = 1000;

						   if (dojo.hasAttr(aid, "title")) {
						       length = dojo.attr(aid, "title");
						   }

						   // if (textarea_dom && submitButton) {
						   if (textarea_dom) {
			 			       Z2h.string.countTextarea(textarea_dom, id, length);

						       dojo.connect(textarea_dom, "onkeyup", function() {
									Z2h.string.countTextarea(textarea_dom, id, length);
		    						    });
						   }
					       });
    },

    initAjax: function() {
	dojo.query(".show_no_replies").forEach(function(link) {
						   var showHandle = dojo.connect(link, "onclick", function(e) {
										     Z2h.comment.showNoReplies(e);
										     dojo.disconnect(showHandle);
										 });
					       });

	dojo.query(".hide_no_replies").forEach(function(link) {
						   var hideHandle = dojo.connect(link, "onclick", function(e) {
										     Z2h.comment.hideNoReplies(e);
										     dojo.disconnect(hideHandle);
										 });
					       });

	dojo.query(".more_replies").forEach(function(link) {
						var showHandle = dojo.connect(link, "onclick", function(e) {
										  Z2h.comment.showMoreReplies(e);
										  dojo.disconnect(showHandle);
									      });
					    });

	dojo.query(".less_replies").forEach(function(link) {
						var hideHandle = dojo.connect(link, "onclick", function(e) {
										  Z2h.comment.hideMoreReplies(e);
										  dojo.disconnect(hideHandle);
									      });
					    });

	dojo.query(".add_post_reply").forEach(function(btn) {
						  dojo.connect(btn, "onclick", Z2h.comment.addReply);
					      });

	var add_comment = dojo.byId("discussion_comment_submit");

	if (add_comment) {
	    dojo.connect(add_comment, "onclick", Z2h.comment.addComment);
	}
    },

    // called after a new comment is added successfully
    refresh: function(href) {
	// update comment count in the view post page and login section
	dojo.query(".discussion_comment_count").forEach(function(link) {
							    var current_count = dojo.attr(link, "alt");
							    var current_text = link.innerHTML;

							    var new_count = parseInt(current_count) + 1;
							    var new_text = "";

							    if (new_count != 1) {
								new_text = new_count + " comments";
							    } else {
								new_text = new_count + " comment";
							    }

							    if (dojo.hasAttr(link, "title")) {
								dojo.attr(link, "title", new_text);
							    }
							    dojo.attr(link, "alt", new_count);
							    link.innerHTML = new_text;
							});

	// update dom id. (make sure there is div id=load_ajax_content_here)
	var update_dom = dojo.byId("load_ajax_content_here");

	// only send an ajax request if nothing is running and the dom exists
	if (update_dom) {
	    // reload the comment list
	    dojo.xhrGet({
			    url: href + "/format/text/",
			    handleAs: "text",
    		 	    sync: true,
			    // run this function if the request is successful
		            load : function(response, ioArgs) {
				// set some element's content
				update_dom.innerHTML = response;

				// initialize js
				Z2h.global.init();

				return response; //always return the response back
		            },
		            // run this function if the request is not successful
		            error : function(response, ioArgs) {
				console.log("failed xhrGet", response, ioArgs);

				alert("ERROR: There was an error while submitting your request. Please try again!");
				/* handle the error... */
				return response; //always return the response back
		            }
			});
	}
    },

    addComment: function(evt) {
	evt.preventDefault();

	var comment_form = dojo.byId("comment_post_form");
	var comment_section = dojo.byId("comment_post_new");

	// only send an ajax request if nothing is running and the dom exists.
	if (comment_form && Z2h.comment._running === false) {
	    Z2h.comment._running = true;

	    var overlay_wait = dojo.byId("comment_post_new_loading");

	    if (overlay_wait) {
		comment_section.style.display = "none";
		overlay_wait.style.display = "block";
	    }

	    dojo.xhrPost({
			     url: comment_form.action+"/format/json",
			     form: comment_form.id,
			     handleAs: "json",
			     //				sync: true,
			     headers: {"X-Requested-With": "XMLHttpRequest"},
			     load: function(data,ioargs){
				 if(data.result == "-1"){
				     // reload the page.
				     window.location.reload(true);
				 } else if(data.result == "1"){
				     var hidden_url = dojo.byId("comment_post_new_after_url");

				     if (hidden_url) {
					 Z2h.comment.refresh(hidden_url.value);
					 if (data.pointsMesg != null) {
					     Z2h.tooltip.popups(data.pointsMesg,'points');
					 }

				     } else {
					 // reload the page
					 window.location.reload(true);
				     }

				 }else{
				     if (overlay_wait) {
					 overlay_wait.style.display = "none";
					 comment_section.style.display = "block";
				     }

				     var comment_errors = dojo.byId("comment_post_new_error");

				     if (comment_errors) {
					 comment_errors.innerHTML = "";

					 for(var k in data.errors){
					     var errorItem = document.createElement('p');
					     errorItem.innerHTML = data.errors[k][0];
					     comment_errors.appendChild(errorItem);
					 }
				     }
				 }

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

				 alert("ERROR: There was an error while submitting your comment form. Please try again!");
				 /* handle the error... */
			         return response; //always return the response back
			     }
			 });

	    Z2h.comment._running = false;
	}
    },

    addReply: function(evt) {
	evt.preventDefault();

	var update_dom_id = dojo.attr(evt.currentTarget, "name");
	var update_dom = dojo.byId(update_dom_id);
	var reply_form = dojo.byId("reply_form_" + update_dom_id);
	var hidden_url = dojo.byId(update_dom_id + "_after_url");

	var button_id = evt.target.id;
	var reply_textarea_id = button_id.replace("submit", "textarea");
	var reply_p_id = button_id.replace("_submit", "");
	var error_id = button_id.replace("submit", "error");
	var reply_text = dojo.byId(reply_textarea_id);

	// only send an ajax request if nothing is running and the dom exists
	if (reply_form && reply_text && Z2h.comment._running === false) {
	    Z2h.comment._running = true;

	    var overlay_wait = dojo.byId(update_dom_id + "_loading");
	    var form_section = dojo.byId(update_dom_id + "_form_section");

	    if (overlay_wait && form_section) {
		form_section.style.display = "none";
		overlay_wait.style.display = "";
	    }

	    dojo.xhrPost({
			     url: reply_form.action + "/format/json",
			     form: reply_form.id,
			     handleAs: "json",
			     //				sync: true,
			     headers: {"X-Requested-With": "XMLHttpRequest"},
			     load: function(data,ioargs){
				 if (data.result == "-1") {
				     // reload the page
				     window.location.reload(true);
				 } else if(data.result == "1") {
				     if (hidden_url && update_dom) {
					 // load the updated comment list.
					 dojo.xhrGet({
							 url: hidden_url.value + "/offset/0/format/text",
							 handleAs: "text",
							 //							 	sync: true,
							 // run this function if the request is successful
						         load : function(response, ioArgs) {
							     // set some element's content
							     update_dom.innerHTML= response;

							     Z2h.comment.init();

							     // initialize flag link
							     dojo.query("a.flag").forEach(function(link) {
											      var flagHandle = dojo.connect(link, "onclick", function(e) {
																Z2h.link.flagDialog(e, flagHandle); // need to pass flag handle to disconnect after flagging item.
															    });
											  });

						             return response; //always return the response back
						         },
						         // run this function if the request is not successful
						         error : function(response, ioArgs) {
						             console.log("failed xhrGet", response, ioArgs);

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

						             /* handle the error... */
						             return response; //always return the response back
						         }
						     });
				     }

				 } else {
				     if (overlay_wait && form_section) {
					 overlay_wait.style.display = "none";
					 form_section.style.display = "";
				     }

				     var comment_errors = dojo.byId(error_id);

				     if (comment_errors) {
					 comment_errors.innerHTML = "";

					 for(var k in data.errors){
					     var errorItem = document.createElement("p");
					     errorItem.innerHTML = data.errors[k][0];
					     comment_errors.appendChild(errorItem);
					 }
				     }

				     dojo.attr(reply_text, "style", "height:150px;");
				 }

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

				 alert("ERROR: There was an error while submitting your reply form. Please try again!");
				 /* handle the error... */
			         return response; //always return the response back
			     }
			 });

	    Z2h.comment._running = false;
	}
    },

    showNoReplies: function(evt) {
	evt.preventDefault();

	var update_dom_id = dojo.attr(evt.currentTarget, "alt");
	var clicked = evt.currentTarget;

	var update_dom = dojo.byId("first_reply_" + update_dom_id);

	// only send an ajax request if nothing is running and the dom exists
	if (update_dom && Z2h.comment._running === false) {
	    Z2h.comment._running = true;

	    dojo.query("li.no_replies", update_dom).forEach(function(node) {
								node.style.display = "";
							    });

	    dojo.removeClass(evt.currentTarget, "show_no_replies");
	    dojo.removeClass(evt.currentTarget, "collapsed_replies");

	    dojo.addClass(evt.currentTarget, "hide_no_replies");
	    dojo.addClass(evt.currentTarget, "expanded_replies");

	    var hideHandle = dojo.connect(evt.currentTarget, "onclick", function(e){
					      Z2h.comment.hideNoReplies(e);
					      dojo.disconnect(hideHandle);
					  });

	    Z2h.comment._running = false;
	}
    },

    hideNoReplies: function(evt) {
	evt.preventDefault();

	var update_dom_id = dojo.attr(evt.currentTarget, "alt");
	var clicked = evt.currentTarget;

	var update_dom = dojo.byId("first_reply_" + update_dom_id);

	// only send an ajax request if nothing is running and the dom exists.
	if (update_dom && Z2h.comment._running === false) {
	    Z2h.comment._running = true;

	    dojo.query("li.no_replies", update_dom).forEach(function(node) {
								node.style.display = "none";
							    });

	    dojo.removeClass(evt.currentTarget, "hide_no_replies");
	    dojo.removeClass(evt.currentTarget, "expanded_replies");

	    dojo.addClass(evt.currentTarget, "show_no_replies");
	    dojo.addClass(evt.currentTarget, "collapsed_replies");

	    var showHandle = dojo.connect(evt.currentTarget, "onclick", function(e){
					      Z2h.comment.showNoReplies(e);
					      dojo.disconnect(showHandle);
					  });

	    Z2h.comment._running = false;
	}
    },

    showMoreReplies: function(evt) {
	evt.preventDefault();

	var href = evt.currentTarget.href;
	var update_dom_id = dojo.attr(evt.currentTarget, "alt");
	var clicked = evt.currentTarget;

	var update_dom = dojo.byId(update_dom_id);

	// only send an ajax request if nothing is running and the dom exists
	if (update_dom && Z2h.comment._running === false) {
	    Z2h.comment._running = true;

	    var overlay_wait = dojo.byId(update_dom_id + "_loading");

	    if (overlay_wait) {
		overlay_wait.style.display = "";
	    }

	    // check the ajax request is made previously
	    var already_requested = dojo.query('ul.hide_comment_replies_list', update_dom).length;
	    var hidden_replies_dom = null;

	    if (already_requested == 1) {
		hidden_replies_dom = dojo.query('ul.hide_comment_replies_list', update_dom)[0];
		dojo.removeClass(hidden_replies_dom, 'hide_comment_replies_list');
		update_dom.style.display = "";
	    } else {
		// hide the link from user double clicking
		evt.currentTarget.style.display = "none";

		// if not, call a ajax request
		dojo.xhrGet({
				url: href + "/format/text",
				handleAs: "text",
				sync: true,
				// run this function if the request is successful
			        load : function(response, ioArgs) {
				    // set some element's content
				    update_dom.innerHTML= response;

				    // initialize editor
				    Z2h.comment.initEditor();

				    // initialize rating links
				    dojo.query('a.rate_up_link').forEach(function(link) {
									     var connected = dojo.connect(link, "onclick", function(e){
													      e.preventDefault();
													      Z2h.link.rate(link, 1, connected);
													  });
									 });

				    // hook onclick event to rate down creation item
				    dojo.query('a.rate_down_link').forEach(function(link) {
									       var connected = dojo.connect(link,
													    "onclick",
													    function(e){
														e.preventDefault();
														Z2h.link.rate(link, -1, connected);
													    });
									   });

				    // initialize flag link.
				    dojo.query('a.flag').forEach(function(link) {
								     var flagHandle = dojo.connect(link, 'onclick', function(e){
												       Z2h.link.flagDialog(e, flagHandle); // need to pass flag handle to disconnect after flagging item.
												   });
								 });

			            return response; //always return the response back
			        },
			        // run this function if the request is not successful
			        error : function(response, ioArgs) {
			            console.log("failed xhrGet", response, ioArgs);

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

			            /* handle the error... */
			            return response; //always return the response back
			        }
			    });
	    }

	    evt.currentTarget.style.display = "";

	    dojo.removeClass(evt.currentTarget, "more_replies");
	    dojo.addClass(evt.currentTarget, "less_replies");

	    var link_span = evt.currentTarget.innerHTML;
	    var new_link_span = link_span.replace("+ Show","- Hide");
	    var new_title = new_link_span.replace("<span>- ","");
	    new_title = new_title.replace("</span>","");

	    evt.currentTarget.innerHTML = new_link_span;
	    dojo.attr(evt.currentTarget, "title", new_title);

	    var hideHandle = dojo.connect(evt.currentTarget,
					  "onclick",
					  function(e){
					      Z2h.comment.hideMoreReplies(e);
					      dojo.disconnect(hideHandle);
					  });

	    if (overlay_wait) {
		overlay_wait.style.display = "none";
	    }

	    Z2h.comment._running = false;
	}
    },

    hideMoreReplies: function(evt) {
	evt.preventDefault();

	var href = evt.currentTarget.href;
	var update_dom_id = dojo.attr(evt.currentTarget, "alt");
	var clicked = evt.currentTarget;

	var update_dom = dojo.byId(update_dom_id);

	// only send an ajax request if nothing is running and the dom exists.
	if (update_dom && Z2h.comment._running === false) {
	    Z2h.comment._running = true;

	    update_dom.style.display = "none";

	    // check the ajax request is made previously.
	    var already_requested = dojo.query('ul.comment_replies_list', update_dom).length;
	    var replies_dom = null;

	    if (already_requested == 1) {
		replies_dom = dojo.query('ul.comment_replies_list', update_dom)[0];
		dojo.addClass(replies_dom, 'hide_comment_replies_list');
	    }

	    dojo.removeClass(evt.currentTarget, "less_replies");
	    dojo.addClass(evt.currentTarget, "more_replies");

	    var link_span = evt.currentTarget.innerHTML;
	    var new_link_span = link_span.replace("- Hide","+ Show");

	    var new_title = new_link_span.replace("<span>+ ","");
	    new_title = new_title.replace("</span>","");

	    evt.currentTarget.innerHTML = new_link_span;
	    dojo.attr(evt.currentTarget, "title", new_title);

	    var showHandle = dojo.connect(evt.currentTarget,
					  "onclick",
					  function(e){
					      Z2h.comment.showMoreReplies(e);
					      dojo.disconnect(showHandle);
					  });

	    Z2h.comment._running = false;
	}
    },

    expand: function(evt) {
	var errors = 0;
	dojo.query('div.error_msg', evt.currentTarget.parentNode).forEach(function(err) {
									      if (err.innerHTML) {
										  errors++;
									      }
									  });

	if (evt.currentTarget.value.length == 0 && errors == 0) {
	    dojo.animateProperty({
				     node : evt.currentTarget,
				     duration : 350,
				     properties : {
			    		 height : {start: '14', end: '150'}
				     }
				 }).play();
	}
    },

    shrink: function(evt) {
	var errors = 0;
	dojo.query('div.error_msg', evt.currentTarget.parentNode).forEach(function(err) {
									      if (err.innerHTML) {
										  errors++;
									      }
									  });

	if (evt.currentTarget.value.length == 0 && errors == 0) {
	    dojo.animateProperty({
				     node : evt.currentTarget,
				     duration : 350,
				     properties : {
			    		 height : {start: '150', end: '14'}
				     }
				 }).play();
	}
    }
}

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

Z2h.inbox = {
    _href: null,

    init: function() {
	// hook onchange event to select messages.
	var mark_select_link = dojo.byId('mark_as_select');
	if (mark_select_link) {
	    dojo.connect(mark_select_link, 'onchange', Z2h.inbox.markSelect);
	}

	// hook onclick event to mark all the selected messages as read.
	var mark_read_link = dojo.byId('markAsRead');
	if (mark_read_link) {
	    dojo.connect(mark_read_link, 'onclick', Z2h.inbox.markRead);
	}

	// hook onclick event to mark all the selected messages as unread.
	var mark_unread_link = dojo.byId('markAsUnread');
	if (mark_unread_link) {
	    dojo.connect(mark_unread_link, 'onclick', Z2h.inbox.markUnread);
	}

	// hook onclick event to delete all the selected messages.
	var mark_hidden_link = dojo.byId('markAsHidden');
	if (mark_hidden_link) {
	    dojo.connect(mark_hidden_link, 'onclick', Z2h.inbox.markHidden);
	}
    },

    markSelect: function(evt) {
	evt.preventDefault();

	switch (evt.currentTarget.value) {
	case 'all':
	    Z2h.inbox.selectAll();
	    break;

	case 'unread':
	    Z2h.inbox.selectUnread();
	    break;

	case 'read':
	    Z2h.inbox.selectRead();
	    break;

	default:
	    Z2h.inbox.selectNone();
	}
    },

    selectAll: function() {
	dojo.query(".message_unread").concat(
	    dojo.query(".message_read").concat(
		dojo.query(".message_reply"))).forEach("item.checked = true");
    },

    selectUnread: function() {
	Z2h.inbox.selectNone();

	// message_unread
	dojo.query(".message_unread").forEach("item.checked = true");

    },

    selectRead: function() {
	Z2h.inbox.selectNone();

	// message_read && message_reply
	dojo.query(".message_read").concat(
	    dojo.query(".message_reply")).forEach("item.checked = true");
    },

    selectNone: function() {
	dojo.query(".message_unread").concat(
	    dojo.query(".message_read").concat(
		dojo.query(".message_reply"))).forEach("item.checked = false");
    },

    markRead: function(evt) {
	evt.preventDefault();

	var items = new Array();
	dojo.query(".message_unread").concat(
	    dojo.query(".message_read").concat(
		dojo.query(".message_reply"))).forEach(
		    function(item){
			if (item.checked) {
			    items.push(item.value);
			}
		    });

	// check as least one message is selected.
	if (items.length > 0) {
	    items = items.join(";");

	    window.location.assign(evt.currentTarget.value+"/ids/"+items);
	} else {
	    Z2h.link.error("Please select at least one message to mark as read.");
	}
    },

    markUnread: function(evt) {
	evt.preventDefault();

	var items = new Array();
	dojo.query(".message_unread").concat(
	    dojo.query(".message_read").concat(
		dojo.query(".message_reply"))).forEach(
		    function(item){
			if (item.checked) {
			    items.push(item.value);
			}
		    });

	// check as least one message is selected.
	if (items.length > 0) {
	    items = items.join(";");

	    window.location.assign(evt.currentTarget.value+"/ids/"+items);
	} else {
	    Z2h.link.error("Please select at least one message to mark as unread.");
	}
    },

    markHidden: function(evt) {
	evt.preventDefault();

	var items = new Array();
	dojo.query(".message_unread").concat(
	    dojo.query(".message_read").concat(
		dojo.query(".message_reply"))).forEach(
		    function(item){
			if (item.checked) {
			    items.push(item.value);
			}
		    });

	// check as least one message is selected.
	if (items.length > 0) {
	    var questionString = "Are you sure you want to delete";

	    if (items.length > 1) {
		questionString += " these messages?";
	    } else {
		questionString += " this message?";
	    }

	    questionString += " Deleting a message will not block particient from replying to the message.";

	    items = items.join(";");

	    Z2h.inbox._href = evt.currentTarget.value+"/ids/"+items;

	    Z2h.link.popup('delete_confirm_overlay', 'Delete Confirmation', questionString, Z2h.inbox.okDeleteAll);
	} else {
	    Z2h.link.error("Please select at least one message to delete.");
	}
    },

    // send post request to delete all item.
    okDeleteAll: function() {
	window.location.assign(Z2h.inbox._href);

	Z2h.inbox._href = null;
    }
}

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

Z2h.inbox.recipients = {
    init: function() {
	// hook onclick event to remove a recipient from recipients list.
	dojo.query('a.remove_user').forEach(function(link) {
						dojo.connect(link, 'onclick', Z2h.inbox.recipients.remove);
					    });

	var total = Z2h.inbox.recipients.total();
	if (total > 1) {
	    var select = dijit.byId('username_select');
	    if (select) {
		select.promptMessage = '';
		select.invalidMessage = '';
	    }
	}
    },

    // count total number of recipients.
    total: function() {
	var total = 0;
	var hiddenRecipients = dojo.byId('hidden_recipients');

	if (hiddenRecipients) {
	    // check the maximum recipients.
	    dojo.query("div#hidden_recipients input.hidden_to").forEach(function(node, i){
			   						    total++;
									});
	}

	return total;
    },

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

	select.promptMessage = '';
	select.invalidMessage = '';
    },

    // check username is available from the options.
    check: function(select) {
	var user_id = select.getValue();
	var username = select.textbox.value;
	var total = Z2h.inbox.recipients.total();
	var added = 0;

	if (user_id && username) {
	    dojo.query("div#hidden_recipients > input.recipient_"+user_id).forEach(function(node, i){
										       added++;
										   });

	    if (added == 0) {
		if (total < 20) {
		    // add the user to recipient container.
		    Z2h.inbox.recipients.add(user_id, username);
		    select.promptMessage = '';
		    select.invalidMessage = '';
		    total++;
		}
	    } else {
		select.promptMessage = 'You already added '+username;
	    }

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

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

    // add a recipient.
    add: function(id, username) {
	// add to hidden recipients list.
	var hiddenRecipients = dojo.byId('hidden_recipients');

	if (hiddenRecipients) {
	    var inputHiddenTo = document.createElement("input");

	    dojo.addClass(inputHiddenTo, "hidden_to");
	    dojo.addClass(inputHiddenTo, "recipient_"+id);
	    dojo.attr(inputHiddenTo, "type", "hidden");
	    dojo.attr(inputHiddenTo, "name", "recipient_to["+id+"]["+username+"]");
	    dojo.attr(inputHiddenTo, "value", id);

	    dojo.place(inputHiddenTo, hiddenRecipients, "last");

	    // create recipient container box.
	    var hiddenContainer = dojo.byId('hidden_container');

	    if (hiddenContainer) {
		var divRecipientBox = document.createElement("div");
		dojo.addClass(divRecipientBox, "recipient_box");
		dojo.addClass(divRecipientBox, "recipient_"+id);
		divRecipientBox.innerHTML = username;

		var aRecipientRemoveLink = document.createElement("a");
		dojo.addClass(aRecipientRemoveLink, "remove_user");
		dojo.attr(aRecipientRemoveLink, "id", id);
		dojo.attr(aRecipientRemoveLink, "alt", username);
		dojo.attr(aRecipientRemoveLink, "title", "Remove this user from recipients?");
		aRecipientRemoveLink.innerHTML = "x";

		// hook remove recipient event to x.
		dojo.connect(aRecipientRemoveLink, "onclick", Z2h.inbox.recipients.remove);

		dojo.place(aRecipientRemoveLink, divRecipientBox, "last");
		dojo.place(divRecipientBox, hiddenContainer, "last");

		// delete the username from the option list.
		/* z2h_users.fetch({
		 onItem: function(item) {
		 if (z2h_users.hasAttribute(item, "id")) {
		 var this_id = z2h_users.getValue(item, "id");
		 if (this_id == id) {
		 z2h_users.setValue(item, "status", '0');
		 }
		 }
		 }
		 }); */
	    }
	}
    },

    // remove a recipient.
    remove: function(evt) {
	evt.preventDefault();

	var remove_id = evt.currentTarget.id;
	var remove_user = dojo.byId(remove_id);

	if (remove_id && remove_user) {
	    var remove_username = dojo.attr(remove_user, "alt");

	    var total = Z2h.inbox.recipients.total();

	    dojo.query(".recipient_"+remove_id).forEach(function(node, i){
							    node.parentNode.removeChild(node);
							});

	    /*z2h_users.fetch({
	     onItem: function(item) {
	     if (z2h_users.hasAttribute(item, "id")) {
	     var this_id = z2h_users.getValue(item, "id");
	     var this_status = z2h_users.getValue(item, "status");
	     if (this_id == remove_id && this_status == '0') {
	     z2h_users.setValue(item, "status", '10');
	     }
	     }
	     }
	     });*/

	    // if select option was disabled, clear the restriction.
	    total--;

	    if (total < 20) {
		var select = dijit.byId('username_select');

		if (total < 1) {
		    select.promptMessage = 'start typing a username';
		    select.invalidMessage = 'no such username found';
		} else {
		    select.promptMessage = '';
		    select.invalidMessage = '';
		}

		select.setDisabled(false);
		select.textbox.value = '';
		select.focus();
	    }
	}
    }
}

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

Z2h.user = {
    _running: false,
    _usernameLabel: "username",
    _passwordLabel: "password",
    _emailLabel: "email address",

    init: function() {
	Z2h.user.resetForms();

	// hook onclick event to show login form.
	var login_link = dojo.byId('back_to_login');
	if (login_link) {
	    dojo.connect(login_link, 'onclick', Z2h.user.showLogin);
	}

	var remember_login = dojo.byId('remember_login');
	if (remember_login) {
	    dojo.connect(remember_login, 'onclick', Z2h.user.showLogin);
	}

	// hook onclick event to submit login form.
	var login_submit_btn = dojo.byId('login_submit');
	if (login_submit_btn) {
	    dojo.connect(login_submit_btn, 'onclick', Z2h.user.login);
	}

	// for safari, hook onsubmit event to submit login form.
	var login_submit_form = dojo.byId('login_form');
	if (login_submit_form) {
	    dojo.connect(login_submit_form, 'onsubmit', Z2h.user.login);
	}

	// hook onclick event to show forgot password form.
	var forgot_password_link = dojo.byId('forgot_password_link');
	if (forgot_password_link) {
	    dojo.connect(forgot_password_link, 'onclick', Z2h.user.showForgot);
	}

	// hook onclick event to show signup form.
	var register_link = dojo.byId('register_link');
	if (register_link) {
	    dojo.connect(register_link,
			 "onclick",
			 function(e){
			     e.preventDefault();
			     Z2h.user.showSignupForm();
	    		 });
	}

	var signupBehavior = {
	    ".show_signup_arrow": {
		'onclick' : function(e){
		    Z2h.user.showSignupForm();
		    Z2h.notificationArrow.notify("signup_form_section");
		}
	    },

	    ".hide_signup_arrow": {
		'onclick' : function(e){
		    Z2h.notificationArrow.destroy();
		    Z2h.user.showLogin(e);
		}
	    }
	}

	dojo.behavior.add(signupBehavior);

	// hook onclick event to submit forgot password form.
	var forgot_submit_btn = dojo.byId('lost_password_submit');
	if (forgot_submit_btn) {
	    dojo.connect(forgot_submit_btn, 'onclick', Z2h.user.forgot);
	}

	// for safari, hook onsubmit event to submit forgot password form.
	var forgot_submit_form = dojo.byId('forgot_form');
	if (forgot_submit_form) {
	    dojo.connect(forgot_submit_form, 'onsubmit', Z2h.user.forgot);
	}

	// hook onclick event to submit sign form.
	var submitButton = dojo.byId('signup_submit_quick');
	if (submitButton) {
	    dojo.connect(submitButton,
			 "onclick",
			 function(e){
			     e.preventDefault();
			     Z2h.user.signupQuick();
	    		 });
	}

	// for safari, hook onsubmit event to submit sign form.
	var signup_post_form = dojo.byId('signup_form_quick');
	if (signup_post_form) {
	    dojo.connect(signup_post_form,
			 "onsubmit",
			 function(e){
			     e.preventDefault();
			     Z2h.user.signupQuick();
	    		 });
	}

	// hook onclick event to show dialog to sign up.
	dojo.query('a.signup').forEach(function(link) {
					   dojo.connect(link, 'onclick', Z2h.user.showSignup);
				       });

	dojo.subscribe("/flash/voting/reload/",dojo.hitch(this,'updateCapital'));
    },

    updateCapital: function(){
	dojo.xhrPost({
			 url: '/user/profile/get-capital/format/json',
			 handleAs: "json",
			 headers: {"X-Requested-With": "XMLHttpRequest"},
			 load: function(data,ioargs){
			     if ( data.points ) {
				 dojo.query(".user_capital").forEach( function(node,index,list){
									  dojo.attr(node,'innerHTML', data.points);
								      });
				 dojo.query(".user_capital_this_week").forEach( function(node,index,list){
										    dojo.attr(node,'innerHTML', data.points_last_week);
										});
			     }
			     return data; //always return the response back
			 },
			 // if any error occurs, it goes here:
			 error : function(response, ioArgs) {
			     console.log("failed xhrGet", response, ioArgs);

			     /* handle the error... */
			     return response; //always return the response back
			 }
		     });
    },

    resetForms: function() {

	// LOGIN FORM RESET
	//==========================================================================

	// login form fields.
	var login_username_field = dojo.byId('login_username');
	var login_passwd_field = dojo.byId('login_passwd');
	var login_passwd_txt_field = dojo.byId('login_passwd_txt');
	var login_error_msg = dojo.byId('login_form_error_msg');
	var login_passwd_txt_field = dojo.byId('login_passwd_txt');

	if (login_username_field) {
	    // reset values.
	    login_error_msg.style.display = "none";
	    login_error_msg.innerHTML = "";

	    if (dojo.hasClass(login_username_field, 'input_new') && login_username_field.value.length == 0) {
		login_username_field.value = Z2h.user._usernameLabel;
		dojo.addClass(login_username_field, "input_empty");

		dojo.connect(login_username_field,
			     "onfocus",
			     function(e){
				 e.preventDefault();
				 var username = Z2h.string.trimAll(login_username_field.value);

				 if (username == Z2h.user._usernameLabel) {
				     login_username_field.value = "";
				     dojo.removeClass(login_username_field, "input_empty");
				 }
			     });

		dojo.connect(login_username_field,
			     "onblur",
			     function(e){
				 e.preventDefault();
				 var username = Z2h.string.trimAll(login_username_field.value);

				 if (username.length == 0) {
				     login_username_field.value = Z2h.user._usernameLabel;
				     dojo.addClass(login_username_field, "input_empty");
				 }

			     });
	    }

	    if (login_passwd_txt_field && dojo.hasClass(login_passwd_txt_field, 'input_new') && login_passwd_field.value.length == 0) {
		login_passwd_txt_field.value = Z2h.user._passwordLabel;
		login_passwd_txt_field.style.display = "";

		login_passwd_field.value = "";
		login_passwd_field.style.display = "none";

		dojo.connect(login_passwd_txt_field,
			     "onfocus",
			     function(e){
				 e.preventDefault();
				 login_passwd_txt_field.style.display = "none";
				 login_passwd_field.style.display = "";
				 login_passwd_field.focus();
			     });

		dojo.connect(login_passwd_field,
			     "onblur",
			     function(e){
				 e.preventDefault();
				 var password = Z2h.string.trimAll(login_passwd_field.value);

				 if (password.length == 0) {
				     login_passwd_txt_field.style.display = "";
				     login_passwd_field.style.display = "none";
				 }
			     });
	    }
	}

	// FORGOT FORM RESET
	//==========================================================================

	// forgot form fields.
	var forgot_email_field = dojo.byId('forgot_email');
	var forgot_error_msg = dojo.byId('forgot_form_error_msg');
	var forgot_success_msg = dojo.byId('forgot_form_success_msg');

	if (forgot_email_field) {
	    forgot_error_msg.style.display = "none";
	    forgot_error_msg.innerHTML = "";
	    forgot_success_msg.innerHTML = "";

	    // reset values.
	    if (dojo.hasClass(forgot_email_field, 'input_new')) {
		forgot_email_field.value = Z2h.user._emailLabel;
		dojo.addClass(forgot_email_field, "input_empty");

		dojo.connect(forgot_email_field,
			     "onfocus",
			     function(e){
				 e.preventDefault();
				 var email = Z2h.string.trimAll(forgot_email_field.value);

				 if (email == Z2h.user._emailLabel) {
				     forgot_email_field.value = "";
				     dojo.removeClass(forgot_email_field, "input_empty");
				 }
			     });

		dojo.connect(forgot_email_field,
			     "onblur",
			     function(e){
				 e.preventDefault();
				 var email = Z2h.string.trimAll(forgot_email_field.value);

				 if (email.length == 0) {
				     forgot_email_field.value = Z2h.user._emailLabel;
				     dojo.addClass(forgot_email_field, "input_empty");
				 }

			     });
	    }
	}

	// QUICK SIGN-UP FORM RESET
	//==========================================================================

	// signup form fields.
	var signup_username_field = dojo.byId('signup_username');
	var signup_email_field = dojo.byId('signup_email');
	var signup_passwd_field = dojo.byId('signup_passwd');
	var signup_passwd_txt_field = dojo.byId('signup_passwd_txt');
	var signup_error_msg = dojo.byId('signup_errors');
	var signup_passwd_txt_field = dojo.byId('signup_passwd_txt');

	if (signup_username_field) {
	    // reset values.
	    signup_error_msg.style.display = "none";
	    signup_error_msg.innerHTML = "";

	    if (dojo.hasClass(signup_username_field, 'input_new')) {
		signup_username_field.value = Z2h.user._usernameLabel;

		dojo.connect(signup_username_field,
			     "onfocus",
			     function(e){
				 e.preventDefault();
				 var username = Z2h.string.trimAll(signup_username_field.value);

				 if (username == Z2h.user._usernameLabel) {
				     signup_username_field.value = "";
				     dojo.removeClass(signup_username_field, "input_empty");
				 }
			     });

		dojo.connect(signup_username_field,
			     "onblur",
			     function(e){
				 e.preventDefault();
				 var username = Z2h.string.trimAll(signup_username_field.value);

				 if (username.length == 0) {
				     signup_username_field.value = Z2h.user._usernameLabel;
				     dojo.addClass(signup_username_field, "input_empty");
				 }

			     });
	    }

	    if (dojo.hasClass(signup_email_field, 'input_new')) {
		signup_email_field.value = Z2h.user._emailLabel;

		dojo.connect(signup_email_field,
			     "onfocus",
			     function(e){
				 e.preventDefault();
				 var email = Z2h.string.trimAll(signup_email_field.value);

				 if (email == Z2h.user._emailLabel) {
				     signup_email_field.value = "";
				     dojo.removeClass(signup_email_field, "input_empty");
				 }
			     });

		dojo.connect(signup_email_field,
			     "onblur",
			     function(e){
				 e.preventDefault();
				 var email = Z2h.string.trimAll(signup_email_field.value);

				 if (email.length == 0) {
				     signup_email_field.value = Z2h.user._emailLabel;
				     dojo.addClass(signup_email_field, "input_empty");
				 }

			     });
	    }

	    if (signup_passwd_txt_field && dojo.hasClass(signup_passwd_txt_field, 'input_new')) {
		signup_passwd_txt_field.value = Z2h.user._passwordLabel;
		signup_passwd_txt_field.style.display = "";

		signup_passwd_field.value = "";
		signup_passwd_field.style.display = "none";

		dojo.connect(signup_passwd_txt_field,
			     "onfocus",
			     function(e){
				 e.preventDefault();
				 signup_passwd_txt_field.style.display = "none";
				 signup_passwd_field.style.display = "";
				 signup_passwd_field.focus();
			     });

		dojo.connect(signup_passwd_field,
			     "onblur",
			     function(e){
				 e.preventDefault();
				 var password = Z2h.string.trimAll(signup_passwd_field.value);

				 if (password.length == 0) {
				     signup_passwd_txt_field.style.display = "";
				     signup_passwd_field.style.display = "none";
				 }
			     });
	    }
	}
    },

    showLogin: function(evt) {
	evt.preventDefault();

	Z2h.user.resetForms();

	// hide forgot password form section, but show login form section.
	var forgotpasswd_form_section = dojo.byId('forgotpasswd_form_section');
	if (forgotpasswd_form_section) {
	    forgotpasswd_form_section.style.display = "none";
	}

	var signup_form_section = dojo.byId('signup_form_section');
	if (signup_form_section) {
	    signup_form_section.style.display = "none";
	}

	var remember_login = dojo.byId('remember_login');
	if (remember_login) {
	    remember_login.style.display = "none";
	}

	var register_link = dojo.byId('register_link');
	if (register_link) {
	    register_link.style.display = "block";
	}

	var login_form_section = dojo.byId('login_form_section');
	if (login_form_section) {
	    dojo.byId('login_form_section').style.display = "block";
	}
    },

    showForgot: function(evt) {
	evt.preventDefault();

	Z2h.user.resetForms();

	// hide login form section, but show forgot password form section.
	var login_form_section = dojo.byId('login_form_section');
	if (login_form_section) {
	    login_form_section.style.display = "none";
	}

	var signup_form_section = dojo.byId('signup_form_section');
	if (signup_form_section) {
	    signup_form_section.style.display = "none";
	}

	var remember_login = dojo.byId('remember_login');
	if (remember_login) {
	    remember_login.style.display = "none";
	}

	var register_link = dojo.byId('register_link');
	if (register_link) {
	    register_link.style.display = "block";
	}

	dojo.byId('forgotpasswd_form_section').style.display = "block";

	// hide after form submission section, but show forgot password form section.
	var forgot_form_success_container = dojo.byId("forgot_form_success_container");
	if (forgot_form_success_container) {
	    forgot_form_success_container.style.display = "none";
	}

	var forgot_form_field = dojo.byId("forgot_form_field");
	if (forgot_form_field) {
	    forgot_form_field.style.display = "block";
	}
    },

    // show hidden signup form.
    showSignupForm: function() {
	//evt.preventDefault();

	Z2h.user.resetForms();

	// hide login form section, but show forgot password form section.
	var login_form_section = dojo.byId('login_form_section');
	if (login_form_section) {
	    login_form_section.style.display = "none";
	}

	var forgotpasswd_form_section = dojo.byId('forgotpasswd_form_section');
	if (forgotpasswd_form_section) {
	    forgotpasswd_form_section.style.display = "none";
	}

	dojo.byId('signup_form_section').style.display = "block";

	var remember_login = dojo.byId('remember_login');
	if (remember_login) {
	    remember_login.style.display = "block";
	}

	var register_link = dojo.byId('register_link');
	if (register_link) {
	    register_link.style.display = "none";
	}
    },

    // send simple signup form.
    signupQuick: function() {
	// signup form fields.
	var form = dojo.byId('signup_form_quick');
	var username_field = dojo.byId('signup_username');
	var email_field = dojo.byId('signup_email');
	var passwd_field = dojo.byId('signup_passwd');
	var passwd_txt_field = dojo.byId('signup_passwd_txt');
	var error_msg = dojo.byId('signup_errors');

	var errors = 0;

	// validate username.
	var username = Z2h.string.trimAll(username_field.value);
	if (username.length == 0 || username == Z2h.user._usernameLabel) {
	    errors++;
	}

	// validate email.
	var email_filter  = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
	if (email_field.value.length == 0) {
	    errors++;
	} else if(!email_filter.test(email_field.value)) {
	    errors++;
	}

	// validate password.
	if (passwd_field.value.length == 0) {
	    errors++;
	}

	// validate form.
	if(errors == 0){
	    // only send an ajax request if nothing is running.
	    if (Z2h.user._running === false) {
		error_msg.style.display = "none";
		error_msg.innerHTML = "";

		var status_active = dojo.byId("overlay_signup_form");
		var btn_active = dojo.byId("signup_submit_quick");
		var overlay_wait = dojo.byId("signup_please_wait");

		if (status_active && btn_active && overlay_wait) {
		    status_active.style.display = "none";
		    overlay_wait.style.display = "";
		}

		dojo.xhrPost({
				 url: form.action+'/format/json',
				 form: "signup_form_quick",
				 handleAs: "json",
				 //					sync: true,
				 headers: {"X-Requested-With": "XMLHttpRequest"},
				 load: function(data,ioargs){
				     if(data.result == '1'){
					 if (Z2h.tracking_id) {
					     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 {
					 status_active.style.display = "";
					 overlay_wait.style.display = "none";

					 if (error_msg) {
					     //								error_msg.innerHTML = "";
					     var error_popup_mesg = "";
					     for(var k in data.errors){
						 error_popup_mesg += data.errors[k][0]+"<br />";
					     }
					     Z2h.tooltip.popupError(error_popup_mesg);
					     //								error_msg.style.display = "block";
					 }
				     }

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

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

			             /* handle the error... */
			             return response; //always return the response back
			         }
			     });
	    }

	    Z2h.user._running = false;
	} else {
	    Z2h.tooltip.popupError("All fields are required (email address must be valid).");

	    //			error_msg.innerHTML = "All fields are required (Email must be valid)";
	    //			error_msg.style.display = "block";
	}
    },

    login: function(evt) {
	evt.preventDefault();


	// login form fields.
	var form = dojo.byId('login_form');
	var username_field = dojo.byId('login_username');
	var passwd_field = dojo.byId('login_passwd');
	var error_msg = dojo.byId('login_form_error_msg');
	var username_error = false;

	var errors = 0;

	// validate username.
	var username = Z2h.string.trimAll(username_field.value);

	if (username.length == 0 || username == Z2h.user._usernameLabel) {
	    errors++;
	    username_error = true;
	}

	// validate password.
	if (passwd_field.value.length == 0 ) { 
	    errors++;
	}

	// validate form.
	if(errors == 0){
	    error_msg.style.display = "none";
	    error_msg.innerHTML = "";

	    // hide the login form.
	    dojo.byId("login_form_submit").style.display = "none";
	    dojo.byId("login_please_wait").style.display = "";

	    dojo.xhrPost({
			     url: form.action+'/format/json',
			     form: "login_form",
			     handleAs: "json",
			     //				sync: true,
			     headers: {"X-Requested-With": "XMLHttpRequest"},
			     load: function(data,ioargs){
				 if(data.result == '1'){
				     if (Z2h.tracking_id) {
					 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);
				     }

				     if (data.pointsMesg != null) {
					 Z2h.tooltip.popups(data.pointsMesg,'points');
				     }
				 } else {
				     Z2h.tooltip.popupError(data.login_error);
				     //						error_msg.innerHTML = data.login_error;
				     //						error_msg.style.display = "block";

				     dojo.byId("login_form_submit").style.display = "";
				     dojo.byId("login_please_wait").style.display = "none";
				 }

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

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

				 dojo.byId("login_form_submit").style.display = "";
				 dojo.byId("overlay_please_wait").style.display = "none";

				 /* handle the error... */
				 return response; //always return the response back
		             }
			 });
	} else {
	    //error_msg.style.display = "block";
		if (errors == 2) {
			Z2h.tooltip.popupError("Username and Password are required.");
		} else {
			if (username_error) {
				Z2h.tooltip.popupError("Username is required.");
			} else {
				Z2h.tooltip.popupError("Password is required.");
			}
		}
	}
    },

    forgot: function(evt) {
	evt.preventDefault();

	// forgot form fields.
	var form = dojo.byId('forgot_form');
	var email_field = dojo.byId('forgot_email');
	var error_msg = dojo.byId('forgot_form_error_msg');

	var errors = 0;
	var email_filter  = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;

	// validate email.
	if (email_field.value.length == 0) {
	    Z2h.tooltip.popupError("Please enter the email you signed up with.");
	    //			error_msg.innerHTML = "Please enter the email you signed up with.";
	    errors++;
	} else if(!email_filter.test(email_field.value)) {
	    Z2h.tooltip.popupError("Please enter a valid email address.");
	    //			error_msg.innerHTML = "Please enter a valid email address.";
	    errors++;
	}

	// validate form.
	if(errors == 0){
	    error_msg.style.display = "none";
	    error_msg.innerHTML = "";

	    dojo.xhrPost({
			     url: form.action+'/format/json',
			     form: "forgot_form",
			     handleAs: "json",
			     //				sync: true,
			     headers: {"X-Requested-With": "XMLHttpRequest"},
			     load: function(data,ioargs){
				 if(data.result == '1'){
				     dojo.byId('forgot_email').value = "";
				     dojo.byId("forgot_form_success_msg").innerHTML = "Ok. We sent you an Email with a link to reset your password.";

				     var forgot_form_success_container = dojo.byId("forgot_form_success_container");
				     if (forgot_form_success_container) {
					 forgot_form_success_container.style.display = "block";
				     }

				     var forgot_form_field = dojo.byId("forgot_form_field");
				     if (forgot_form_field) {
					 forgot_form_field.style.display = "none";
				     }
				 } else {
				     Z2h.tooltip.popupError(data.forgot_error);
				     //						error_msg.innerHTML = data.forgot_error;
				     //						error_msg.style.display = "block";
				 }

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

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

				 /* handle the error... */
				 return response; //always return the response back
		             }
			 });
	} else {
	    //			error_msg.style.display = "block";
	}
    },

    // show overlay form to sign up.
    showSignup: function(evt) {
	evt.preventDefault();

	var href = evt.currentTarget.href;

	// only send an ajax request if nothing is running.
	if (Z2h.user._running === false) {
	    Z2h.user._running = true;

	    dojo.xhrGet({
			    url: href+"/format/text",  //the relative URL
			    handleAs: "text",
			    //			 	sync: true,
			    // run this function if the request is successful
		            load : function(response, ioArgs) {
			 	// close already opend signup form.
			 	var opened_signup_form = dijit.byId('signup_form_overlay');

			 	if (opened_signup_form) {
			 	    opened_signup_form.hide();
			 	    opened_signup_form.destroy();
			 	}

			 	// initialize dialog.
				var signup_form = new dijit.Dialog({id: "signup_form_overlay"});
				dojo.style(signup_form.titleBar, "display", "none");

				signup_form.attr('content', response);
				signup_form.show();

				// hide parent email field as default.
				var parentEmail = dojo.byId('parent_email');
				if (parentEmail) {
				    parentEmail.style.display = "none";
				}

				// close over flag form.
				dojo.query(".overlay_signup_close").forEach(function(node, i){
										//node.style.display = "block";
										var closeHandle = dojo.connect(node,
													       "onclick",
													       dojo.hitch(signup_form,
													     		  function(e){
													    		      e.preventDefault();
													    		      signup_form.attr('content', '');
													    		      signup_form.hide();
													    		      signup_form.destroy();
													     		      dojo.disconnect(closeHandle);
													     		  }));
									    });

				// overwrite the default esc key event.
				var escHandle = dojo.connect(signup_form.domNode, "onkeypress", function(e){
								 var key = e.keyCode || e.charCode;
								 var k = dojo.keys;

								 if (key == k.ESCAPE) {
								     e.preventDefault();
								     signup_form.attr('content', '');
						    		     signup_form.hide();
						    		     signup_form.destroy();
						     		     dojo.disconnect(escHandle);
								 }
							     });

				// create a submit button to send the flag form.
				var submitButton = dojo.byId('signup_submit');
				if (submitButton) {
				    dojo.connect(submitButton,
						 "onclick",
						 function(e){
						     e.preventDefault();
						     Z2h.user.signup();
				    		 });
				}

				var signup_post_form = dojo.byId('signup_form');
				if (signup_post_form) {
				    dojo.connect(signup_post_form,
						 "onsubmit",
						 function(e){
						     e.preventDefault();
						     Z2h.user.signup();
				    		 });
				}

				// hook onclick event to select an avatar from predefined set.
				dojo.query("a.avatar_link").forEach(function(link) {
									dojo.connect(link, "onclick", Z2h.link.selectAvatar);
								    });

				// hook events with birthday select list.
				var signup_birth_y = dojo.byId('signup_birth_y');
				var signup_birth_m = dojo.byId('signup_birth_m');
				var signup_birth_d = dojo.byId('signup_birth_d');

				if (signup_birth_y && signup_birth_m && signup_birth_d) {
				    dojo.connect(signup_birth_m,
						 "onchange",
						 function(e){
				    		     Z2h.user.calenderDays('signup_birth_d', 'signup_birth_m', 'signup_birth_y');
				    		 });

				    dojo.connect(signup_birth_y,
						 "onchange",
						 function(e){
						     Z2h.user.calenderDays('signup_birth_d', 'signup_birth_m', 'signup_birth_y');
				    		 });
				}

				//

				return response; //always return the response back
		            },
		            // run this function if the request is not successful
		            error : function(response, ioArgs) {
				console.log("failed xhrGet", response, ioArgs);

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

				/* handle the error... */
				return response; //always return the response back
		            }
			});

	    Z2h.user._running = false;
	}
    },

    // send signup form.
    signup: function() {
	// only send an ajax request if nothing is running.
	if (Z2h.user._running === false) {
	    Z2h.user._running = true;

	    var form = dojo.byId('signup_form');

	    if (form) {
		var signup_errors = dojo.byId('signup_errors');
		var parentEmail = dojo.byId('parent_email');

		// show/hide parent email form field.
		var birth_m_field = dojo.byId('signup_birth_m');
		var birth_d_field = dojo.byId('signup_birth_d');
		var birth_y_field = dojo.byId('signup_birth_y');

		if (birth_m_field && birth_d_field && birth_y_field) {
		    var birth_m = birth_m_field.value;
		    var birth_d = birth_d_field.value;
		    var birth_y = birth_y_field.value;

		    if(parentEmail && birth_m != '00' && birth_d != '00' && birth_y != '0000'){
			// get an age.
			var current_age = Z2h.user.getAge(parseInt(birth_y), parseInt(birth_m), parseInt(birth_d));

			if (current_age <= 13) {
			    parentEmail.style.display = "";
			} else {
			    parentEmail.style.display = "none";
			}
		    }
		}

		var status_active = dojo.byId("overlay_signup_form");
		var btn_active = dojo.byId("overlay_signup_position");
		var overlay_wait = dojo.byId("signup_please_wait");

		if (status_active && btn_active && overlay_wait) {
		    status_active.style.display = "none";
		    btn_active.style.display = "none";
		    overlay_wait.style.display = "";
		}

		dojo.xhrPost({
				 url: form.action+'/format/json',
				 form: "signup_form",
				 handleAs: "json",
				 //					sync: true,
				 headers: {"X-Requested-With": "XMLHttpRequest"},
				 load: function(data,ioargs){
				     if(data.result == '1'){
					 if (Z2h.tracking_id) {
					     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 {
					 status_active.style.display = "";
					 btn_active.style.display = "";
					 overlay_wait.style.display = "none";

					 if (signup_errors) {
					     signup_errors.innerHTML = "";

					     for(var k in data.errors){
						 signup_errors.innerHTML += data.errors[k][0]+"<br />";
					     }

					     signup_errors.style.display = "block";
					 }
				     }

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

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

			             /* handle the error... */
			             return response; //always return the response back
			         }
			     });
	    }

	    Z2h.user._running = false;
	}
    },

    // update number of days based on selected year and month.
    calenderDays: function(day_select_id, month_select_id, year_select_id) {
	var month = parseInt(dojo.byId(month_select_id).value);
	var year = parseInt(dojo.byId(year_select_id).value);
	var day = parseInt(dojo.byId(day_select_id).value);
	var day_options = dojo.byId(day_select_id);

	var thirtyone_days = ["01", "03", "05", "07", "08", "10", "12"];
	var thirty_days = ["04", "06", "09", "11"];
	var found;

	// check the selected month has 31 days.
	found = dojo.indexOf(thirtyone_days, month);
	if (found == -1) {
	    // check the selected month has 30 days.
	    found = dojo.indexOf(thirty_days, month);

	    if (found == -1) {
		// a year will be a leap year if it is divisible by 4 but not by 100.
		// if a year is divisible by 4 and by 100, it is not a leap year unless it is also divisible by 400.
		if (year > 0) {
		    if ((year%4 == 0 && year%100 != 0) || (year%4 == 0 && year%100 == 0 && year%400 == 0)) {
			// a leap year has 29 days in February.
			dojo.removeAttr(day_options.options[29], "disabled");
			dojo.attr(day_options.options[30], "disabled", "disabled");
			dojo.attr(day_options.options[31], "disabled", "disabled");

			if (day > 29) {
			    dojo.attr(day_options.options[29], "selected", "selected");
			    day_options.selectedIndex = 29;
			}
		    } else {
			// set it to 28 days for February.
			dojo.attr(day_options.options[29], "disabled", "disabled");
			dojo.attr(day_options.options[30], "disabled", "disabled");
			dojo.attr(day_options.options[31], "disabled", "disabled");

			if (day > 28) {
			    dojo.attr(day_options.options[28], "selected", "selected");
			    day_options.selectedIndex = 28;
			}
		    }
		} else {
		    // set it to 28 days for February.
		    dojo.attr(day_options.options[29], "disabled", "disabled");
		    dojo.attr(day_options.options[30], "disabled", "disabled");
		    dojo.attr(day_options.options[31], "disabled", "disabled");

		    if (day > 28) {
			dojo.attr(day_options.options[28], "selected", "selected");
			day_options.selectedIndex = 28;
		    }
		}
	    } else {
		// hide day 31th from the day select option.
		dojo.removeAttr(day_options.options[29], "disabled");
		dojo.removeAttr(day_options.options[30], "disabled");
		dojo.attr(day_options.options[31], "disabled", "disabled");

		if (day > 30) {
		    dojo.attr(day_options.options[30], "selected", "selected");
		    day_options.selectedIndex = 30;
		}
	    }
	} else {
	    // remove all disabled from options.
	    dojo.removeAttr(day_options.options[29], "disabled");
	    dojo.removeAttr(day_options.options[30], "disabled");
	    dojo.removeAttr(day_options.options[31], "disabled");
	}
    },

    // calculate age.
    getAge: function(birth_y, birth_m, birth_d) {
	var d = new Date();
	var current_year = d.getFullYear();
	var current_month = d.getMonth();
	var current_day = d.getDay();

	var year_diff  = current_year - birth_y;
	var month_diff = current_month - birth_m;
	var day_diff   = current_day - birth_d;

	if (month_diff < 0) {
	    year_diff--;
	} else if ((month_diff==0) && (day_diff < 0)) {
	    year_diff--;
	}

	return year_diff;
    }
}

Z2h.user.hovercard = {
    _shown: false,

    _timer: 50,

    _current: null,

    _should_hide: true,

    init: function(){
	var userBehavior = {
	    ".hover_avatar_card" : {
		onmouseover: function(evt){
		    Z2h.user.hovercard.showHoverCard(evt.target);
		}
	    },

	    ".user_tile" : {
		onmouseleave: function(evt){
		    Z2h.user.hovercard.setTimer();
		    Z2h.user.hovercard._should_hide = true;
		}
	    },

	    //				".user_tile * ": {
	    //					onmouseover: function(evt){
	    //						Z2h.user.hovercard.cancelTimer();
	    //						Z2h.user.hovercard._should_hide = false;
	    //					}
	    //				},

	    ".follow_me_hover": {
		onclick: function(evt){
		    Z2h.connection.reasonDialog(evt);
		}
	    }
	};

	dojo.behavior.add(userBehavior);
    },

    hideHoverCard: function(domE){
	if ( this._current && this._should_hide ) {
	    this._shown = false;
	    dojo.style(this._current,{
			   'left': "-9999px",
			   'top' : "0px",
			   'display': 'none'
		       });
	    this._current = null;
	}
    },

    setTimer: function(){
	if ( this._current ){
	    this._current.timer = setTimeout( function(){Z2h.user.hovercard.hideHoverCard()}, this._timer);
	}
    },

    cancelTimer: function(){
	if ( this._current ){
	    clearTimeout(this._current.timer);
	    //			this._current.timer = setTimeout( function(){Z2h.user.hovercard.hideHoverCard()}, this._timer);
	}
    },

    showHoverCard: function(domE){
	var userId = domE.id.replace("user_avatar_","");
	var avatarPos = dojo.position(domE,true);
	var userHoverCard = dojo.byId("user_tile_"+userId);
	if ( !this._shown ){
	    if ( userHoverCard ){
		this._shown = true;
		dojo.style(userHoverCard,{
			       'left': (avatarPos.x - 10)+"px",
			       'top' : (avatarPos.y - 10)+"px",
			       'display':'block',
			       'position':'absolute'
			   });
	    } else {
		userHoverCard = Z2h.user.hovercard.getHoverCardForUser(userId,domE);
	    }
	    this._current = userHoverCard;
	    dojo.behavior.apply();
	}
    },

    getHoverCardForUser: function(uid,domE){
	var avatarPos = dojo.position(domE,true);
	var newDiv = dojo.create('div');
	dojo.place(newDiv,'prestige_user_hovercards','last');
	var loadingDiv = dojo.byId('prestige_hovercard_loading');
	newDiv.innerHTML = loadingDiv.innerHTML;
	dojo.attr(newDiv,'class','user_tile');
	dojo.attr(newDiv,'id','user_tile_'+uid)
	dojo.attr(newDiv,'style','');
	dojo.style(newDiv,{
		       'left': (avatarPos.x - 10)+"px",
		       'top' : (avatarPos.y - 10)+"px",
		       'display':'block',
		       'position':'absolute'
		   });

	dojo.xhrGet({
			url: "/default/interaction/get-user-tile/format/json/uid/"+uid,
			handleAs: "text",
			headers: {"X-Requested-With": "XMLHttpRequest"},
			load: function(data,ioargs){
			    newDiv.innerHTML = data;
			    return data;
			},
			error: function(response,ioargs){

			    return response;
			}
		    });

	return newDiv;
    }
};

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

Z2h.user.profile = {
    _running: false,

    init: function() {
	var user_capital_tooltip_label = dojo.byId('user_capital_tooltip_label');
	if (user_capital_tooltip_label) {
	    var tooltip_label = user_capital_tooltip_label.innerHTML;

	    var profileBehavior = {
		".user_capital_title * ": {
		    onmouseover: function(evt){
			new dijit.Tooltip({
					      connectId: ["user_capital_tooltip_launcher"],
					      label: tooltip_label,
					      showDelay: 0
					  });
	 	    }
	 	}
	    };
	}

	dojo.behavior.add(profileBehavior);

	// initialize status.
	Z2h.user.profile.initStatus();

	// initialize add profile form.
	Z2h.user.profile.initAddProfile();
    },

    // initialize status
    initStatus: function() {
	// hook onclick event to show edit title form.
	var edit_title_link = dojo.byId('edit_title_link');
	if (edit_title_link) {
	    dojo.connect(edit_title_link, 'onclick', function(evt) {
			     evt.preventDefault();
			     Z2h.user.profile.loadTitle(evt.currentTarget.href);
			 });
	}

	// hook onclick event to cancel title form.
	var edit_title_cancel = dojo.byId('edit_title_cancel');
	if (edit_title_cancel) {
	    dojo.connect(edit_title_cancel, 'onclick', function(evt) {
			     evt.preventDefault();
			     Z2h.user.profile.loadTitle(evt.currentTarget.href);
			 });
	}

	// hook onclick event to submit title form.
	var edit_title_submit = dojo.byId('edit_title_submit');
	if (edit_title_submit) {
	    dojo.connect(edit_title_submit, 'onclick', Z2h.user.profile.updateTitle);
	}

	// hook onclick event to show edit status form.
	var edit_status_link = dojo.byId('edit_status_link');
	if (edit_status_link) {
	    dojo.connect(edit_status_link, 'onclick', function(evt) {
			     evt.preventDefault();
			     Z2h.user.profile.loadStatus(evt.currentTarget.href);
			 });
	}

	// hook text character length aid. (max 255 characters are allowed)
	var status_info = dojo.byId('edit_status_info');
	if (status_info) {
	    dojo.connect(status_info,
		    	 "onkeyup",
		    	 function(){
			     var numChars = dojo.number.parse(status_info.value.length);
			     var currentValue = parseInt(255) - numChars;

			     if (currentValue < 0) {
				 status_info.value = status_info.value.slice(0, 255);
			     }
			 });
	}

	// hook onclick event to cancel status form.
	var edit_status_cancel = dojo.byId('edit_status_cancel');
	if (edit_status_cancel) {
	    dojo.connect(edit_status_cancel, 'onclick', function(evt) {
			     evt.preventDefault();
			     Z2h.user.profile.loadStatus(evt.currentTarget.href);
			 });
	}

	// hook onclick event to submit status form.
	var edit_status_submit = dojo.byId('edit_status_submit');
	if (edit_status_submit) {
	    dojo.connect(edit_status_submit, 'onclick', Z2h.user.profile.updateStatus);
	}
    },

    // show edit status form or refresh status info.
    updateStatus: function(evt) {
	evt.preventDefault();

	// only send an ajax request if nothing is running.
	if (Z2h.user.profile._running === false) {
	    Z2h.user.profile._running = true;

	    var form = dojo.byId('user_status_update');

	    if (form) {
		dojo.xhrPost({
				 url: form.action+'/format/json',
				 form: "user_status_update",
				 handleAs: "json",
				 //					sync: true,
				 headers: {"X-Requested-With": "XMLHttpRequest"},
				 load: function(data,ioargs){
				     if(data.result == '1'){
					 Z2h.user.profile._running = false;

					 // refresh status info.
					 var edit_status_cancel = dojo.byId('edit_status_cancel');
					 if (edit_status_cancel) {
					     Z2h.user.profile.loadStatus(edit_status_cancel.href);
					 }
				     } else {
					 var status_info_error = dojo.byId('status_info_error');

					 if (status_info_error) {
					     status_info_error.innerHTML = "";

					     for(var k in data.errors){
						 if(k == 'logged_out'){
						     window.location.assign(data.errors[k]);
						 } else {
						     status_info_error.innerHTML += data.errors[k]+"<br />";
						 }
					     }

					     status_info_error.style.display = "block";
					 }
				     }

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

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

			             /* handle the error... */
			             return response; //always return the response back
			         }
			     });
	    }

	    Z2h.user.profile._running = false;
	}
    },

    // load status info or status update form.
    loadStatus: function(href) {
	// only send an ajax request if nothing is running.
	if (Z2h.user.profile._running === false) {
	    Z2h.user.profile._running = true;

	    var status_active = dojo.byId("status_active");
	    var overlay_wait = dojo.byId("overlay_please_wait");

	    if (status_active && overlay_wait) {
		status_active.style.display = "none";
		overlay_wait.style.display = "";
	    }

	    dojo.xhrGet({
			    url: href+"/format/text",  //the relative URL
			    handleAs: "text",
			    //			 	sync: true,
			    // run this function if the request is successful
		            load : function(response, ioArgs) {
				if (response == 'logged_out') {
			 	    window.location.assign('/login-required');
			 	} else {
			 	    // set some element's content...
				    var update_dom = dojo.byId("user_status_info");

				    if (update_dom) {
					update_dom.innerHTML= response;

					// hook events again.
					Z2h.user.profile.initStatus();
				    }
			 	}

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

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

				/* handle the error... */
				return response; //always return the response back
		            }
			});

	    Z2h.user.profile._running = false;
	}
    },

    // show edit title form or refresh title info.
    updateTitle: function(evt) {
	evt.preventDefault();

	// only send an ajax request if nothing is running.
	if (Z2h.user.profile._running === false) {
	    Z2h.user.profile._running = true;

	    var form = dojo.byId('user_title_update');

	    if (form) {
		dojo.xhrPost({
				 url: form.action+'/format/json',
				 form: "user_title_update",
				 handleAs: "json",
				 //					sync: true,
				 headers: {"X-Requested-With": "XMLHttpRequest"},
				 load: function(data,ioargs){
				     if(data.result == '1'){
					 Z2h.user.profile._running = false;

					 // refresh status info.
					 var edit_title_cancel = dojo.byId('edit_title_cancel');
					 if (edit_title_cancel) {
					     Z2h.user.profile.loadTitle(edit_title_cancel.href);
					 }

					 dojo.behavior.apply();
				     } else {
					 var title_info_error = dojo.byId('title_info_error');

					 if (title_info_error) {
					     title_info_error.innerHTML = "";

					     for(var k in data.errors){
						 if(k == 'logged_out'){
						     window.location.assign(data.errors[k]);
						 } else {
						     title_info_error.innerHTML += data.errors[k]+"<br />";
						 }
					     }

					     title_info_error.style.display = "block";
					 }
				     }

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

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

			             /* handle the error... */
			             return response; //always return the response back
			         }
			     });
	    }

	    Z2h.user.profile._running = false;
	}
    },

    // load title info or title update form.
    loadTitle: function(href) {
	// only send an ajax request if nothing is running.
	if (Z2h.user.profile._running === false) {
	    Z2h.user.profile._running = true;

	    var title_active = dojo.byId("title_active");
	    var overlay_wait = dojo.byId("overlay_title_wait");

	    if (title_active && overlay_wait) {
		title_active.style.display = "none";
		overlay_wait.style.display = "";
	    }

	    dojo.xhrGet({
			    url: href+"/format/text",  //the relative URL
			    handleAs: "text",
			    //			 	sync: true,
			    // run this function if the request is successful
		            load : function(response, ioArgs) {
				if (response == 'logged_out') {
			 	    window.location.assign('/login-required');
			 	} else {
			 	    // set some element's content...
				    var update_dom = dojo.byId("user_title_info");

				    if (update_dom) {
					update_dom.innerHTML= response;

					// hook events again.
					dojo.behavior.apply();
					Z2h.user.profile.initStatus();
				    }
			 	}

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

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

				/* handle the error... */
				return response; //always return the response back
		            }
			});

	    Z2h.user.profile._running = false;
	}
    },

    // load each profile info or profile update form
    loadProfile: function(href, id) {
	// only send an ajax request if nothing is running.
	if (Z2h.user.profile._running === false) {
	    Z2h.user.profile._running = true;

	    var status_active = dojo.byId("info_active_"+id);
	    var overlay_wait = dojo.byId("info_please_wait_"+id);

	    if (status_active && overlay_wait) {
		status_active.style.display = "none";
		overlay_wait.style.display = "";
	    }

	    dojo.xhrGet({
			    url: href+"/format/text",  //the relative URL
			    handleAs: "text",
			    //			 	sync: true,
			    // run this function if the request is successful
		            load : function(response, ioArgs) {
				if (response == 'logged_out') {
			 	    window.location.assign('/login-required');
			 	} else {
			 	    // set some element's content...
				    var update_dom = dojo.byId("info_"+id);

				    if (update_dom) {
					update_dom.innerHTML= response;

					// hook events.
					Z2h.user.profile.initEditProfile(id);
				    }
			 	}

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

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

				/* handle the error... */
				return response; //always return the response back
		            }
			});

	    Z2h.user.profile._running = false;
	}
    },

    // update each profile.
    updateProfile: function(id) {
	// only send an ajax request if nothing is running.
	if (Z2h.user.profile._running === false) {
	    Z2h.user.profile._running = true;

	    var form = dojo.byId('user_profile_update_'+id);
	    var status_active = dojo.byId("info_active_"+id);
	    var overlay_wait = dojo.byId("info_please_wait_"+id);

	    if (form) {
		if (status_active && overlay_wait) {
		    status_active.style.display = "none";
		    overlay_wait.style.display = "";
		}

		if (Z2h.user.profile.validateProfileForm('new_category_name_'+id, 'description_'+id)) {
		    dojo.xhrPost({
				     url: form.action+'/format/json',
				     form: 'user_profile_update_'+id,
				     handleAs: "json",
				     //						sync: true,
				     headers: {"X-Requested-With": "XMLHttpRequest"},
				     load: function(data,ioargs){
					 if(data.result == '1'){
					     Z2h.user.profile._running = false;

					     // refresh profile details.
					     var profile_link = dojo.byId('edit_profile_cancel_'+id);
					     if (profile_link) {
						 Z2h.user.profile.loadProfile(profile_link.href, id);
					     }
					 } else {
					     if (status_active && overlay_wait) {
						 status_active.style.display = "";
						 overlay_wait.style.display = "none";
					     }

					     var profile_info_error = dojo.byId('profile_personal_error_'+id);

					     if (profile_info_error) {
						 profile_info_error.innerHTML = "";

						 for(var k in data.errors){
						     if(k == 'logged_out'){
							 window.location.assign(data.errors[k]);
						     } else {
							 profile_info_error.innerHTML += data.errors[k]+"<br />";
						     }
						 }

						 profile_info_error.style.display = "block";
					     }
					 }

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

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

				         /* handle the error... */
				         return response; //always return the response back
				     }
				 });
		} else {
		    if (status_active && overlay_wait) {
			status_active.style.display = "";
			overlay_wait.style.display = "none";
		    }

		    var profile_info_error = dojo.byId('profile_personal_error_'+id);

		    if (profile_info_error) {
			profile_info_error.innerHTML = "Topic is required.";
			profile_info_error.style.display = "block";
		    }
		}
	    }

	    Z2h.user.profile._running = false;
	}
    },

    // initialize edit profile form.
    initEditProfile: function(id) {
	if (dijit.byId("new_category_name_"+id)) {
            dijit.byId("new_category_name_"+id).destroy();
        }

        dojo.parser.parse(dojo.byId("info_"+id));

	// show form by ajax.
	var edit_link = dojo.byId('edit_profile_'+id);

	// only connect the js action if the edit link is available.
	if (edit_link) {
	    dojo.connect(edit_link,
			 "onclick",
			 function(e){
			     e.preventDefault();
			     Z2h.user.profile.loadProfile(edit_link.href, id);
			 });
	}

	// submit form by ajax.
	var update_submit = dojo.byId('edit_profile_submit_'+id);

	// only connect the js action if the submit button is available.
	if (update_submit) {
	    dojo.connect(update_submit,
			 "onclick",
			 function(e){
			     e.preventDefault();
			     Z2h.user.profile.updateProfile(id);
			 });
	}

	// cancel form by ajax.
	var update_cancel = dojo.byId('edit_profile_cancel_'+id);

	// only connect the js action if the cancel button is available.
	if (update_cancel) {
	    dojo.connect(update_cancel,
			 "onclick",
			 function(e){
			     e.preventDefault();
			     Z2h.user.profile.loadProfile(update_cancel.href, id);
			 });
	}

	// hook onclick event to show confirm dialog to delete item.
	var delete_link = dojo.byId('delete_profile_'+id);

	if (delete_link) {
	    dojo.connect(delete_link, 'onclick', Z2h.link.doPostDelete);
	}
    },

    // initialize add profile form.
    initAddProfile: function() {
	var default_topic  = "Enter a Topic you'd like to talk about!";
	var default_profile ="Tell us about your interests or hobbies. Talk about your favorite movies, music or books. Tell us little bit about you!";

	var profile_topic = dojo.byId('profile_category');
	var profile_body = dojo.byId('description');

	if (profile_topic) {
	    profile_topic.value = default_topic;
	    dojo.addClass(profile_topic, "profile_details_empty");

	    dojo.connect(profile_topic,
		    	 "onkeyup",
		    	 function(){
			     var numChars = dojo.number.parse(profile_topic.value.length);
			     var currentValue = parseInt(255) - numChars;

			     if (currentValue < 0) {
				 profile_topic.value = profile_topic.value.slice(0, 255);
			     }
			 });

	    dojo.connect(profile_topic,
			 "onfocus",
			 function(e){
			     e.preventDefault();
			     var updated_topic = profile_topic.value;

			     if (updated_topic == default_topic) {
				 profile_topic.value = "";
				 dojo.removeClass(profile_topic, "profile_details_empty");
			     }

			 });

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

			     if (updated_topic == "") {
				 profile_topic.value = default_topic;
				 dojo.addClass(profile_topic, "profile_details_empty");
			     }

			 });
	}

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

	    dojo.connect(profile_body,
		    	 "onkeyup",
		    	 function(){
			     var numChars = dojo.number.parse(profile_body.value.length);
			     var currentValue = parseInt(1000) - numChars;

			     if (currentValue < 0) {
				 profile_body.value = profile_body.value.slice(0, 1000);
			     }
			 });

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

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

			 });

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

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

			 });
	}

	// hook onclick event to submit profile form.
	var add_profile_submit = dojo.byId('add_profile_submit');
	if (add_profile_submit) {
	    dojo.connect(add_profile_submit, 'onclick', Z2h.user.profile.addProfile);
	}

	// hook onclick event to edit profile or cancel editing profile.
	dojo.query(".edit_personal_info").forEach(function(node, i){
						      dojo.connect(node, 'onclick', function(evt) {
								       evt.preventDefault();

								       var href = node.href;
								       var id = dojo.attr(node, "alt");

								       Z2h.user.profile.loadProfile(href, id);
								   });
						  });

	// hook onclick event to show confirm dialog to delete item.
	dojo.query('a.delete').forEach(function(link) {
					   dojo.connect(link, 'onclick', Z2h.link.doPostDelete);
				       });
    },

    // validate profile form.
    validateProfileForm: function(category_id, description_id) {
	var category = dojo.byId(category_id);
	var description = dojo.byId(description_id);

	if (dojo.hasClass(category, 'profile_details_empty')) {
	    // topic is required.
	    return false;
	} else {
	    if (category.value.length == 0) {
		return false;
	    } else {
		if (dojo.hasClass(description, 'profile_details_empty')) {
		    description.value = "";
		    dojo.removeClass(description, "profile_details_empty");
		}

		return true;
	    }
	}
    },

    // submit form to add a new profile info.
    addProfile: function(evt) {
	evt.preventDefault();

	// only send an ajax request if nothing is running.
	if (Z2h.user.profile._running === false) {
	    Z2h.user.profile._running = true;

	    var form = dojo.byId('user_profile_create');
	    var status_active = dojo.byId("add_profile_submit");
	    var overlay_wait = dojo.byId("add_personal_please_wait");

	    if (form) {
		if (status_active && overlay_wait) {
		    status_active.style.display = "none";
		    overlay_wait.style.display = "";
		}

		if (Z2h.user.profile.validateProfileForm('profile_category', 'description')) {
		    dojo.xhrPost({
				     url: form.action+'/format/json',
				     form: "user_profile_create",
				     handleAs: "json",
				     //						sync: true,
				     headers: {"X-Requested-With": "XMLHttpRequest"},
				     load: function(data,ioargs){
					 if(data.result == '1'){
					     Z2h.user.profile._running = false;

					     // refresh profile details.
					     var profile_details_link = dojo.byId('profile_details_link');
					     if (profile_details_link) {
						 Z2h.user.profile.loadProfileDetails(profile_details_link.href);
					     }
					 } else {
					     if (status_active && overlay_wait) {
						 status_active.style.display = "";
						 overlay_wait.style.display = "none";
					     }

					     var profile_info_error = dojo.byId('profile_personal_error');

					     if (profile_info_error) {
						 profile_info_error.innerHTML = "";

						 for(var k in data.errors){
						     if(k == 'logged_out'){
							 window.location.assign(data.errors[k]);
						     } else {
							 profile_info_error.innerHTML += data.errors[k]+"<br />";
						     }
						 }

						 profile_info_error.style.display = "block";
					     }
					 }

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

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

				         /* handle the error... */
				         return response; //always return the response back
				     }
				 });
		} else {
		    if (status_active && overlay_wait) {
			status_active.style.display = "";
			overlay_wait.style.display = "none";
		    }

		    var profile_info_error = dojo.byId('profile_personal_error');

		    if (profile_info_error) {
			profile_info_error.innerHTML = "Topic is required.";
			profile_info_error.style.display = "block";
		    }
		}
	    }

	    Z2h.user.profile._running = false;
	}
    },

    // load profile details.
    loadProfileDetails: function(href) {
	// only send an ajax request if nothing is running.
	if (Z2h.user.profile._running === false) {
	    Z2h.user.profile._running = true;

	    dojo.xhrGet({
			    url: href+"/format/text",  //the relative URL
			    handleAs: "text",
			    //			 	sync: true,
			    // run this function if the request is successful
		            load : function(response, ioArgs) {
				if (response == 'logged_out') {
			 	    window.location.assign('/login-required');
			 	} else {
			 	    // set some element's content...
				    var update_dom = dojo.byId("user_profile_info");

				    if (update_dom) {
					update_dom.innerHTML= response;

					if (dijit.byId("profile_category")) {
					    dijit.byId("profile_category").destroy();
					}

					dojo.parser.parse(update_dom);

					// hook events again.
					Z2h.user.profile.initAddProfile();
				    }
			 	}

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

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

				/* handle the error... */
				return response; //always return the response back
		            }
			});

	    Z2h.user.profile._running = false;
	}
    }
}

//---------------------- AUTO-COMPLETE COUNTRY & REGION JS --------------------------------
Z2h.autocomplete = {
    init: function() {
	var selected_country_field = dojo.byId("selected_country");
	var selected_country_id = 0;
	var country_select = dijit.byId("country_id");

	if (selected_country_field) {
	    selected_country_id = selected_country_field.value;
	}

	var selected_region_field = dojo.byId("selected_region");
	var selected_region_id = 0;
	var region_select = dijit.byId("region_id");

	if (selected_region_field) {
	    selected_region_id = selected_region_field.value;
	}

	// if country is selected, set the country name in the select list
	if (country_select) {
	    country_select.setValue(selected_country_id);
	}

	// if region is selected, set the region name in the select list
	if (region_select) {
	    region_select.query = {country_id : selected_country_id};
	    region_select.sort = [{attribute: "region_name", descending: true}];
	    region_select.setValue(selected_region_id);
	}
    },

    // clear error
    clearErr: function(select, field) {
	if (!select.isValid()) {
	    select.setValue(0);
	}
    },

    // clear field if default value is selected
    resetField: function(select) {
	var id = select.getValue();
	if (id == 0) {
	    select.textbox.value = "";
	}
    },

    // refresh regions
    refreshRegions: function(select) {
	if (select.isValid()) {
	    var selected_country_field = dojo.byId("selected_country");
	    var current_country_id = 0;
	    var selected_country_id = select.getValue();

	    if (selected_country_field) {
		current_country_id = selected_country_field.value;
	    }

	    if (current_country_id != selected_country_id) {
		// refresh the region list based on selected country id
		var selected_country_id = select.getValue();

		if (selected_country_field) {
		    selected_country_field.value = selected_country_id;
		}

		var region_select = dijit.byId("region_id");
		if (region_select) {
		    //					region_select.setValue(0);
		    //					region_select.textbox.value = "-- select province --";
		    region_select.query = {'country_id' : selected_country_id};
		    region_select.sort = [{attribute: "region_name", descending: true}];
		}
	    }
	}
    }
}

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

    init: function() {
	// hook onclick event to show reason dialog
	dojo.query(".follow_me").forEach(function(link) {
					     dojo.connect(link, "onclick", Z2h.connection.reasonDialog);
					 });

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

    unblock: function(evt) {
	evt.preventDefault();

	dojo.xhrGet({
			url: evt.currentTarget.href+"/format/json",
			handleAs: "json",
			sync: true,
			headers: {"X-Requested-With": "XMLHttpRequest"},
			load: function(data,ioargs){
			    if (data.result == "1") {
		 		var call_back = dojo.byId('do_after_callback');
				if (call_back) {
				    if (document.createEvent) {
					// Firefox etc.
					event = document.createEvent("HTMLEvents");
					event.initEvent("click", false, true);
					call_back.dispatchEvent(event);
				    } else {
					// IE
					call_back.fireEvent("onclick");
				    }
				} else {
				    // refresh the current page
				    window.location.reload(true);
				}
		 	    } else {
		 		// refresh the current page
				window.location.reload(true);
		 	    }

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

			    alert("ERROR: There was an error while submitting your form. Please try again!");
			    /* handle the error... */
			    return response; //always return the response back
			}
		    });
    },

    // show reason dialog.
    reasonDialog: function(evt) {
	evt.preventDefault();

	var href = evt.currentTarget.href;

	// only send an ajax request if nothing is running
	if (Z2h.connection._running === false) {
	    Z2h.connection._running = true;

	    dojo.xhrGet({
			    url: href + "/format/text",
			    handleAs: "text",
			    //			 	sync: true,
			    // run this function if the request is successful
		            load : function(response, ioArgs) {
				if (response == "logged_out") {
			 	    window.location.assign("/login-required");
			 	} else if (response == "connected") {
			 	    // refresh the current page
				    window.location.reload(true);
			 	} else {
			 	    // close already opend reason form
				    var opened_reason_form = dijit.byId("reason_dialog");

				    if (opened_reason_form) {
				 	opened_reason_form.hide();
				 	opened_reason_form.destroy();
				    }

				    // initialize dialog
				    var reason_form = new dijit.Dialog({id: "reason_dialog"});
				    dojo.style(reason_form.titleBar, "display", "none");

				    reason_form.attr("content", response);
				    reason_form.show();

				    // close over flag form.
				    dojo.query(".dijitDialogCloseIcon, #reason_dialog_cancel").forEach(function(node, i) {
													   //node.style.display = "block";
													   var closeHandle = dojo.connect(node, "onclick", dojo.hitch(reason_form, function(e) {
																					  e.preventDefault();

																					  reason_form.attr("content", "");
																					  reason_form.hide();
																					  reason_form.destroy();

																					  dojo.disconnect(closeHandle);
																				      }));
												       });

				    // overwrite the default esc key event
				    var escHandle = dojo.connect(reason_form.domNode, "onkeypress", function(e) {
								     var key = e.keyCode || e.charCode;
								     var k = dojo.keys;

								     if (key == k.ESCAPE) {
									 e.preventDefault();

									 reason_form.attr("content", "");
									 reason_form.hide();
									 reason_form.destroy();

									 dojo.disconnect(escHandle);
								     }
								 });

				    // create a submit button to send the connection form
				    var submitButton = dojo.byId("reason_dialog_submit");

				    if (submitButton) {
					dojo.connect(submitButton, "onclick", function(e) {
					    		 e.preventDefault();
							 Z2h.connection.sendReason();
					    	     });
				    }

				    var connect_following_form = dojo.byId("connect_following_form");

				    if (connect_following_form) {
					dojo.connect(connect_following_form, "onsubmit", function(e) {
					    		 e.preventDefault();
							 Z2h.connection.sendReason();
					    	     });
				    }

				    var otherText = dojo.byId("othertext");
				    var otherRadio = dojo.byId("otherradio");

				    if (otherText && otherText.value.length == 0) {
					otherText.disabled = true;
				    }

				    // attach radio button
				    if (otherRadio && otherText) {
					dojo.connect(otherRadio, "onclick", function(e) {
							 otherText.disabled = false;
							 otherText.focus();
						     });

					dojo.connect(otherText, "onclick", function(e) {
							 otherRadio.checked = true;
							 otherText.disabled = false;
						     });
				    }

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

				return response; //always return the response back
		            },
		            // run this function if the request is not successful
		            error : function(response, ioArgs) {
				console.log("failed xhrGet", response, ioArgs);

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

				/* handle the error... */
				return response; //always return the response back
		            }
			});

	    Z2h.connection._running = false;
	}
    },

    sendReason: function() {
	// only send an ajax request if nothing is running
	if (Z2h.connection._running === false) {
	    Z2h.connection._running = true;

	    var status_active = dojo.byId("connections_reason_popup");
	    var active_btn = dojo.byId("connections_buttons");
	    var overlay_wait = dojo.byId("following_please_wait");
	    var form = dojo.byId("connect_following_form");

	    if (form) {
		if (status_active && active_btn && overlay_wait) {
		    status_active.style.display = "none";
		    active_btn.style.display = "none";
		    overlay_wait.style.display = "";
		}

		dojo.xhrPost({
				 url: form.action + "/format/json",
				 form: "connect_following_form",
				 handleAs: "json",
				 //					sync: true,
				 headers: {"X-Requested-With": "XMLHttpRequest"},
				 load: function(data,ioargs){
				     if(data.result != "0"){
					 // close already opend reason form
					 var opened_reason_form = dijit.byId('reason_dialog');

					 if (opened_reason_form) {
					     opened_reason_form.hide();
					     opened_reason_form.destroy();
					 }

					 if (data.result == "1") {
					     var call_back = dojo.byId('do_after_callback');
					     if (call_back) {
						 if (document.createEvent) {
						     // Firefox etc.
						     event = document.createEvent("HTMLEvents");
						     event.initEvent("click", false, true);
						     call_back.dispatchEvent(event);
						 } else {
						     // IE
						     call_back.fireEvent("onclick");
						 }
					     } else {
						 // refresh the current page
						 window.location.reload(true);
					     }
					 } else {
					     // refresh the current page
					     window.location.reload(true);
					 }
				     } else {
					 if (status_active && active_btn && overlay_wait) {
					     status_active.style.display = "";
					     active_btn.style.display = "";
					     overlay_wait.style.display = "none";
					 }

					 var following_error = dojo.byId("following_error");

					 if (following_error) {
					     following_error.innerHTML = "";

					     for(var k in data.errors){
						 if(k == "logged_out"){
						     window.location.assign(data.errors[k]);
						 } else {
						     following_error.innerHTML += data.errors[k][0] + "<br />";
						 }
					     }

					     following_error.style.display = "block";
					 }
				     }

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

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

				     /* handle the error... */
				     return response; //always return the response back
				 }
			     });
	    }

	    Z2h.connection._running = false;
	}
    }
}

//---------------------- DOJO EDITOR JS --------------------------------
Z2h.editor = {
    init: function() {
	// hook onclick event to replace textarea with dojo editor value
	dojo.query("form.dojo_editor_form").forEach(function(node) {
							dojo.connect(node, "onsubmit", Z2h.editor.submitForm);
						    });

	// hook event to submit post.
	var save_publish_submit = dojo.byId('save_publish_submit');
	if (save_publish_submit) {
	    dojo.connect(save_publish_submit,'onclick',Z2h.editor.publishPostForm);
	}

	var community_post_form = dojo.byId('community_post_form');
	if (community_post_form) {
	    dojo.connect(community_post_form,'onsubmit',Z2h.editor.publishPostForm);
	}

	var save_draft_submit = dojo.byId('save_draft_submit');
	if (save_draft_submit) {
	    dojo.connect(save_draft_submit,'onclick',Z2h.editor.savePostForm);
	}
    },

    isValid: function() {
	var errors = 0;

	// validate title.
	var title = dojo.byId("discussion_edit_title");
	var titleError = dojo.byId("form_error_title");

	if (title.value.length == 0) {
	    errors++;
	    title.style.border =  "solid 1px red";
	    titleError.innerHTML = "You must enter a title";
	    dojo.style(titleError, "color", "red");
	    titleError.style.display = "block";
	} else {
	    title.style.border = "solid 1px black";
	    titleError.style.display = "none";
	}

	// validate body.
	var dojo_editor = dijit.byId("dojo_editor_textarea");
	if (dojo_editor) {
	    var body = dojo_editor.getValue();
	    body = body.replace("<br />", "");
	    body = body.replace(/^\s*/, "").replace(/\s*$/, "").replace(/<\/?[^>]+(>|$)/g, "");

	    var bodyError = dojo.byId("form_error_body");
	    var textarea = dojo.byId("dojo_editor_textarea");

	    if (body.length < 10) {
		errors++;
		textarea.style.border = "solid 1px red";
		bodyError.innerHTML = "Content can't be shorter than 10 characters";
		dojo.style(bodyError, "color", "red");
		bodyError.style.display = "block";
	    } else {
		textarea.style.border = "solid 1px #bfbfbf";
		bodyError.style.display = "none";
	    }
	}

	// validate form.
	if(errors == 0){
	    return true;
	} else {
	    return false;
	}
    },

    publishPostForm: function(evt) {
	evt.preventDefault();

	// validate title and discussion topic and text body.
	var community_post_form = dojo.byId('community_post_form');

	if (Z2h.editor.isValid() && community_post_form) {
	    var save_publish_option = dojo.byId('save_publish_option');

	    if (save_publish_option) {
		save_publish_option.value = 1;

		// get editor value as textarea body value
		var dojo_editor = dijit.byId("dojo_editor_textarea");

		if (dojo_editor) {
		    var textarea = document.createElement("textarea");
		    dojo.attr(textarea, "name", "body");
		    dojo.style(textarea, {"display": "none"});
		    textarea.value = dojo_editor.getValue();

		    dojo.place(textarea, community_post_form, "first");
		}

		community_post_form.submit();
	    }
	}
    },

    savePostForm: function(evt) {
	evt.preventDefault();

	// validate title and discussion topic and text body.
	var community_post_form = dojo.byId('community_post_form');

	if (Z2h.editor.isValid() && community_post_form) {
	    var save_publish_option = dojo.byId('save_publish_option');

	    if (save_publish_option) {
		save_publish_option.value = 0;

		// get editor value as textarea body value
		var dojo_editor = dijit.byId("dojo_editor_textarea");

		if (dojo_editor) {
		    var textarea = document.createElement("textarea");
		    dojo.attr(textarea, "name", "body");
		    dojo.style(textarea, {"display": "none"});
		    textarea.value = dojo_editor.getValue();

		    dojo.place(textarea, community_post_form, "first");
		}

		community_post_form.submit();
	    }
	}
    },

    submitForm: function(evt) {
	evt.preventDefault();

	// get editor value as textarea body value
 	var dojo_editor = dijit.byId("dojo_editor_textarea");

 	if (dojo_editor) {
 	    var textarea = document.createElement("textarea");
	    dojo.attr(textarea, "name", "body");
	    dojo.style(textarea, {"display": "none"});
	    textarea.value = dojo_editor.getValue();

	    dojo.place(textarea, evt.currentTarget, "first");
 	    evt.currentTarget.submit();
 	}
    }
}

//---------------------- SOCIAL CAPITAL JS --------------------------------
Z2h.social = {
    init: function() {
	var preview_btn = dojo.byId("social_preview_btn");

	if (preview_btn) {
	    dojo.connect(preview_btn, "onclick", Z2h.social.doPreview);
	}

	var save_btn = dojo.byId("social_save_btn");

	if (save_btn) {
	    dojo.connect(save_btn, "onclick", Z2h.social.confirmSave);
	}

	// for safari, hook onsubmit event to submit login form
	var save_form = dojo.byId("social_capital_form");

	if (save_form) {
	    dojo.connect(save_form, "onsubmit", Z2h.social.confirmSave);
	}
    },

    confirmSave: function(evt) {
	evt.preventDefault();
	Z2h.link.popup("save_confirm_overlay", "Save Confirmation", "Are you sure you want to save? Once you save the changes, you cannot undo.", Z2h.social.doSave);
    },

    doSave: function() {
	var form = dojo.byId("social_capital_form");
	form.submit();
    },

    // preview user social capital before saving
    doPreview: function(evt) {
	evt.preventDefault();
	var href = dojo.attr(evt.currentTarget, "title");

	// hide no script sections
	dojo.query('div.no_script_running').forEach(function(no_script_section) {
							no_script_section.style.display = "none";
						    });

	// show script sections
	dojo.query('div.script_running').forEach(function(script_section) {
						     script_section.style.display = "block";
						 });

	dojo.xhrPost({
			 url: href + "/format/text",
			 form: "social_capital_form",
			 handleAs: "text",
			 //			sync: true,
			 headers: {"X-Requested-With": "XMLHttpRequest"},
			 load : function(response, ioArgs) {
			     var update_dom = dojo.byId("preview_user_ranks");

			     if (update_dom) {
				 update_dom.innerHTML= response;
			     }

			     // hide script sections
			     dojo.query("div.script_running").forEach(function(script_section) {
									  script_section.style.display = "none";
								      });

			     // show no script sections
			     dojo.query("div.no_script_running").forEach(function(no_script_section) {
									     no_script_section.style.display = "block";
									 });

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

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

		             /* handle the error... */
		             return response; //always return the response back
			 }
		     });
    }
}

//---------------------- CREATION JS -------------------------
Z2h.creation = {
    _running: false,

    _sliding_base: 520,

    init: function() {
	// sliding effect for prev link
	dojo.query("div.creation_pagination > ul.pagination > li.previous > a").forEach(function(link) {
											    dojo.connect(link, "onclick", Z2h.creation.slidingPrevPaginator);
											});

	// sliding effect for pagination
	dojo.query("div.creation_pagination > ul.pagination > li.inactive > a").forEach(function(link) {
											    dojo.connect(link, "onclick", Z2h.creation.slidingPaginator);
											});

	// sliding effect for next link
	dojo.query("div.creation_pagination > ul.pagination > li.next > a").forEach(function(link) {
											dojo.connect(link, "onclick", Z2h.creation.slidingNextPaginator);
										    });

	// change background color
	var creation_container = dojo.byId("creation_container");

	if (creation_container) {
	    dojo.query(".text_light_option").forEach(function(option) {
							 dojo.connect(option, "onclick", function(e) {
									  e.preventDefault();

									  if (dojo.hasClass(creation_container, "text_dark")) {
									      dojo.removeClass(creation_container, "text_dark");
									  }
								      });
						     });

	    dojo.query(".text_dark_option").forEach(function(option) {
							dojo.connect(option, "onclick", function(e) {
									 e.preventDefault();
									 dojo.addClass(creation_container, "text_dark");
								     });
						    });
	}

	// change font size
	var creation_container_content = dojo.byId("creation_container_content");

	if (creation_container_content) {
	    dojo.query(".font_size_option").forEach(function(option) {
							dojo.connect(option, "onclick", function(e) {
									 e.preventDefault();

									 var currently_selected = dojo.query(".selected_font_size")[0];

									 if (currently_selected) {
									     var current_font_size = dojo.attr(currently_selected, "title");

									     if (dojo.hasClass(currently_selected, "selected_font_size")) {
										 dojo.removeClass(currently_selected, "selected_font_size");
									     }

									     if (dojo.hasClass(creation_container_content, "text_size_" + current_font_size)) {
										 dojo.removeClass(creation_container_content, "text_size_" + current_font_size);
									     }
									 }

									 var new_font_size = dojo.attr(option, "title");

									 dojo.addClass(option, "selected_font_size");
									 dojo.addClass(creation_container_content, "text_size_" + new_font_size);
								     });
						    });
	}
    },

    slidingPrevPaginator: function(evt) {
	evt.preventDefault();

	var prev_page = 0;
	var next_link = dojo.query("div.creation_pagination > ul.pagination > li.next")[0];
	var selected_link = dojo.query("div.creation_pagination > ul.pagination > li.active")[0];

	if (selected_link) {
	    var selected_page = parseInt(selected_link.innerHTML);

	    dojo.removeClass(selected_link, "active");
	    dojo.addClass(selected_link, "inactive");

	    var pagination_link = document.createElement("a");

	    dojo.attr(pagination_link, "id", "fanfiction_page_" + selected_page);
	    dojo.attr(pagination_link, "href", "#");
	    pagination_link.innerHTML = selected_page;
	    dojo.connect(pagination_link, "onclick", Z2h.creation.slidingPaginator);

	    selected_link.innerHTML = "";
	    dojo.place(pagination_link, selected_link, "last");

	    prev_page = selected_page - 1;
	}

	if (prev_page > 0) {
	    var prev_link = dojo.byId("fanfiction_page_" + prev_page);

	    if (prev_link) {
		var li_parent = prev_link.parentNode;

		if (li_parent) {
		    dojo.removeClass(li_parent, "inactive");
		    dojo.addClass(li_parent, "active");
		    li_parent.innerHTML = prev_page;
		}

		// slide to right
		amt = parseInt(Z2h.creation._sliding_base * (1 - prev_page));
		Z2h.creation.slidingRight(amt);
	    }

	    // show/hide prev link
	    if (prev_page == 1) {
		evt.currentTarget.parentNode.style.display = "none";
	    } else {
		evt.currentTarget.parentNode.style.display = "";
	    }
	}

	// show next link
	if (next_link) {
	    next_link.style.display = "";
	}
    },

    slidingPaginator: function(evt) {
	evt.preventDefault();

	var page_id = evt.currentTarget.id;
	var page = page_id.replace("fanfiction_page_", "");
	var prev_link = dojo.query("div.creation_pagination > ul.pagination > li.previous")[0];
	var next_link = dojo.query("div.creation_pagination > ul.pagination > li.next")[0];

	var selected_link = dojo.query("div.creation_pagination > ul.pagination > li.active")[0];

	if (selected_link) {
	    var selected_page = parseInt(selected_link.innerHTML);

	    dojo.removeClass(selected_link, "active");
	    dojo.addClass(selected_link, "inactive");

	    var pagination_link = document.createElement("a");

	    dojo.attr(pagination_link, "id", "fanfiction_page_" + selected_page);
	    dojo.attr(pagination_link, "href", "#");
	    pagination_link.innerHTML = selected_page;
	    dojo.connect(pagination_link, "onclick", Z2h.creation.slidingPaginator);

	    selected_link.innerHTML = "";
	    dojo.place(pagination_link, selected_link, "last");
	}

	var li_parent = evt.currentTarget.parentNode;

	if (li_parent) {
	    dojo.removeClass(li_parent, "inactive");
	    dojo.addClass(li_parent, "active");
	    li_parent.innerHTML = page;

	    // show/hide next link
	    if (next_link) {
		if (dojo.hasClass(li_parent, "last_inactive")) {
		    next_link.style.display = "none";
		}else{
		    next_link.style.display = "";
		}
	    }
	}

	// show/hide prev link
	if (prev_link) {
	    if (page == 1) {
		// show prev link
		prev_link.style.display = "none";
	    } else {
		prev_link.style.display = "";
	    }
	}

	var amt = 0;

	if (page > selected_page) {
	    // slide to left
	    amt = parseInt(Z2h.creation._sliding_base * (page-1));
	    Z2h.creation.slidingLeft(amt);
	} else {
	    // slide to right
	    amt = parseInt(Z2h.creation._sliding_base * (1 - page));
	    Z2h.creation.slidingRight(amt);
	}
    },

    slidingNextPaginator: function(evt) {
	evt.preventDefault();

	var next_page = 0;
	var prev_link = dojo.query("div.creation_pagination > ul.pagination > li.previous")[0];
	var selected_link = dojo.query("div.creation_pagination > ul.pagination > li.active")[0];

	if (selected_link && !dojo.hasClass(selected_link, "last_inactive")) {
	    var selected_page = parseInt(selected_link.innerHTML);

	    dojo.removeClass(selected_link, "active");
	    dojo.addClass(selected_link, "inactive");

	    var pagination_link = document.createElement("a");

	    dojo.attr(pagination_link, "id", "fanfiction_page_" + selected_page);
	    dojo.attr(pagination_link, "href", "#");
	    pagination_link.innerHTML = selected_page;
	    dojo.connect(pagination_link, "onclick", Z2h.creation.slidingPaginator);

	    selected_link.innerHTML = "";
	    dojo.place(pagination_link, selected_link, "last");

	    next_page = selected_page + 1;

	    var next_link = dojo.byId("fanfiction_page_" + next_page);

	    if (next_link) {
		var li_parent = next_link.parentNode;

		if (li_parent) {
		    dojo.removeClass(li_parent, "inactive");
		    dojo.addClass(li_parent, "active");
		    li_parent.innerHTML = next_page;

		    // show/hide next link
		    if (dojo.hasClass(li_parent, "last_inactive")) {
			evt.currentTarget.parentNode.style.display = "none";
		    } else {
			evt.currentTarget.parentNode.style.display = "";
		    }
		}

		// slide to left
		var amt = parseInt(Z2h.creation._sliding_base * (next_page - 1));
		Z2h.creation.slidingLeft(amt);
	    }
	}

	// show prev link
	if (prev_link) {
	    prev_link.style.display = "";
	}
    },

    slidingLeft: function(amt) {
	var creation_content_slider = dojo.byId("creation_content_slider");

	if (creation_content_slider) {
	    var slideArgs = {
	        node: "creation_content_slider",
	        top: (dojo.coords("creation_content_slider").t).toString(),
	        left: (0 - amt).toString(),
	        unit: "px"
	    };

	    dojo.fx.slideTo(slideArgs).play();
	}
    },

    slidingRight: function(amt) {
	var creation_content_slider = dojo.byId("creation_content_slider");

	if (creation_content_slider) {
	    var slideArgs = {
	        node: "creation_content_slider",
	        top: (dojo.coords("creation_content_slider").t).toString(),
	        left: (0 + amt).toString(),
	        unit: "px"
	    };

	    dojo.fx.slideTo(slideArgs).play();
	}
    }
};

//---------------------- CREATION TAGS JS --------------------------------
Z2h.tags = {
    creationURL: "/creation/index/get-creations/type/all/",
    creationTitle: "All Creations",

    init: function(){
	var removeAll = dojo.byId('clearAllTags');
	if ( removeAll ) {
	    dojo.connect(removeAll, 'onclick', Z2h.tags.removeAll );
	}

	dojo.query(".removeTag").forEach( function(link){
					      dojo.connect(link, 'onclick', Z2h.tags.removeTag );
					  });

	var switchSearchBy = dijit.byId('searchBy');
	if ( switchSearchBy ) {
	    dojo.connect(switchSearchBy, 'onchange', Z2h.tags.switchSearchBy );
	}

	var keywordEnter = dojo.byId('add_keyword');
	if ( keywordEnter ) {
	    dojo.connect(keywordEnter, 'onkeydown', Z2h.tags.checkKeywordEnter );
	    dojo.connect(keywordEnter, 'onkeyup', Z2h.tags.addKeyword );
	}

	var removeKeyword = dojo.byId('remove_keyword');
	if ( removeKeyword ) {
	    dojo.connect(removeKeyword, 'onclick', Z2h.tags.removeKeyword );
	    Z2h.tags.searchCreations();
	}

	var doSearch = dojo.byId('doSearch');
	if ( doSearch ) {
	    dojo.connect(doSearch,'onclick', Z2h.tags.searchCreations);
	}

	var tagInput = dijit.byId('add_tag');
	if ( tagInput ) {
	    tagInput.textbox.value = 'enter a tag';
	}
    },

    updateSortByLinks: function(baseLink){
	var relevanceLink = dojo.byId("sortBy_relevance");
	if ( baseLink == "" ) {
	    dojo.style(relevanceLink,{
			   'display': 'none'
		       });
	} else {
	    dojo.style(relevanceLink,{
			   'display': 'block'
		       });
	}

	dojo.query("li.sortBy_list_item a").forEach(function(link){
							link.href = dojo.attr(link,'alt') + baseLink;
						    });
    },

    searchCreations: function(){
	var searchTip = dojo.byId('tagSearchTip');
	if ( searchTip ) {
	    dojo.style(searchTip,'display','none');
	}

	var searchOptions = {
	    'keyword': ''
	};

	searchOptions.tags = new Array();
	searchOptions.usernames = new Array();

	var searchKeyword = dojo.byId('creation_search_keyword');
	if ( searchKeyword !== null && searchKeyword !== undefined ){
	    searchOptions.keyword = dojo.attr(searchKeyword,'innerHTML');
	}

	dojo.query('#keywords li.tag').forEach(function(tag){
						   if ( tag ) {
						       if ( dojo.hasClass(tag,'deleteMe')){
							   dojo.query("#"+tag.id).orphan();
						       } else {
							   dojo.removeClass(tag,'added');
							   var parts = tag.id.split("_");

							   if ( parts[0] == 'tag' ) {
							       searchOptions.tags.push(parts[1]);
							   } else if ( parts[0] == 'username' ) {
							       searchOptions.usernames.push(parts[1]);
							   }
						       }
						   }
					       });

	var searchString = "/";

	if ( searchOptions.keyword !== null && searchOptions.keyword !== undefined && searchOptions.keyword != '' ) {
	    searchString += "keyword/"+searchOptions.keyword + "/";
	}

	if ( searchOptions.tags.length > 0 ){
	    searchString += "tags/" + searchOptions.tags.join(',') + "/";
	}

	if ( searchOptions.usernames.length > 0 ){
	    searchString += "usernames/" + searchOptions.usernames.join(',') + "/";
	}

	node = dijit.byId("category_id");

	if ( node.getValue() > 0 ){
	    searchString += "contest_category_id/" + node.getValue() + "/";
	    dojo.forEach(node.getOptions(), function(childNode,index,list) {
			     if ( childNode.value == node.getValue() ){
				 dojo.attr('list_category','innerHTML'," In The Category '"+childNode.label+"'");
			     }
			 });
	} else {
	    dojo.attr('list_category','innerHTML',"");
	}


	searchString += "format/json/";

	var creationList = dojo.byId('load_ajax_content_here');
	creationList.innerHTML = "<br /><h1>Loading Results</h1><br /><img src='/images/loader.gif' />"

	var clearAllTagsLink = dojo.byId('clearAllTags');
	if ( searchOptions.tags.length > 0 || searchOptions.usernames.length > 0 ){
	    dojo.style( clearAllTagsLink, {
			    'display': 'block'
			});
	} else {
	    dojo.style( clearAllTagsLink, {
			    'display': 'none'
			});
	}

	try {
	    var googleTracker = _gat._getTracker(Z2h.tracking_id);
	    googleTracker._trackPageview(Z2h.tags.creationURL + searchString + "?ga_search=" + searchString);
	} catch (err) {}

	dojo.xhrGet({
			url: Z2h.tags.creationURL + searchString,
			handleAs: "text",
			load : function(response, ioArgs) {
			    var creationList = dojo.byId('load_ajax_content_here');
			    creationList.innerHTML = response;

			    var searchSortByItem = dojo.byId('sortBy_relevance');
			    if ( searchSortByItem ) {
				dojo.style(searchSortByItem,{
					       display: 'inline'
					   });
			    }

			    var searchSortByLink = dojo.byId('sortBy_relevance_link');
			    dojo.query('li.sortBy_list_item a').forEach( function(link){
									     dojo.removeClass(link,'creation_browse_sortBy_current');
									 });
			    if ( searchSortByLink ) {
				dojo.addClass(searchSortByLink,'creation_browse_sortBy_current');
			    } else {
				dojo.addClass("sortBy_newest_link","creation_browse_sortBy_current");
			    }

			    dojo.query("a.load_ajax").forEach(function(link) {
								  dojo.connect(link, "onclick", Z2h.link.loadAjax);
							      });
			    //Z2h.tags.updateSortByLinks(searchString);

			    return response; //always return the response back
			},
			// if any error occurs, it goes here:
			error : function(response, ioArgs) {
			    //error!
			    return response; //always return the response back
			}
		    });
    },

    checkKeywordEnter: function(e){
	if ( e.keyCode == dojo.keys.ENTER ){
	    Z2h.tags.searchCreations();
	}
    },

    switchSearchBy: function(selectWidget){
	var switchTo = selectWidget.value.toLowerCase();
	var addKeyword = dojo.byId("add_keyword_input");
	var addTag = dojo.byId("add_tag_input");

	if ( switchTo == 'tag' ) {
	    dojo.style(addKeyword,{
			   'display': "none"
		       });
	    dojo.style(addTag, {
			   'display': "block"
		       });
	    var tagInput = dijit.byId('add_tag');
	    if ( tagInput ) {
		tagInput.textbox.value = 'enter a tag';
	    }

	} else if ( switchTo == 'keyword' ) {
	    dojo.style(addKeyword,{
			   'display': "block"
		       });
	    dojo.style(addTag, {
			   'display': "none"
		       });
	    var searchTip = dojo.byId('tagSearchTip');
	    if ( searchTip ) {
		dojo.style(searchTip,'display','none');
	    }
	}
    },

    clear: function(select){
	select.promptMessage = 'enter a tag';
	select.invalidMessage = 'enter a tag';

	if (!select.isValid()) {
	    select.invalidMessage = 'no such tag found';
	    select.textbox.value = "";
	}
    },

    undelete: function(e){
	e.preventDefault();
	var parentLi = e.target.parentNode;
	if ( parentLi ) {
	    while ( parentLi.nodeName != 'LI' ){
		parentLi = parentLi.parentNode;
	    }

	    var tag = parentLi.id.replace("username_","");
	    tag = tag.replace("tag_","");
	    if ( tag !== null && dojo.hasClass(parentLi,'deleteMe') ) {
		parentLi.innerHTML = "<p>"+tag + "</p> <span alt='"+parentLi.id+"' class='removeTag img_replace'><span>X</span></span>";
		dojo.removeClass(parentLi,'deleteMe');
		dojo.query(".removeTag").forEach( function(link){
						      dojo.connect(link, 'onclick', Z2h.tags.removeTag );
						  });
	    }
	}
    },

    removeAll: function(e){
	e.preventDefault();
	dojo.query('ul#keywords li.tag').orphan();
	var searchTip = dojo.byId('tagSearchTip');
	if ( searchTip ) {
	    dojo.style(searchTip,'display','none');
	}
	var removeAll = dojo.byId('clearAllTags');
	if ( removeAll ) {
	    dojo.style( removeAll, 'display', 'none' );
	}
	var tagInput = dijit.byId('add_tag');
	if ( tagInput ) {
	    tagInput.textbox.value = 'enter a tag';
	}
	Z2h.tags.searchCreations();
    },

    removeTag: function(e){
	e.preventDefault();
	var searchTip = dojo.byId('tagSearchTip');
	if ( searchTip ) {
	    dojo.style(searchTip,'display','block');
	}
	var parentLi = e.target.parentNode;
	if ( parentLi ) {
	    while ( parentLi.nodeName != 'LI' ){
		parentLi = parentLi.parentNode;
	    }

	    dojo.query('#'+parentLi.id).orphan();

	    if ( dojo.query('ul#keywords li.tag').length <= 0 ){
		var removeAll = dojo.byId('clearAllTags');
		if ( removeAll ) {
		    dojo.style( removeAll, 'display', 'none' );
		}

		if ( searchTip ) {
		    dojo.style(searchTip,'display','none');
		}
	    }
	}
    },

    removeKeyword: function(e){
	if ( e ) {
	    e.preventDefault();
	}
	var keywordDisplay = dojo.byId('creationsSearchTitle');
	keywordDisplay.innerHTML = Z2h.tags.creationTitle;

	var keywordInput = dojo.byId('add_keyword');
	if ( keywordInput ) {
	    keywordInput.value = '';
	}
    },

    addKeyword: function(e){
	var keywordDisplay = dojo.byId("creationsSearchTitle");
	var keywordInput = dojo.byId('add_keyword');

	if ( keywordInput.value.length > 0 ){
	    keywordDisplay.innerHTML = "\"<span id='creation_search_keyword'>" + keywordInput.value + "</span>\" <a id='remove_keyword' href=\"#\">(remove keyword)</a>";
	    var removeKeyword = dojo.byId('remove_keyword');
	    dojo.connect(removeKeyword, 'onclick', function(e){
			     Z2h.tags.removeKeyword(e);
			     Z2h.tags.searchCreations()
			 });
	} else {
	    Z2h.tags.removeKeyword();
	}
    },

    tagExists: function(tag,type){
	var returnValue = false;
	var testValue = type+"_"+tag;
	dojo.query('ul#keywords li.tag').forEach(function(item){
						     if ( testValue == item.id ){
							 returnValue = true;
						     }
						 });
	return returnValue;
    },

    addTag: function(select){
	if ( select.textbox.value.length > 0 && select.item ){
	    var chosen = select.item.value[0];
	    var parts = chosen.split("_");

	    if ( !Z2h.tags.tagExists(parts[0],parts[1]) ){
		var searchTip = dojo.byId('tagSearchTip');
		if ( searchTip ) {
		    dojo.style(searchTip,'display','block');
		}
		select.promptMessage = '';
		var closeSpan = dojo.doc.createElement('span');
		dojo.attr(closeSpan, {
			      'alt': parts[1]+"_"+parts[0].replace(" ","_"),
			      'class': "removeTag img_replace",
			      'innerHTML': "<span>X</span>"
			  });

		dojo.connect(closeSpan,'onclick',Z2h.tags.removeTag);

		var listItem = dojo.doc.createElement('li');
		dojo.attr( listItem,{
			       'id': parts[1]+"_"+parts[0].replace(" ","_"),
			       'class': "tag "+parts[1]+"s added"
			   });
		var tagItem = dojo.doc.createElement('p');
		tagItem.innerHTML = parts[0];
		listItem.appendChild(tagItem);
		listItem.innerHTML += " ";//"<p>"+parts[0]+"</p> ";
		listItem.appendChild(closeSpan);
		var lists = dojo.byId("keywords");

		dojo.place(listItem,"tagAddRefPoint",'before');

		if ( dojo.style(lists,"display") == "none" ) {
		    dojo.style(lists,"display","block");
		}

		var hideKeywords = dojo.byId("clearAllTags");
		if ( dojo.style(hideKeywords,"display") == "none" ){
		    dojo.style(hideKeywords,"display","block");
		}
	    } else {
		select.promptMessage = "You already added '"+ parts[0]+"'";
	    }
	}
	select.textbox.value = "";
	select.reset();
    }
};

//---------------------- GROUP JS --------------------------------
Z2h.group = {
    _running: false,

    init: function() {
	// hook onchange event to select vote.
	var group_type_select = dojo.byId('group_type');
	if (group_type_select) {
	    dojo.connect(group_type_select, 'onchange', Z2h.group.refreshGroupDescription);
	}

	// hook onclick event to show dialog to leave a group.
	dojo.query("a.leave_group").forEach(function(link) {
						dojo.connect(link, "onclick", Z2h.group.leaveGroupDialog);
					    });

	// hook onclick event to submit form to search group members or posts
	var group_search_btn = dojo.byId('group_search_btn');
	if (group_search_btn) {
	    dojo.connect(group_search_btn, 'onclick', Z2h.group.searchGroup);
	}

	// hook onclick event to submit form to search group members or posts
	var group_search_form = dojo.byId('group_search');
	if (group_search_form) {
	    dojo.connect(group_search_form, 'onsubmit', Z2h.group.searchGroup);
	}

	// hook onclick event to submit form to send group invitation
	var group_invitation_btn = dojo.byId('group_invitation_btn');
	if (group_invitation_btn) {
	    dojo.connect(group_invitation_btn, 'onclick', Z2h.group.sendInvitation);
	}

	// hook onclick event to submit form to send group invitation
	var group_invitation_form = dojo.byId('group_invitation_form');
	if (group_invitation_form) {
	    dojo.connect(group_invitation_form, 'onsubmit', Z2h.group.sendInvitation);
	}
    },

    refreshGroupDescription: function(evt) {
	evt.preventDefault();

	var type = evt.currentTarget.value;

	dojo.query(".group_description").forEach(function(p) {
						     p.style.display = "none";
						 });

	var selected_description = dojo.byId("group_description_"+type);
	if (selected_description) {
	    selected_description.style.display = "block";
	}
    },

    // show overlay form to leave group
    leaveGroupDialog: function(evt) {
	evt.preventDefault();

	var href = evt.currentTarget.href;

	// only send an ajax request if nothing is running
	if (Z2h.group._running === false) {
	    Z2h.group._running = true;

	    dojo.xhrGet({
			    url: href + "/format/text",  //the relative URL
			    handleAs: "text",
			    //			 	sync: true,
			    // run this function if the request is successful
		            load : function(response, ioArgs) {
			 	if (response == "logged_out") {
			 	    window.location.assign("/login-required");
			 	} else {
			 	    // close already opend overlay form
			 	    var opened_form = dijit.byId("leave_form_overlay");

			 	    if (opened_form) {
			 		opened_form.hide();
			 		opened_form.destroy();
			 	    }

			 	    // initialize dialog
				    var leave_form = new dijit.Dialog({id: "leave_form_overlay"});
				    dojo.style(leave_form.titleBar, "display", "none");

				    leave_form.attr("content", response);
				    leave_form.show();

				    // close over flag form
				    dojo.query("#leave_cancel_btn, .overlay_leave_close, .popupCancelButton").forEach(function(node, i) {
															  var closeHandle = dojo.connect(node,
																			 "onclick",
																			 dojo.hitch(leave_form,
														     						    function(e){
														    							e.preventDefault();
														    							leave_form.attr("content", "");
														    							leave_form.hide();
														    							leave_form.destroy();
														     							dojo.disconnect(closeHandle);
																				    }));
														      });

				    // overwrite the default esc key event
				    var escHandle = dojo.connect(leave_form.domNode, "onkeypress", function(e){
								     var key = e.keyCode || e.charCode;
								     var k = dojo.keys;

								     if (key == k.ESCAPE) {
									 e.preventDefault();
									 leave_form.attr("content", "");
									 leave_form.hide();
									 leave_form.destroy();
							     		 dojo.disconnect(escHandle);
								     }
								 });

				    // create a submit button to send the leave form
				    var submitButton = dojo.byId("leave_submit_btn");
				    if (submitButton) {
					dojo.connect(submitButton,
						     "onclick",
						     function(e){
							 e.preventDefault();
							 Z2h.group.submitLeave(submitButton.href);
					    	     });
				    }
			 	}

				return response; //always return the response back
		            },
		            // run this function if the request is not successful
		            error : function(response, ioArgs) {
				alert("ERROR: There was an error while submitting your request. Please try again!");

				/* handle the error... */
				return response; //always return the response back
		            }
			});

	    Z2h.group._running = false;
	}
    },

    // submit leave form
    submitLeave: function(href) {
	var form = document.createElement("form");
	form.setAttribute("id", "leaveForm");
	form.setAttribute("method", "POST");
	form.setAttribute("action", href);
	document.getElementsByTagName("body").item(0).appendChild(form);
	form.submit();
    },

    searchGroup: function(evt) {
	evt.preventDefault();

	var form = dojo.byId('group_search');
	var input = dojo.byId('group_search_keyword');

	if (form && input) {
	    var base_href = form.action;

	    // update dom id (make sure there is div id=load_ajax_content_here)
	    var update_dom = dojo.byId("load_ajax_content_here");

	    // while loading (make sure there is div id=load_ajax_content_loading)
	    var loading_wait = dojo.byId("load_ajax_content_loading");

	    // ajax requst url
	    var href = base_href+"/keyword/"+input.value;

	    if (loading_wait) {
		update_dom.style.display = "none";
		loading_wait.style.display = "";
	    }

	    dojo.xhrGet({
			    url: href + "/format/text/",
			    handleAs: "text",
			    //			 	sync: true,
			    // run this function if the request is successful
		            load : function(response, ioArgs) {
				// set some element's content
				update_dom.innerHTML = response;

				if (loading_wait) {
				    loading_wait.style.display = "none";
				    update_dom.style.display = "";
				}

				// initialize js
				Z2h.global.init();

				return response; //always return the response back
		            },
		            // run this function if the request is not successful
		            error : function(response, ioArgs) {
				console.log("failed xhrGet", response, ioArgs);

				alert("ERROR: There was an error while submitting your request. Please try again!");
				/* handle the error... */
				return response; //always return the response back
		            }
			});
	}
    },

    sendInvitation: function(evt) {
	evt.preventDefault();

	var form = dojo.byId('group_invitation_form');

	// count errors
	var errors = 0;
	var error_msg = "";

	// validate recipients
	var total = Z2h.inbox.recipients.total();
	if (total == 0) {
	    errors++;

	    if (error_msg != "") {
		error_msg += "<br />";
	    }
	    error_msg += "At lease one recipient is required for the message.";
	}

	// validate subject
	var subject = Z2h.string.trimAll(dojo.byId('inbox_title').value);
	if (subject.length == 0) {
	    errors++;

	    if (error_msg != "") {
		error_msg += "<br />";
	    }
	    error_msg += "Subject is required.";
	}

	// validate body
	var body = Z2h.string.trimAll(dojo.byId('inbox_compose_textarea').value);
	if (body.length < 10) {
	    errors++;

	    if (error_msg != "") {
		error_msg += "<br />";
	    }
	    error_msg += "Your message is too short, it can't be shorter than 10 characters.";
	}

	// validate form
	if (errors > 0) {
	    // display error message
	    dojo.byId("inbox_compose_errors").innerHTML = error_msg;
	} else {
	    dojo.byId("inbox_compose_errors").innerHTML = "";

	    // update dom id (make sure there is div id=load_ajax_content_here)
	    var update_dom = dojo.byId("load_ajax_content_here");

	    // while loading (make sure there is div id=load_ajax_content_loading)
	    var loading_wait = dojo.byId("load_ajax_content_loading");

	    if (loading_wait) {
		update_dom.style.display = "none";
		loading_wait.style.display = "";
	    }

	    if (form) {
		dojo.xhrPost({
				 url: form.action + "/format/json",
				 form: "group_invitation_form",
				 handleAs: "json",
				 //					sync: true,
				 headers: {"X-Requested-With": "XMLHttpRequest"},
				 load: function(data,ioargs){
				     // refresh the current page
				     window.location.reload(true);

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

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

				     /* handle the error... */
				     return response; //always return the response back
				 }
			     });
	    }
	}
    }
};

Z2h.zip = {
    clearErr: function(select,field){
	//console.log("Z2h.zip.clearErr() called");
	Z2h.autocomplete.clearErr(select,field);
    },

    resetField: function(select){
	var selectRegular = dojo.byId(select.id);
	var hiddenZip = dojo.byId("zip_code_field");

	if ( selectRegular ){
	    if ( hiddenZip ) {
		hiddenZip.value = selectRegular.value;
	    }
	}

	if ( selectRegular.value != "" ) {
	    select.setValue(selectRegular.value);
	}
	Z2h.autocomplete.resetField(select);
    }

};

Z2h.tooltip = {
    _timeout: 5000,

    _container: 'toasterList',

    popups: function(list,type){
	for ( var i in list ){
	    if ( type == "points" ) {
		this.popupPoints(list[i].mesg,list[i].points);
	    } else if ( type == "error" ){
		this.popupError(list[i].mesg);
	    } else if ( type == "rank" ) {
		this.popupRank(list[i].mesg,list[i].points,list[i].rank);
	    } else if ( type == "suggestion" ){
		this.popupSuggestion(list[i].mesg);
	    } else if ( type == "avatar" ) {
		this.popopSuggestionWithAvatar(list[i].mesg,list[i].avatar);
	    }
	}
    },

    popup: function(message){
	var tempPopup = new Z2h.Toast({
					  containerNode: this._container,
					  mainContent: message,
					  imgSrc:"/images/temp/exclaimation_green.png"});
	tempPopup.show();
    },

    popupError: function(message){
	var tempPopup = new Z2h.Toast({
					  containerNode: this._container,
					  mainContent: message,
					  imgSrc:"/images/temp/exclaimation_red.png",
					  notificationType:"error",
					  sticky: true
				      });
	tempPopup.show();
    },

    popupPoints: function(message,points){
	var tempPopup = new Z2h.Toast({
					  containerNode: this._container,
					  notificationType:"points",
					  mainContent: message,
					  topText: points,
					  bottomText:"Points",
					  imgSrc:"/images/icons/icon_coin.gif"
				      });
	tempPopup.show();
    },

    popupRank: function(message,points,rank){
	var tempPopup = new Z2h.Toast({
					  containerNode: this._container,
					  notificationType:"rank",
					  mainContent: message,
					  topText: points,
					  bottomText:"Points",
					  imgSrc:"/images/icons/icon_rank"+rank+".gif"
				      });
	tempPopup.show();
    },

    popupSuggestion: function(message){
	var tempPopup = new Z2h.Toast({
					  containerNode: this._container,
					  mainContent: message,
					  imgSrc:"/images/temp/exclaimation_purple.png",
					  notificationType:"suggestion"
				      });
	tempPopup.show();
    },

    popupSuggestionWithAvatar: function(message,avatar){
	var tempPopup = new Z2h.Toast({
					  containerNode: this._container,
					  mainContent: message,
					  imgSrc: avatar,
					  notificationType:"suggest_av"
				      });
	tempPopup.show();
    },

    popupFromObject: function(obj){
	tempPopup['containerNode'] = this._container;
	var tempPopup = new Z2h.Toast(obj);
	tempPopup.show();
    }


};

Z2h.isMature = {
    _running: false,
    _redirect: true,
    _sendTo: "/",

    init: function(){
	var isMatureBehavior = {
	    ".isMature": {
		onclick: function(evt){
		    Z2h.isMature.isMature(evt);
		}
	    }
	};

	dojo.behavior.add(isMatureBehavior);
    },

    isMature: function(evt) {
	evt.preventDefault();

	var isMature = dojo.cookie("isMature");
	var href = "";

	if (Z2h.isMature._redirect) {
	    href= evt.currentTarget.href;
	} else {
	    href = Z2h.isMature._sendTo;
	}

	if (isMature && isMature == "1"){
	    // isMature cookie is set, value is 1 ( TRUE ), user is mature, no need to ask
	    if(this._redirect){
		window.location.assign(href.replace("#",""));
	    } else {
		var mature_content_dom = dojo.byId("mature_content");
		if (mature_content_dom) {
		    dojo.style(mature_content_dom,"display","none");
		}
	    }
	} else if (isMature && isMature == "0"){
	    // isMature cookie is set, value is 0 ( FALSE ), user is not mature, can't view content
	    Z2h.isMature.notMature();
	} else {
	    // isMature cookie not set or improper value, ask user for their birthday
	    Z2h.isMature.createIsMatureDialog(escape(href.replace(/\//g,"|")));
	}
    },

    // handles redirecting or error message if the user isn't mature
    notMature: function() {
	/*var matureOverlay = dojo.byId('mature_content');
	 if (matureOverlay){
	 window.location.assign(this._sendTo);
	 } else { */
	// close already opend dialog form.
	var opened_askAgeDialog = dijit.byId('askAgeDialog');
	if (opened_askAgeDialog) {
	    opened_askAgeDialog.hide();
	    opened_askAgeDialog.destroy();
	}

	Z2h.link.popup("not_mature_dialog", "You Are Not 18+", "You are not old enought to view this content", null);
	//}
    },

    createIsMatureDialog: function(url) {
	// only send an ajax request if nothing is running.
	if (Z2h.isMature._running === false) {
	    Z2h.isMature._running = true;

	    dojo.xhrGet({
			    url: "/default/interaction/is-mature/format/text/url/"+url,  //the relative URL
			    handleAs: "text",
			    //			 	sync: true,
			    // run this function if the request is successful
		            load : function(response, ioArgs) {
				// close already opend dialog form.
				var opened_askAgeDialog = dijit.byId('askAgeDialog');
				if (opened_askAgeDialog) {
				    opened_askAgeDialog.hide();
				    opened_askAgeDialog.destroy();
				}

				// initialize dialog.
				var askAgeDialog = new dijit.Dialog({id: "askAgeDialog"});
				dojo.style(askAgeDialog.titleBar, "display", "none");

				askAgeDialog.attr('content', response);
				askAgeDialog.show();

				// close over flag form.
				dojo.query(".cancel_mature_check").forEach(function(node, i){
									       var closeHandle = dojo.connect(node,
													      "onclick",
													      dojo.hitch(askAgeDialog,
													     		 function(e){
													    		     e.preventDefault();
													    		     askAgeDialog.attr('content', '');
													    		     askAgeDialog.hide();
													    		     askAgeDialog.destroy();
													     		     dojo.disconnect(closeHandle);
													     		 }));
									   });

				// overwrite the default esc key event.
				var escHandle = dojo.connect(askAgeDialog.domNode, "onkeypress", function(e){
								 var key = e.keyCode || e.charCode;
								 var k = dojo.keys;

								 if (key == k.ESCAPE) {
								     e.preventDefault();
								     askAgeDialog.attr('content', '');
								     askAgeDialog.hide();
								     askAgeDialog.destroy();
						     		     dojo.disconnect(escHandle);
								 }
							     });

				// create a submit button to send the flag form.
				var submitButton = dojo.byId('check_if_mature');
				if (submitButton) {
				    dojo.connect(submitButton,
						 "onclick",
						 function(e){
						     e.preventDefault();
						     Z2h.isMature.checkMature();
				    		 });
				}

				var ask_post_form = dojo.byId('checkMatureForm');
				if (ask_post_form) {
				    dojo.connect(ask_post_form,
						 "onsubmit",
						 function(e){
						     e.preventDefault();
						     Z2h.isMature.checkMature();
				    		 });
				}

				// hook events with birthday select list.
				var checkMatureYear = dojo.byId('checkMatureYear');
				var checkMatureMonth = dojo.byId('checkMatureMonth');
				var checkMatureDay = dojo.byId('checkMatureDay');

				if (checkMatureYear && checkMatureMonth && checkMatureDay) {
				    dojo.connect(checkMatureMonth,
						 "onchange",
						 function(e){
				    		     Z2h.user.calenderDays('checkMatureDay', 'checkMatureMonth', 'checkMatureYear');
				    		 });

				    dojo.connect(checkMatureYear,
						 "onchange",
						 function(e){
						     Z2h.user.calenderDays('checkMatureDay', 'checkMatureMonth', 'checkMatureYear');
				    		 });
				}

				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.isMature._running = false;
    },

    checkMature: function() {
	// only send an ajax request if nothing is running.
	if (Z2h.isMature._running === false) {
	    Z2h.isMature._running = true;

	    var form = dojo.byId('checkMatureForm');

	    if (form) {
		// validate form. (make sure year, month and day are selected)
		var checkMatureYear = dojo.byId('checkMatureYear');
		var checkMatureMonth = dojo.byId('checkMatureMonth');
		var checkMatureDay = dojo.byId('checkMatureDay');
		var errorContainer = dojo.byId("checkMatureError");

		if (checkMatureYear && checkMatureMonth && checkMatureDay) {
		    var birth_m = checkMatureMonth.value;
		    var birth_d = checkMatureDay.value;
		    var birth_y = checkMatureYear.value;

		    if(birth_m != '00' && birth_d != '00' && birth_y != '0000'){
			var overlay_wait = dojo.byId("overlay_please_wait");
			var btn_active = dojo.byId("overlay_age_position");
			var status_active = dojo.byId("overlay_age_form");

			if (errorContainer) {
			    errorContainer.innerHTML = "";
			}

			if (status_active && btn_active && overlay_wait) {
			    status_active.style.display = "none";
			    btn_active.style.display = "none";
			    overlay_wait.style.display = "";
			}

			dojo.xhrPost({
					 url: form.action+'/format/json',
					 form: "checkMatureForm",
					 handleAs: "json",
					 //							sync: true,
					 headers: {"X-Requested-With": "XMLHttpRequest"},
					 load: function(data,ioargs){
					     if(data.result == '-1') {
						 // invalid birthday.
						 if (errorContainer) {
						     errorContainer.innerHTML = "Please enter a valid birthday";
						 }
					     } else if(data.result == '1') {
						 // mature
						 if (data.redirect) {
						     window.location.assign(data.url.replace("#",""));
						 } else {
						     var mature_content_dom = dojo.byId("mature_content");
						     if (mature_content_dom) {
							 dojo.style(mature_content_dom,"display","none");
						     }
						 }
					     } else {
						 // immature
						 Z2h.isMature.notMature();
					     }

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

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

					     /* handle the error... */
					     return response; //always return the response back
					 }
				     });


		    } else {
			// must select validate birthday
			if (errorContainer) {
			    errorContainer.innerHTML = "Please enter a valid birthday";
			}
		    }
		} else {
		    Z2h.link.popup("not_mature_dialog", "You Are Not 18+", "You are not old enought to view this content", null);
		}
	    }

	    Z2h.isMature._running = false;
	}
    }
};

//---------------------- ADMIN JS -------------------------
Z2h.admin = {
    _running: false,

    init: function() {
	// hook onclick event to show form.
	var admin_edit_submit = dojo.byId('admin_edit_submit');
	if (admin_edit_submit) {
	    dojo.connect(admin_edit_submit, 'onclick', Z2h.admin.edit);
	}

	var admin_edit_form = dojo.byId('admin_edit_form');
	if (admin_edit_form) {
	    dojo.connect(admin_edit_form,'onsubmit', Z2h.admin.edit);
	}
    },

    edit: function(evt) {
	evt.preventDefault();

	var admin_edit_form = dojo.byId('admin_edit_form');

	if (Z2h.admin.isValid() && admin_edit_form) {
	    // get editor value as textarea body value
	    var dojo_editor = dijit.byId("dojo_editor_textarea");

	    if (dojo_editor) {
	 	var textarea = document.createElement("textarea");
		dojo.attr(textarea, "name", "body");
		dojo.style(textarea, {"display": "none"});
		textarea.value = dojo_editor.getValue();

		dojo.place(textarea, admin_edit_form, "first");
	    }

	    admin_edit_form.submit();
	}
    },

    isValid: function() {
	var errors = 0;

	// validate title.
	var title = dojo.byId("excls_title");
	var titleError = dojo.byId("form_error_title");

	if (title.value.length == 0) {
	    errors++;
	    title.style.border =  "solid 1px red";
	    titleError.innerHTML = "You must enter a title";
	    dojo.style(titleError, "color", "red");
	    titleError.style.display = "block";
	} else {
	    title.style.border = "solid 1px black";
	    titleError.style.display = "none";
	}

	// validate body.
	var dojo_editor = dijit.byId("dojo_editor_textarea");
	if (dojo_editor) {
	    var body = dojo_editor.getValue();
	    body = body.replace("<br />", "");
	    body = body.replace(/^\s*/, "").replace(/\s*$/, "").replace(/<\/?[^>]+(>|$)/g, "");

	    var bodyError = dojo.byId("form_error_body");
	    var textarea = dojo.byId("dojo_editor_textarea");

	    if (body.length < 10) {
		errors++;
		textarea.style.border = "solid 1px red";
		bodyError.innerHTML = "Content can't be shorter than 10 characters";
		dojo.style(bodyError, "color", "red");
		bodyError.style.display = "block";
	    } else {
		textarea.style.border = "solid 1px #bfbfbf";
		bodyError.style.display = "none";
	    }
	}

	// validate form.
	if(errors == 0){
	    return true;
	} else {
	    return false;
	}
    }
};

//---------------------- EXCLUSIVES JS -------------------------
Z2h.excls = {
    _running: false,

    init: function() {
	// hook onclick event to show preview.
	var excls_preview_submit = dojo.byId('excls_preview_submit');
	if (excls_preview_submit) {
	    dojo.connect(excls_preview_submit, 'onclick', Z2h.excls.preview);
	}

	// hook onclick event to show form.
	var excls_edit_submit = dojo.byId('excls_edit_submit');
	if (excls_edit_submit) {
	    dojo.connect(excls_edit_submit, 'onclick', Z2h.excls.edit);
	}

	var exclusiveBehavior = {
	    '#article_dates': {
		onchange: function(e){
		    e.preventDefault();
		    Z2h.excls.loadArticles(e.target);
		}
	    }
	};

	dojo.behavior.add(exclusiveBehavior);
    },

    fixTags: function(evt){
	dojo.query(".discussion_post_tag input").every( function(node){
							    if ( node.value.match(/[^a-zA-Z0-9]+/g) ){
								evt.preventDefault();
								Z2h.tooltip.popupError("Tag name should contain only letters and numbers, and cannot have spaces.");
								return;
							    }
							});
    },

    edit: function(evt) {
	evt.preventDefault();

	dojo.query(".edit_view").forEach(function(edit) {
					     edit.style.display = "block";
					 });

	dojo.query(".preview_view").forEach(function(preview) {
						preview.style.display = "none";
					    });
    },

    preview: function(evt) {
	evt.preventDefault();

	if (Z2h.excls.isValid()) {
	    var excls_title_input = dojo.byId('excls_title');
	    var excls_title_preview = dojo.byId('excls_title_preview');

	    if (excls_title_input && excls_title_preview) {
		excls_title_preview.innerHTML = excls_title_input.value;
	    }

	    var dojo_editor = dijit.byId("dojo_editor_textarea");
	    var excls_body_preview = dojo.byId('excls_body_preview');

	    if (dojo_editor && excls_body_preview) {
		excls_body_preview.innerHTML = dojo_editor.getValue();
	    }

	    var excls_quote = dojo.byId('excls_publish_textarea');
	    var excls_quote_preview = dojo.byId('excls_quote_preview');

	    if (excls_quote && excls_quote_preview) {
		excls_quote_preview.innerHTML = excls_quote.value;
	    }

	    dojo.query(".edit_view").forEach(function(edit) {
						 edit.style.display = "none";
					     });

	    dojo.query(".preview_view").forEach(function(preview) {
						    preview.style.display = "block";
						});

	    var pending_video = dojo.byId("swfupVideoPending");
	    if (pending_video && pending_video.value == 0) {
		// hide the video
		var video_placeholder = dojo.byId("video_placeholder");
		if (video_placeholder) {
		    video_placeholder.style.display = "none";
		}
	    }
	}
    },

    disableForm: function(dis) {
	/*var title = dojo.byId("excls_title");
	 if (title) {
	 title.disabled = dis;
	 }

	 var quote = dojo.byId("excls_publish_textarea");
	 if (quote) {
	 quote.disabled = dis;
	 }*/

	var dojo_editor = dijit.byId("dojo_editor_textarea");
	if (dojo_editor) {
	    dojo_editor.attr("disabled", dis);
	}

	/* var quote = dojo.byId("excls_publish_textarea");
	 if (quote) {
	 quote.disabled = dis;
	 }

	 dojo.query(".dijitReset").forEach(function(tag) {
	 tag.disabled = dis;
	 }); */

	var excls_please_wait = dojo.byId("excls_please_wait");
	if (dis) {
	    dojo.query("button").forEach(function(btn) {
					     btn.style.display = "none";
					 });

	    if (excls_please_wait) {
		excls_please_wait.style.display = "block";
	    }
	} else {
	    dojo.query("button").forEach(function(btn) {
					     btn.style.display = "block";
					 });

	    if (excls_please_wait) {
		excls_please_wait.style.display = "none";
	    }
	}
    },

    isValid: function() {
	var errors = 0;

	// validate title.
	var title = dojo.byId("excls_title");
	var titleError = dojo.byId("form_error_title");

	if (title.value.length == 0) {
	    errors++;
	    title.style.border =  "solid 1px red";
	    titleError.innerHTML = "You must enter a title";
	    dojo.style(titleError, "color", "red");
	    titleError.style.display = "block";
	} else {
	    title.style.border = "solid 1px black";
	    titleError.style.display = "none";
	}

	// validate header image.
	var header_image = dojo.byId("swfupImageFileHidden");
	var image = dojo.byId("swfupImageFileQueued");
	var imageError = dojo.byId("form_error_image");

	if (header_image.value.length == 0) {
	    errors++;
	    image.style.border =  "solid 1px red";
	    imageError.innerHTML = "Please upload a header image";
	    dojo.style(imageError, "color", "red");
	    imageError.style.display = "block";
	} else {
	    image.style.border = "solid 1px black";
	    imageError.style.display = "none";
	}

	// validate quote.
	var quote = dojo.byId("excls_publish_textarea");
	var quoteError = dojo.byId("form_error_quote");

	if (quote.value.length == 0) {
	    errors++;
	    quote.style.border =  "solid 1px red";
	    quoteError.innerHTML = "Pull Quote is required";
	    dojo.style(quoteError, "color", "red");
	    quoteError.style.display = "block";
	} else {
	    quote.style.border = "solid 1px black";
	    quoteError.style.display = "none";
	}

	// validate body.
	var dojo_editor = dijit.byId("dojo_editor_textarea");
	if (dojo_editor) {
	    var body = dojo_editor.getValue();
	    body = body.replace("<br />", "");
	    body = body.replace(/^\s*/, "").replace(/\s*$/, "").replace(/<\/?[^>]+(>|$)/g, "");

	    var bodyError = dojo.byId("form_error_body");
	    var textarea = dojo.byId("dojo_editor_textarea");

	    if (body.length < 10) {
		errors++;
		textarea.style.border = "solid 1px red";
		bodyError.innerHTML = "Content can't be shorter than 10 characters";
		dojo.style(bodyError, "color", "red");
		bodyError.style.display = "block";
	    } else {
		textarea.style.border = "solid 1px #bfbfbf";
		bodyError.style.display = "none";
	    }
	}

	// validate tags.
	var tag_errors = 0;
	for (i=1;i<=5;i++) {
	    var eachTag = dojo.byId("content_tag_"+i);
	    if (eachTag && eachTag.value.match(/[^a-zA-Z0-9]+/g)) {
		tag_errors++;
	    }
	}

	var tagError = dojo.byId("form_error_tags");
	if (tag_errors > 0) {
	    tagError.innerHTML = "Tag name should contain only letters and numbers, and cannot have spaces.";
	    dojo.style(tagError, "color", "red");
	    tagError.style.display = "block";
	} else {
	    tagError.style.display = "none";
	}

	// validate form.
	if(errors == 0){
	    return true;
	} else {
	    return false;
	}
    },

    loadArticles: function(target){
	var chosen = target.value;
	var form = dojo.byId('article_list_change');

	// update dom id
	var update_dom = dojo.byId('article_list');

	// while loading
	var loading_wait = dojo.byId("load_ajax_excls_loading");

	if (loading_wait && update_dom && form) {
	    update_dom.style.display = "none";
	    loading_wait.style.display = "";

	    if (form) {
		dojo.xhrPost({
				 url: form.action+"/date_range/"+chosen+"/format/json",
				 handleAs: "text",
				 headers: {"X-Requested-With": "XMLHttpRequest"},
				 load: function(data,ioargs){
				     update_dom.innerHTML = data;
				     update_dom.style.display = "";
				     loading_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.slideshow = {
    playerStarted: function(obj){
	dojo.publish("Z2h.slideshow.playerStarted",[obj]);
    }
};

//---------------------- VIDEO JS --------------------------------
Z2h.video = {
    _running: false,

    _href: null,

    _refresh: false,

    init: function() {
	// hook onclick event to refresh video.
	dojo.query("a.load_ajax_video").forEach(function(link) {
						    dojo.connect(link, "onclick", Z2h.video.loadVideoAjax);
						});

	var edit_video_form = dojo.byId('edit_video_form');
	if (edit_video_form) {
	    dojo.connect(edit_video_form,'onsubmit',Z2h.video.checkGenre);
	}

	var creation_publish_submit = dojo.byId('creation_publish_submit');
	if (creation_publish_submit) {
	    dojo.connect(creation_publish_submit,'onclick',Z2h.video.checkGenre);
	}

	var creation_update_submit = dojo.byId('creation_update_submit');
	if (creation_update_submit) {
	    dojo.connect(creation_update_submit,'onclick',Z2h.video.checkGenre);
	}

	var emptyQuestion = "Want your fans to give you specific feedback? Ask them a question here!";

	dojo.behavior.add({
			      "#video_question_textarea" : {
				  'onfocus': function(e){
				      e.preventDefault();
				      var updated_question = e.target.value;
				      var question_text = dojo.byId("video_question");

				      if (updated_question == emptyQuestion) {
					  e.target.value = "";
					  dojo.removeClass(e.target, "empty_box");

					  if (question_text) {
					      dojo.removeClass(question_text, "text_length_aid_disable");
					      dojo.addClass(question_text, "text_length_aid");

					      dojo.query(".text_length_aid").forEach(function(aid) {
											 var id = aid.id;
											 var textarea_dom = dojo.byId(id + "_textarea");
											 var length = 1000;

											 if (dojo.hasAttr(aid, "title")) {
											     length = dojo.attr(aid, "title");
											 }

											 if (textarea_dom) {
								 			     Z2h.string.countTextarea(textarea_dom, id, length);

											     dojo.connect(textarea_dom, "onkeyup", function() {
													      Z2h.string.countTextarea(textarea_dom, id, length);
							    						  });
											 }
										     });
					  }
				      }
				  },
				  'onblur': function(e){
			    	      e.preventDefault();
			    	      var updated_question = e.target.value;
			    	      var question_text = dojo.byId("video_question");

				      if (updated_question == "") {
					  e.target.value = emptyQuestion;
					  dojo.addClass(e.target, "empty_box");

					  if (question_text) {
					      dojo.removeClass(question_text, "text_length_aid");
					      dojo.addClass(question_text, "text_length_aid_disable");
					  }
				      }
				  }
			      }
			  });
    },

    // before submitting a form, check a genre is selected.
    checkGenre: function(evt) {
	evt.preventDefault();

	var title = dojo.byId("video_title");
	var errors = false;

	var titleError = dojo.byId("form_error_title");
	if (title.value.length <= 0) {
	    errors = true;
	    title.style.border =  "solid 1px red";
	    titleError.innerHTML = "You must enter a title";
	    dojo.style(titleError, "color", "red");
	    titleError.style.display = "block";
	} else {
	    title.style.border = "solid 1px black";
	    titleError.style.display = "none";
	}

	var video_genre_id = dojo.byId("video_genre_id");
	var genreError = dojo.byId("form_error_genre");

	if (video_genre_id) {
	    var selected = video_genre_id.value;

	    if (selected == 0) {
		if (genreError) {
		    errors = true;
		    genreError.innerHTML = "Please pick a genre for your video";
		    dojo.style(genreError, "color", "red");
		    genreError.style.display = "block";
		}
	    } else {
		if (genreError) {
		    genreError.innerHTML = "";
		    genreError.style.display = "none";
		}
	    }
	}

	if (!errors) {
	    var theForm = dojo.byId("edit_video_form");
	    if (theForm) {
		theForm.submit();
	    }
	}
    },

    // load content by ajax call
    loadVideoAjax: function(evt) {
	evt.preventDefault();

	var video_filename = "";
	var video_thumbnail = "";

	if (dojo.hasAttr(evt.currentTarget, "alt")){
	    var files = dojo.attr(evt.currentTarget, "alt");
	    var filesSplit = files.split("#");

	    video_filename = filesSplit[0];
	    video_thumbnail = filesSplit[1];
	}

	// 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.video._running === false) {
	    Z2h.video._running = true;

	    if (loading_wait) {
		update_dom.style.display = "none";
		loading_wait.style.display = "";
	    }

	    dojo.query("a.current_video").forEach(function(link) {
						      dojo.removeClass(link, "current_video");
						  });

	    dojo.addClass(evt.currentTarget, "current_video");

	    dojo.xhrGet({
			    url: href + "/format/text/",
			    handleAs: "text",
			    // run this function if the request is successful
		            load : function(response, ioArgs) {
				// set some element's content
				update_dom.innerHTML = response;

				var clearTheDiv = dojo.byId("making_of_video");

				if (clearTheDiv) {
				    clearTheDiv.innerHTML = "";
				}

				if (loading_wait) {
				    loading_wait.style.display = "none";
				    update_dom.style.display = "";
				}

				var flashvars = {
				    file:video_filename,
				    autostart:true,
				    image:video_thumbnail
				};

				var params = {
				    "wmode": "opaque",
				    "allowFullScreen": "true",
				    "allowscriptaccess":"always"
				};

				var attributes = {};
				swfobject.embedSWF(
				    "/flash/player.swf",
				    "making_of_video",
				    "520", "312",
				    "9.0.0",
				    "/js/expressInstall.swf",
				    flashvars,
				    params,
				    attributes
				);

				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.video._running = false;
	}
    }
};

Z2h.contest = {
    init: function(){
	dojo.behavior.add({
			      ".ContestFAQExpand": {
				  onclick: function(e){
				      e.preventDefault();
				      Z2h.contest.toggleAnswer(e.target);
				  }
			      },

			      ".contest_nominee_vote": {
				  onclick: function(e){
				      e.preventDefault();
				      Z2h.contest.openVotingWidget(e.target);
				  }
			      }
			  });

	dojo.subscribe("/flash/voting/reload/",dojo.hitch(this,'getPoints'));

    },

    getPoints: function(data){
	dojo.xhrGet({
			url: "/contest/index/get-points-spent/",
			handleAs: "json",
			headers: {"X-Requested-With": "XMLHttpRequest"},
			load: function(data,ioargs){
			    dojo.forEach(data.messages, function(item){
					     Z2h.tooltip.popupPoints(item.mesg.replace("/",""),item.points);
					 });
			    return data;
			},
			error: function(response,ioargs){

			    return response;
			}
		    });
    },

    updateCategory: function(node){
	var searchTip = dojo.byId('tagSearchTip');
	if ( searchTip ) {
	    dojo.style(searchTip,'display','none');
	}

	var searchOptions = {
	    'keyword': ''
	};

	searchOptions.tags = new Array();
	searchOptions.usernames = new Array();

	var searchKeyword = dojo.byId('creation_search_keyword');
	if ( searchKeyword !== null && searchKeyword !== undefined ){
	    searchOptions.keyword = dojo.attr(searchKeyword,'innerHTML');
	}

	dojo.query('#keywords li.tag').forEach(function(tag){
						   if ( tag ) {
						       if ( dojo.hasClass(tag,'deleteMe')){
							   dojo.query("#"+tag.id).orphan();
						       } else {
							   dojo.removeClass(tag,'added');
							   var parts = tag.id.split("_");

							   if ( parts[0] == 'tag' ) {
							       searchOptions.tags.push(parts[1]);
							   } else if ( parts[0] == 'username' ) {
							       searchOptions.usernames.push(parts[1]);
							   }
						       }
						   }
					       });

	var searchString = "/";

	if ( searchOptions.keyword !== null && searchOptions.keyword !== undefined && searchOptions.keyword != '' ) {
	    searchString += "keyword/"+searchOptions.keyword + "/";
	}

	if ( searchOptions.tags.length > 0 ){
	    searchString += "tags/" + searchOptions.tags.join(',') + "/";
	}

	if ( searchOptions.usernames.length > 0 ){
	    searchString += "usernames/" + searchOptions.usernames.join(',') + "/";
	}

	if ( node.getValue() > 0 ){
	    searchString += "contest_category_id/" + node.getValue() + "/";
	    dojo.forEach(node.getOptions(), function(childNode,index,list) {
			     if ( childNode.value == node.getValue() ){
				 dojo.attr('list_category','innerHTML'," In The Category '"+childNode.label+"'");
			     }
			 });
	} else {
	    dojo.attr('list_category','innerHTML',"");
	}

	searchString += "format/json/";


	var creationList = dojo.byId('load_ajax_content_here');
	creationList.innerHTML = "<br /><h1>Loading Results</h1><br /><img src='/images/loader.gif' />"

	var clearAllTagsLink = dojo.byId('clearAllTags');
	if ( searchOptions.tags.length > 0 || searchOptions.usernames.length > 0 ){
	    dojo.style( clearAllTagsLink, {
			    'display': 'block'
			});
	} else {
	    dojo.style( clearAllTagsLink, {
			    'display': 'none'
			});
	}

	try {
	    var googleTracker = _gat._getTracker(Z2h.tracking_id);
	    googleTracker._trackPageview(Z2h.tags.creationURL + searchString + "?ga_search=" + searchString);
	} catch (err) {}

	dojo.xhrGet({
			url: Z2h.tags.creationURL + searchString,
			handleAs: "text",
			load : function(response, ioArgs) {
			    var creationList = dojo.byId('load_ajax_content_here');
			    creationList.innerHTML = response;

			    var searchSortByItem = dojo.byId('sortBy_relevance');
			    if ( searchSortByItem ) {
				dojo.style(searchSortByItem,{
					       display: 'inline'
					   });
			    }

			    var searchSortByLink = dojo.byId('sortBy_relevance_link');
			    dojo.query('li.sortBy_list_item a').forEach( function(link){
									     dojo.removeClass(link,'creation_browse_sortBy_current');
									 });
			    if ( searchSortByLink ) {
				dojo.addClass(searchSortByLink,'creation_browse_sortBy_current');
			    } else {
				dojo.addClass("sortBy_newest_link","creation_browse_sortBy_current");
			    }

			    dojo.query("a.load_ajax").forEach(function(link) {
								  dojo.connect(link, "onclick", Z2h.link.loadAjax);
							      });
			    //Z2h.tags.updateSortByLinks(searchString);

			    return response; //always return the response back
			},
			// if any error occurs, it goes here:
			error : function(response, ioArgs) {
			    //error!
			    return response; //always return the response back
			}
		    });
    },

    openVotingWidget: function(node){
	var widgetDiv = dojo.byId( node.id.replace("Link","Widget") );

	var animateProperties = null;

	if ( dojo.hasClass(node,'widget_open') ){
	    dojo.removeClass(node,'widget_open');
	    dojo.addClass(node,'widget_closed');

	    dojo.animateProperty({
				     node: widgetDiv,
				     widget: widgetDiv,
				     properties: { height: { start: 108, end: 0, units:"px"} },
				     easing: dojo.fx.easing.quadInOut,
				     duration: 500,
				     onEnd: function(){
					 var flashWidget = dojo.byId( this.widget.id.replace("contestNomineeVote","flashVoting"));
					 dojo.style(flashWidget,'display','none');
				     }
				 }).play();

	} else {
	    dojo.removeClass(node,'widget_closed');
	    dojo.addClass(node,'widget_open');

	    dojo.animateProperty({
				     node: widgetDiv,
				     widget: widgetDiv,
				     properties: { height: { start: 0, end: 108, units:"px"} },
				     easing: dojo.fx.easing.quadInOut,
				     duration: 500,
				     onBegin: function(){
					 var flashWidget = dojo.byId( this.widget.id.replace("contestNomineeVote","flashVoting"));
					 dojo.style(flashWidget,'display','block');
				     }
				 }).play();
	}

    },

    toggleAnswer: function(node){
	var id = node.id.replace("faq_question_","");
	var question = dojo.byId("faq_answer_"+id);

	var display = dojo.style(question,'display');

	dojo.removeClass(node,'festival_faq_item_header_open');

	if ( display == 'none' ){
	    dojo.addClass(node,'festival_faq_item_header_open');
	    dojo.style(question,'display','block');
	} else {
	    dojo.style(question,'display','none');
	}
    },

    getCategoryNominees: function(node){
	var contestID = node.alt.replace("contest_","");
	var loadingDiv = dojo.byId("loading_nominees");
	var nomineeList = dojo.byId("list_of_nominees");

	dojo.style(loadingDiv,'display','block');
	dojo.style(nomineeList,'display','none');

	var catTitle = dojo.byId("current_category");
        dojo.forEach( node.getOptions(), function(childNode,index,list){
        		  if ( childNode.value == node.getValue() ){
        		      dojo.attr(catTitle,'innerHTML',childNode.label);
			  }
		      });

	dojo.xhrPost({
			 url: "/contest/festival/get-nominees/id/"+contestID+"/contest_category_id/"+escape(node.getValue()).replace("/","%2F")+"/format/json/",
			 handleAs: "text",
			 load: function(data,ioargs){
			     dojo.attr(nomineeList,'innerHTML',data);
			     dojo.style(loadingDiv,'display','none');
			     dojo.style(nomineeList,'display','block');
			     dojo.parser.parse();
			     dojo.behavior.apply();
			     return data;
			 },
			 error: function(response, ioargs) {
			     console.log("XHRPost Error: ", response)
			     dojo.style(loadingDiv,'display','none');
			     dojo.style(nomineeList,'display','block');
			     return response;
			 }
		     });
    },

    switchPastWinner: function(node){
	var contestId = node.getValue();
	dojo.xhrPost({
			 url: "/contest/festival/get-past-winners/contest_id/" + contestId,
			 handleAs: "text",
			 headers: {"X-Requested-With": "XMLHttpRequest"},
			 load: function(data,ioargs){
			     var contestWinners = dojo.byId("past_winners");
			     dojo.attr(contestWinners,'innerHTML',data);
			     dojo.parser.parse();
			     return data;
			 },
			 error: function(reponse, ioargs){

			 }
		     });
    }
};

Z2h.notificationArrow = {
    _current: null,

    notify: function(domNode){
	if ( this._current != null ){
	    this._current.destroy();
	}
	this._current = new Z2h.Notification({ pointTo: domNode });
    },

    destroy: function(){
	this._current.destroy();
    }
};


Z2h.quiz = {
    _running: false,

    init: function(){
	dojo.behavior.add({
			      ".QuizAnswerExpand": {
				  onclick: function(e){
				      e.preventDefault();
				      Z2h.quiz.toggleAnswer(e.target);
				  }
			      },
			      "#quiz_question_howto": {
				  onclick: function(e){
				      e.preventDefault();
				      Z2h.quiz.toggleHowTo(e.target);
				  }
			      },
			      ".survey_play_button": {
				  'onclick' : function(e){
				      e.preventDefault();
				      Z2h.quiz.showQuizDialog(e.target.href);
				  }
			      },
			      ".survey_results_button": {
				  'onclick' : function(e){
				      e.preventDefault();
				      Z2h.quiz.showResultsDialog(e.target.href);
				  }
			      },
			      "#quiz_form": {
				  'onsubmit' : function(e){
				      e.preventDefault();
				      Z2h.quiz.submitForm();
				  }
			      },
			      "#quiz_form_submit": {
				  'onclick' : function(e){
				      e.preventDefault();
				      Z2h.quiz.submitForm();
				  }
			      }
			  });
    },

    submitForm: function() {
	var quiz_form = dojo.byId("quiz_form");

	if (Z2h.quiz.isValid() && quiz_form) {
	    quiz_form.submit();
	}
    },

    isValid: function() {
	var errors = 0;
	var errorMsg = "";

	// validate topic.
	var topic = dojo.byId("quiz_topic");
	if (Z2h.string.trimAll(topic.value).length == 0) {
	    errors++;
	    errorMsg = "Question is required.";
	}

	// validate start date.
	var quiz_start_date = dojo.byId("quiz_start_date");
	if (quiz_start_date==null||quiz_start_date=="") {
	    errors++;

	    if (errorMsg != "") {
		errorMsg += "<br />";
	    }

	    errorMsg += "Start date is required.";
	}

	// validate points.
	var quiz_points = dojo.byId("points");
	if (!quiz_points.value.match(/[0-9]{2,3}/g)) {
	    errors++;

	    if (errorMsg != "") {
		errorMsg += "<br />";
	    }

	    errorMsg += "Points need to be a number between 10 and 999.";
	}

	// validate answers.
	var how_many_answers = 0;
	dojo.query('input.quiz_answer').forEach(function(answer){
						    if (Z2h.string.trimAll(answer.value).length > 0) {
							how_many_answers++;
						    }
						});

	if (how_many_answers < 2){
	    errors++;

	    if (errorMsg != "") {
		errorMsg += "<br />";
	    }

	    errorMsg += "Minimum of 2 answers are required for each question.";
	}

	// validate form.
	if(errors == 0){
	    return true;
	} else {
	    Z2h.tooltip.popupError(errorMsg);
	    return false;
	}
    },

    // show overlay form to sign up.
    showQuizDialog: function(url) {
	// only send an ajax request if nothing is running.
	if (Z2h.quiz._running === false) {
	    Z2h.quiz._running = true;

	    var overlay_wait = dojo.byId("quiz_please_wait");
	    var status_active = dojo.byId("quiz_play_go");

	    if (status_active && overlay_wait) {
		status_active.style.display = "none";
		overlay_wait.style.display = "";
	    }

	    dojo.xhrGet({
			    url: url+"/format/text",  //the relative URL
			    handleAs: "text",
			    //			 	sync: true,
			    // run this function if the request is successful
		            load : function(response, ioArgs) {
				if (status_active && overlay_wait) {
				    status_active.style.display = "";
				    overlay_wait.style.display = "none";
				}

				// close already opend signup form.
			 	var opened_quiz_form = dijit.byId('quiz_form_overlay');

			 	if (opened_quiz_form) {
			 	    opened_quiz_form.hide();
			 	    opened_quiz_form.destroy();
			 	}

			 	// initialize dialog.
				var quiz_form = new dijit.Dialog({id: "quiz_form_overlay"});
				dojo.style(quiz_form.titleBar, "display", "none");

				quiz_form.attr('content', response);
				quiz_form.show();

				// close over flag form.
				dojo.query(".overlay_quiz_close").forEach(function(node, i){
									      //node.style.display = "block";
									      var closeHandle = dojo.connect(node,
													     "onclick",
													     dojo.hitch(quiz_form,
													     		function(e){
													    		    e.preventDefault();
													    		    quiz_form.attr('content', '');
													    		    quiz_form.hide();
													    		    quiz_form.destroy();
													     		    dojo.disconnect(closeHandle);
													     		}));
									  });

				// overwrite the default esc key event.
				var escHandle = dojo.connect(quiz_form.domNode, "onkeypress", function(e){
								 var key = e.keyCode || e.charCode;
								 var k = dojo.keys;

								 if (key == k.ESCAPE) {
								     e.preventDefault();
								     quiz_form.attr('content', '');
						    		     quiz_form.hide();
						    		     quiz_form.destroy();
						     		     dojo.disconnect(escHandle);
								 }
							     });

				// create a submit button to send the flag form.
				var submitButton = dojo.byId('quiz_submit_btn');
				if (submitButton) {
				    dojo.connect(submitButton,
						 "onclick",
						 function(e){
						     e.preventDefault();
						     Z2h.quiz.answer();
				    		 });
				}

				var quiz_post_form = dojo.byId('quiz_play_form');
				if (quiz_post_form) {
				    dojo.connect(quiz_post_form,
						 "onsubmit",
						 function(e){
						     e.preventDefault();
						     Z2h.quiz.answer();
				    		 });
				}

				dojo.query("a.quiz_play_option").forEach(function(obj) {
									     dojo.connect(obj, "onclick", function(evt) {
											      evt.preventDefault();

											      var selected_option = dojo.byId("quiz_selected_option");
											      var previous_option = 0;

											      if (selected_option) {
												  previous_option = selected_option.value;
												  selected_option.value = obj.id;
											      }

											      var previous_parent_li = dojo.byId("answer_"+previous_option+"_li");
											      var previous_parent_selected_li = dojo.byId("answer_"+previous_option+"_li_selected");
											      if (previous_parent_li && previous_parent_selected_li) {
												  dojo.style(previous_parent_li,'display','');
												  dojo.style(previous_parent_selected_li,'display','none');
											      }

											      var parent_li = dojo.byId("answer_"+obj.id+"_li");
											      var parent_selected_li = dojo.byId("answer_"+obj.id+"_li_selected");
											      if (parent_li && parent_selected_li) {
												  dojo.style(parent_li,'display','none');
												  dojo.style(parent_selected_li,'display','');
											      }
											  });
									 });

				return response; //always return the response back
		            },
		            // run this function if the request is not successful
		            error : function(response, ioArgs) {
				console.log("failed xhrGet", response, ioArgs);

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

				/* handle the error... */
				return response; //always return the response back
		            }
			});

	    Z2h.quiz._running = false;
	}
    },

    // show overlay form to sign up.
    showResultsDialog: function(url) {
	// only send an ajax request if nothing is running.
	if (Z2h.quiz._running === false) {
	    Z2h.quiz._running = true;

	    var overlay_wait = dojo.byId("quiz_please_wait");
	    var status_active = dojo.byId("quiz_result_go");

	    if (status_active && overlay_wait) {
		status_active.style.display = "none";
		overlay_wait.style.display = "";
	    }

	    dojo.xhrGet({
			    url: url+"/format/text",  //the relative URL
			    handleAs: "text",
			    //			 	sync: true,
			    // run this function if the request is successful
		            load : function(response, ioArgs) {
				if (status_active && overlay_wait) {
				    status_active.style.display = "";
				    overlay_wait.style.display = "none";
				}

				// close already opend signup form.
			 	var opened_quiz_form = dijit.byId('quiz_form_overlay');

			 	if (opened_quiz_form) {
			 	    opened_quiz_form.hide();
			 	    opened_quiz_form.destroy();
			 	}

			 	// initialize dialog.
				var quiz_form = new dijit.Dialog({id: "quiz_form_overlay"});
				dojo.style(quiz_form.titleBar, "display", "none");

				quiz_form.attr('content', response);
				quiz_form.show();

				// close over flag form.
				dojo.query(".overlay_quiz_close").forEach(function(node, i){
									      //node.style.display = "block";
									      var closeHandle = dojo.connect(node,
													     "onclick",
													     dojo.hitch(quiz_form,
													     		function(e){
													    		    e.preventDefault();
													    		    quiz_form.attr('content', '');
													    		    quiz_form.hide();
													    		    quiz_form.destroy();
													     		    dojo.disconnect(closeHandle);
													     		}));
									  });

				// overwrite the default esc key event.
				var escHandle = dojo.connect(quiz_form.domNode, "onkeypress", function(e){
								 var key = e.keyCode || e.charCode;
								 var k = dojo.keys;

								 if (key == k.ESCAPE) {
								     e.preventDefault();
								     quiz_form.attr('content', '');
						    		     quiz_form.hide();
						    		     quiz_form.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
		            }
			});

	    Z2h.quiz._running = false;
	}
    },

    answer: function() {
	// only send an ajax request if nothing is running.
	if (Z2h.quiz._running === false) {
	    Z2h.quiz._running = true;

	    var status_active = dojo.byId("quiz_play_answers");
	    var active_btn = dojo.byId("quiz_buttons");
	    var overlay_wait = dojo.byId("quiz_play_please_wait");
	    var form = dojo.byId("quiz_play_form");
	    var selected_option = dojo.byId("quiz_selected_option");

	    if (form && selected_option) {
		// validate the form.
		if (selected_option.value==null||selected_option.value==""||selected_option.value=="0") {
		    Z2h.tooltip.popupError("Please choose your answer first!");
		} else {
		    if (status_active && active_btn && overlay_wait) {
			status_active.style.display = "none";
			active_btn.style.display = "none";
			overlay_wait.style.display = "";
		    }

		    dojo.xhrPost({
				     url: form.action + "/format/json",
				     form: "quiz_play_form",
				     handleAs: "json",
				     //						sync: true,
				     headers: {"X-Requested-With": "XMLHttpRequest"},
				     load: function(data,ioargs){
					 if(data.result == "1"){
					     var quiz_result_go = dojo.byId("quiz_result_go");
					     var quiz_play_go = dojo.byId("quiz_play_go");

					     if (quiz_result_go && quiz_play_go) {
						 quiz_result_go.style.display = "";
						 quiz_play_go.style.display = "none";
					     }

					     if (data.pointsMesg != null) {
						 Z2h.tooltip.popups(data.pointsMesg,'points');
						 Z2h.user.updateCapital();
					     }

					     // get results.
					     dojo.xhrGet({
							     url: data.url+"/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_quiz_form = dijit.byId('quiz_form_overlay');
								 opened_quiz_form.attr('content', response);

								 // close over flag form.
								 dojo.query(".overlay_quiz_close").forEach(function(node, i){
													       //node.style.display = "block";
													       var closeHandle = dojo.connect(node,
																	      "onclick",
																	      dojo.hitch(opened_quiz_form,
																		     	 function(e){
																		    	     e.preventDefault();
																		    	     opened_quiz_form.attr('content', '');
																		    	     opened_quiz_form.hide();
																		    	     opened_quiz_form.destroy();
																		     	     dojo.disconnect(closeHandle);
																		     	 }));
													   });

							     },
							     // run this function if the request is not successful
							     error : function(response, ioArgs) {
							         console.log("failed xhrGet", response, ioArgs);

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

							         /* handle the error... */
							         return response; //always return the response back
							     }
							 });
					 } else {
					     if (status_active && active_btn && overlay_wait) {
						 status_active.style.display = "";
						 active_btn.style.display = "none";
						 overlay_wait.style.display = "none";
					     }

					     status_active.innerHTML = data.errorMsg;
					     status_active.style.width = "392px";
					     status_active.style.height = "150px";
					     status_active.style.textAlign = "center";
					 }

					 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.quiz._running = false;
	}
    },

    toggleAnswer: function(node){
	var id = node.id.replace("quiz_question_","");
	var question = dojo.byId("quiz_answer_"+id);

	var display = dojo.style(question,'display');

	if ( display == 'none' ){
	    dojo.style(question,'display','block');
	} else {
	    dojo.style(question,'display','none');
	}
    },

    toggleHowTo: function(node){
	var howto_answer = dojo.byId("quiz_question_howto_answer");

	if (howto_answer) {
	    var display = dojo.style(howto_answer,'display');

	    if ( display == 'none' ){
		node.innerHTML = "Hide How-To";
		dojo.style(howto_answer,'display','block');
	    } else {
		node.innerHTML = "Show How-To";
		dojo.style(howto_answer,'display','none');
	    }
	}
    }
};

//---------------------- PAGE ONLOND -------------------------
dojo.addOnLoad(function() {
		   Z2h.global.init();

		   dojo.behavior.apply();

		   var editor_iframe = dojo.byId("dojo_editor_textarea_iframe");

		   if (editor_iframe) {
		       editor_iframe.style.width = "479px";
		       editor_iframe.style.padding = "0";
		   }

		   var sidebar = dojo.byId("side_banner");

		   if (sidebar) {
		       var browserWidth = document.documentElement.clientWidth;

		       // show/hide sidebar on load (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";
					}
				    });
		   }
	       });
