/*
* XOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOX
*
* SCRIPT: notcraft.js
*
* NOTICE: (c)opyright 2012 by Notcraft.com and Zeras
*
* XOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOX
*/

/*
* XOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOX
*
* variable initialisation
*
* XOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOX
*/

	var	effectSpeed = 'fast';
	var	rightNow = new Date();
	var	jan1 = new Date(rightNow.getFullYear(), 0, 1, 0, 0, 0, 0);
	var	temp = jan1.toGMTString();
	var	jan2 = new Date(temp.substring(0, temp.lastIndexOf(" ")-1));
	var	std_time_offset = (jan1 - jan2) / (1000 * 60 * 60);
	var	july1 = new Date(rightNow.getFullYear(), 6, 1, 0, 0, 0, 0);
	temp = july1.toGMTString();
	var	july2 = new Date(temp.substring(0, temp.lastIndexOf(" ")-1));
	var	daylight_time_offset = (july1 - july2) / (1000 * 60 * 60);
	var	dst = '0';
	if (std_time_offset != daylight_time_offset) {
		dst = "1";
	}
//	alert('(' + dst + ')');


/*
* XOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOX
*
* jquery extensions
*
* XOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOX
*/


jQuery.fn.disableTextSelection = function() {
	return this.each(function() {
		if (typeof this.onselectstart != "undefined") {  // IE
			this.onselectstart = function() { return false; };
		} else if (typeof this.style.MozUserSelect != "undefined") {  // Firefox
			this.style.MozUserSelect = "none";
		} else {  // All others
			this.onmousedown = function() { return false; };
			this.style.cursor = "default";
		}
	});
};


//
// example:  $.cookie('the_cookie', 'the_value', { expires: 7, path: '/', domain: 'jquery.com', secure: true });
//

jQuery.cookie = function(name, value, options) {
				if (typeof value != 'undefined') { // name and value given, set cookie
					options = options || {};
					if (value === null) {
						value = '';
						options.expires = -1;
					}
					var	expires = '';
					if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
						var	date;
						if (typeof options.expires == 'number') {
							date = new Date();
							date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
						} else {
							date = options.expires;
						}
						expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
					}
					// CAUTION: Needed to parenthesize options.path and options.domain
					// in the following expressions, otherwise they evaluate to undefined
					// in the packed version for some reason...
					var	path = options.path ? '; path=' + (options.path) : '';
					var	domain = options.domain ? '; domain=' + (options.domain) : '';
					var	secure = options.secure ? '; secure' : '';
					document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
				} else { // only name given, get cookie
					var	cookieValue = null;
					if (document.cookie && document.cookie != '') {
						var	cookies = document.cookie.split(';');
						for (var	i = 0; i < cookies.length; i++) {
							var	cookie = jQuery.trim(cookies[i]);
							// Does this cookie string begin with the name we want?
							if (cookie.substring(0, name.length + 1) == (name + '=')) {
								cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
								break;
							}
						}
					}
					return cookieValue;
				}
			};


	(function($) {
		jQuery.fn.putCursorAtEnd = function() {
 			return this.each(function() {
				$(this).focus()
				// If this function exists...
				if (this.setSelectionRange) {
					// ... then use it
					// (Doesn't work in IE)
					// Double the length because Opera is inconsistent about whether a carriage return is one character or two. Sigh.
					var	len = $(this).val().length * 2;
					this.setSelectionRange(len, len);
				} else {
					// ... otherwise replace the contents with itself
					// (Doesn't work in Google Chrome)
					$(this).val($(this).val());
				}
				// Scroll to the bottom, in case we're in a tall textarea
				// (Necessary for Firefox and Google Chrome)
				this.scrollTop = 999999;
			});
		};
	})(jQuery);

	jQuery.fn.zCenter = function() {
						return this.each(function() {
							var	t = jQuery(this);
							if ((t.width()) && (t.height())) {
								var	changeflag = false;
								if ($(window).width() > t.width()) {
									t.css('left',($(window).width()-t.width())/2);
									t.css('right',($(window).width()-t.width())/2);
								} else {
									t.css('left','auto');
									t.css('right','auto');
								}
								if ($(window).height() > t.height()) {
									t.css('top',($(window).height()-t.height())/2);
									changeflag = true;
								}
								if (changeflag) {
									t.css('position','fixed');
								} else {
									t.css('position','static');
								}
							}
						});
					};





	(function($,sr) {
			// debouncing function from John Hann
			// http://unscriptable.com/index.php/2009/03/20/debouncing-javascript-methods/
			var	debounce = function (func, threshold, execAsap) {
			var	timeout;
 
			return function debounced () {
			var	obj = this, args = arguments;
			function delayed () {
			    if (!execAsap)
			        func.apply(obj, args);
			    timeout = null; 
			};
 
			if (timeout)
			    clearTimeout(timeout);
			else if (execAsap)
			    func.apply(obj, args);
 
			timeout = setTimeout(delayed, threshold || 100); 
		};
	  }

	jQuery.fn[sr] =			function(fn) {
								return fn ? this.bind('resize', debounce(fn)) : this.trigger(sr);
							};
							})(jQuery,'z_resize');
 
	jQuery.fn.delay =			function(time,func) {
								this.each(function() {
									setTimeout(func,time);
								});
								return this;
							};

	jQuery.fn.z_centerWindow =	function() {
								return this.each(function() {
									var	t = jQuery(this);
									if ((t.width()) && (t.height())) {
										var	changeflag = false;
										if ($(window).width() > t.width()) {
											t.css('left',($(window).width()-t.width())/2);
											t.css('right',($(window).width()-t.width())/2);
										}
										if ($(window).height() > t.height()) {
											t.css('top',($(window).height()-t.height())/2);
											t.css('bottom',($(window).height()-t.height())/2);
											changeflag = true;
										}
										if (changeflag) {
											if (t.css('position') != 'fixed') {
											}
											t.css('position','fixed');
										}
									}
								});
							};

/*
* XOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOX
*
* 
*
* XOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOX
*/

	var	z_page_alert_active = 0;
	var	z_interval_pageCheckAlerts = 0;
	var	z_start_time = z_timeStamp();
	var	z_ajax_timestamp = z_timeStamp();
	var	z_pageflag_timestamp_mail = 0;
	var	z_pageflag_timestamp_alert = 0;
	var	z_site_energy_refresh = 0;

	function	z_user_update_energy_recovery() {
				var	z_time_age_in_seconds = Math.floor((z_timeStamp() - z_start_time) / 1000);
				z_user_energy_progress = Math.floor(((z_time_age_in_seconds + z_user_energy_recovery_time_passed) / z_user_energy_recovery_period) * 100);
				z_user_energy_progress = (z_user_energy_progress > 100) ? 100 : z_user_energy_progress;
//				z_user_energy_progress = (z_user_energy_progress < 10) ? 10 : z_user_energy_progress;
//alert('(' + z_time_age_in_seconds + ')');
//alert('(' + z_user_energy_progress + ')');
				$('#page_profile_energy_recovering .page-profile-progress').attr('title',z_user_energy_progress + '%');
				if (z_user_energy_progress >= 10) {
					$('#page_profile_energy_recovering .page-profile-progress-bar').css('width',z_user_energy_progress + '%');
					if (z_user_energy_progress >= 100) {
						clearInterval(z_site_energy_refresh);
						$('#page_profile_energy_recovering').hide();
						$('#page_profile_energy').show();
//alert('Full Energy!');
					}
				}
			}

	function	z_showAtCursor(id,event) {
				var	object_width = $('#' + id).width();
				var	object_height = $('#' + id).height();
				var	z_mouse_x = event.pageX + 25;
				var	z_mouse_y = event.pageY + 25;
				if ((z_mouse_x + object_width) > $(window).width()) {
					if ((z_mouse_x - object_width) >= 0) {
						z_mouse_x = z_mouse_x - object_width;
					}
				}
				if ((z_mouse_y + object_height) > ($(window).height() + $(window).scrollTop())) {
					if ((z_mouse_y - object_height) >= 0) {
						z_mouse_y = z_mouse_y - object_height;
					}
				}
				$('#' + id).css('position','fixed');
				if ($('#' + id).is(':hidden')) {
					$('#' + id).show();
				}
				$('#' + id).offset({ top: z_mouse_y, left: z_mouse_x });
			}

	function	z_isAlphaKey(e) {
				var	k;
				document.all ? k = e.keyCode : k = e.which;
				return ((k > 64 && k < 91) || (k > 96 && k < 123) || (k >= 48 && k <= 57) || k == 8);
			}

	function	z_isLetterKey(e) {
				var	k;
				document.all ? k = e.keyCode : k = e.which;
				return ((k > 64 && k < 91) || (k > 96 && k < 123) || k == 8);
			}

	function	z_extractAlphaChars(str) {
				return str.replace(/[^A-Za-z0-9]/gi,"");
			}

	function	z_upperCaseFieldValue(id) {
				id.value = id.value.toUpperCase();
			}

	function	z_upperCaseFirstLetter(str) {
				if (str.length > 0) {
					return(str.substr(0,1).toUpperCase() + str.substr(1));
				}
			}

	function	z_ucFirst(str) {
				return(str.substr(0,1).toUpperCase() + str.substr(1).toLowerCase());
			}

	function	z_browserMobileSafari() {
				if (z_iPod()) {
					return(1);
				}
				if (z_iPad()) {
					return(1);
				}
			}

	function	z_iPod() {
				if (navigator.platform.indexOf("iPhone") != -1) {
					return(1);
				}
				if (navigator.platform.indexOf("iPod") != -1) {
					return(1);
				}
			}

	function	z_iPad() {
				if (navigator.platform.indexOf("iPad") != -1) {
					return(1);
				}
			}

	function	z_goAnchor(anchorStr) {
				if (anchorStr.length > 0) {
					location.href = '#' + anchorStr;
				}
			}

	function	z_timeStamp() {
				var	date = new Date;
				return(date.getTime());
			}

	function	z_updateClientTime() {
				var	newdate = new Date();
				var	server_time = 0;
				var	time_offset = 0;
				if (($.cookie('server_time')) && ($.cookie('server_time').length > 0)) {
					server_time = $.cookie('server_time');
					client_time = Math.floor(newdate.getTime() / 1000);
					time_offset = client_time - server_time;
					$.cookie('client_timeoffset',time_offset,{ path: '/' });
				}
			}

	function	z_checkFormField(cmd,formfield,addstr,submitted,formfield2) {
				if ((cmd) && (formfield)) {
					var	formfieldid = '#form' + z_ucFirst(formfield);
					var	formRowBlockFieldId = '#form' + z_ucFirst(formfield) + 'FieldBody';
					var	formfieldstatus = formfieldid + "Status";
					var	formFieldStatusMessage = formfieldid + "StatusMessage";
					var	dataStr = 'cmd=' + cmd + '&field=' + $(formfieldid).val();
					if (addstr) {
						dataStr = dataStr + '&' + addstr;
					}
					if (submitted) {
						dataStr = dataStr + '&submitted=1';
					}
					if ((formfield2.length != 0) && (formfield2 != 'undefined')) {
						dataStr = dataStr + '&field2=' + $('#form' + z_ucFirst(formfield2)).val();
					}
					new $.ajax({
						type: 'post',
						url: '/ajax.x',
						data: dataStr,
						success: function(responseText) {
								if (responseText) {
									$(formFieldStatusMessage).empty();
									$(formFieldStatusMessage).html(responseText);
									$(formfieldstatus).show();
									$(formRowBlockFieldId).addClass('form-field-body-error');
								} else {
									$(formRowBlockFieldId).removeClass('form-field-body-error');
									$(formFieldStatusMessage).empty();
									$(formfieldstatus).hide();
								}
						}
					});
				}
			}

	function	z_local_resizepage() {
				var	z_page_height = 0;
				if ($('#container').height() < $(window).height()) {
					z_page_height = $('#pageTableBody').height() + ($(window).height() - $('#container').height());
					$('#pageTableBody').css('height',z_page_height + 'px');
				} else if ($('#container').height() > $(window).height()) {
					$('#pageTableBody').css('height','auto');
				}
			}

	function	z_pageCheckClearIntervals() {
				if ((z_start_time + z_idle_timeout) < z_timeStamp()) {
					clearInterval(z_interval_pageCheckAlerts);
//__SAVE_THIS					$("#pageDimmer").fadeIn();
//__SAVE_THIS					$('#pageTimeout').zCenter();
//__SAVE_THIS					$('#pageTimeout').show();
					return 1;
				}
			}

	function	z_pageAlertShow() {
				if ($('#page_alert').is(':hidden')) {
					if (!z_page_alert_active) {
						z_page_alert_active = 1;
						$('#page_alert').slideDown('400', function() {
							$('#page_alert').show();
						});
					}
				}
			}

	function	z_pageAlertHide() {
				z_page_alert_active = 0;
				$('#page_alert').slideUp('400', function() {
					$('#page_alert').hide();
				});
			}




	function	z_pageAlertUpdate() {
				if (z_pageCheckClearIntervals()) {
					return false;
				}
				$.get('/ajax.x?cmd=user_alert_check&token=' + z_user_token, function(responseText) {
					if (responseText.length > 0) {
						$('#page_alert').html(responseText);
						z_pageAlertShow();
					} else {
						if (z_page_alert_active) {
							z_pageAlertHide();
						}
					}
				});
			}

	function	z_pageCheckFlags() {
				if (z_pageCheckClearIntervals()) {
					return false;
				}
				$.post('/ajaxflag.x',{ cmd: 'pageflags', siteid: z_site_id, userid: z_user_id, token: z_user_token }, function(responseText) {
					if (responseText.length > 0) {
						var	z_data = responseText.split('|');
						var	z_data_slot = 0;
						for (z_data_slot in z_data) {
							pageflagStr = z_data[z_data_slot];
							var	z_flag_data = responseText.split(':');
							var	z_flag_code = z_flag_data[0];
							var	z_flag_timestamp = z_flag_data[1];
							var	z_flag_value = z_flag_data[2];
//							if (z_flag_code == 'chatroom_' + z_user_chatroom) {
//							}
//							if (z_flag_code == 'alert') {
//							}
							if ((z_flag_code == 'alert') && (z_flag_timestamp > z_pageflag_timestamp_alert)) {
								z_pageAlertUpdate();
								z_pageflag_timestamp_alert = z_flag_timestamp;
							}
						}
					}
				});
				if ((z_timeStamp() - z_ajax_timestamp) > 20) {
					if (!z_profile_userid) {
//						z_pageProgressUpdate();
					}
					z_ajax_timestamp = z_timeStamp();
				}
			}


	function	z_pageHelpShow() {
				$("#pageDimmer").fadeIn('400',function() {
					$('#pageHelp').zCenter();
					$('#pageHelp').fadeIn(400);
				});
				$(document).keyup(function(e) {
					  if ((e.keyCode == 13) || (e.keyCode == 27)) {
						  z_pageHelpHide();
					  }
				});
				$(window).resize(function(e) {
					$('#pageHelp').zCenter();
				});
			}

	function	z_pageHelpHide() {
				$(document).unbind('keyup');
				$(window).unbind('resize');
				$('#pageHelp').hide();
				$("#pageDimmer").fadeOut();
			}


	function	z_pageDimmerReset() {
// *** create dimmer block
				var z_dimmer_height = $(document).height();
				if ($(window).height() > z_dimmer_height) {
					z_dimmer_height = $(window).height();
				}
				$('#pageDimmer').css('height',z_dimmer_height);
//__fix				$('#pageBody').css('height',z_dimmer_height - ($('#pageHeader').height() + $('#pageFooter').height()));
			}


	function	z_pageFooterReset() {
				var	z_footer_top = 0;
//				$('#pageFooter').offset({ top: 'auto', left: 0 });
				z_footer_top = $('#pageFooterMarker').offset().top;
				$('#pageFooter').offset({ top: z_footer_top, left: 0 });
				if ($('#pageFooter').offset().top < ($(window).height() - $('#pageFooter').height())) {
					z_footer_top = $(window).height() - $('#pageFooter').height();
					$('#pageFooter').offset({ top: z_footer_top, left: 0 });
				}
			}

	function	z_page_timeout_reset() {
				z_start_time = z_timeStamp();
			}

/*
* XOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOX
*
* notcraft chat
*
* XOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOX
*/


	var	z_chat_first = 1;
	var	z_chatroom_lastid = 0;
	var	z_chat_timestamp = z_timeStamp();
	var	z_chat_lastupdate = 0;
	var	z_chat_lastinput = 0;
	var	z_chat_timedout = 0;
	var	z_chat_lastcachetimestamp = 0;
	var	z_chat_lasttimestamp = 0;
	var	z_chat_lastUsers = "";
	var	z_chat_lastMessages = "";
	var	z_chat_refresh = 0;
	var	z_chat_save_page_height = 0;
	var	z_chat_save_height = 0;
	var	z_chat_save_width = 0;
	var	z_chat_save_top = 0;
	var	z_chat_save_left = 0;
	var	z_chat_window_top = 0;
	var	z_chat_window_left = 0;
	var	z_chat_full_mode = 0;
	var	z_chat_hide_users = 0;
	var	z_chat_timeout = 0;
	var	z_height = 0;
	var	z_chat_disabled = 0;
	var	z_chat_refresh_rate = 5;

	var	zChat = {

		init:			function(e) {
							$.ajaxSetup({
								cache: false
							});
							z_chat_save_width = $('#page_chatroom').width();;
							$('#page_chatroom').css('width',z_chat_save_width + 'px');
							z_chat_window_top = $('#page_chatroom').position().top;
							z_chat_window_left = $('#page_chatroom').position().left;
							$(window).resize(function(e) {
								if (z_chat_full_mode) {
									zChat.setFullMode();
								}
							});

							$('#page_chatroom').disableTextSelection();

//future							window.onbeforeunload = function() {
//future								$.ajax({
//future									type: "GET",
//future									url: "/ajaxchat.x",
//future									cache: false,
//future									async: false,
//future									data: "cmd=chatroom_leave",
//future									success: function(responseText) {
//future											}
//future								}); 
//future							}

//future							$('#page_chatroom_FormMessage').live('mousedown',function(e) {
//future								if ($('#page_chatroom_FormMessage').val() == z_chatroom_lang_input_message) {
//future									$('#page_chatroom_FormMessage').val('');
//future								}
//future							});
//future							$('#page_chatroom_FormMessage').live('blur',function(e) {
//future								if (!$('#page_chatroom_FormMessage').val()) {
//future									$('#page_chatroom_FormMessage').val(z_chatroom_lang_input_message);
//future								}
//future							});

							$('[id^=chat_message_user_]').live('click',function(e) {
								$('#page_chatroom_FormMessage').val('/tell ' + $(this).text() + ' ');
								$('#page_chatroom_FormMessage').focus();
							});

							$(window).resize(function(e) {
								$('#page_chatroom').css('width','100%');
							});


							$('#page_chatroom_button_normalmode').live('click',function(e) {
								zChat.setNormalMode();
								return false;
							});
							$('#page_chatroom_button_fullmode').live('click',function(e) {
								zChat.setFullMode();
								return false;
							});
//future							$('#page_chatroom_ButtonReload').live('click',function(e) {
//future								window.location.href = window.location.href;
//future								return false;
//future							});
//future							$('#page_chatroom_ButtonHideUsers').live('click',function(e) {
//future								zChat.setHideUsers();
//future								return false;
//future							});
//future							$('#page_chatroom_ButtonShowUsers').live('click',function(e) {
//future								zChat.setShowUsers();
//future								return false;
//future							});
//future							$('#page_chatroom_BodyDivider').show();
//future							$('#page_chatroom_BodyUsers').show();

							$('#page_chatroom_FormMessage').attr('autocomplete','off');

							zChat.enableChat();
							zChat.resetUpdate();
							zChat.updateWindow();
//							zChat.updateWindow(1);
						},

		enableChat:		function(e) {
							$('#page_chat_inner').die('click');
							$('.page-chat-footer-disabled').fadeOut('slow',function(e) {
								$('.page-chat-header-buttons').fadeIn('slow');
								$('.page-chat-footer').fadeIn('slow',function() {
									$('#page_chatroom_FormMessage').focus();
								});
							});
							$('#page_chat_inner').css('cursor','auto');
							$('#page_chatroom_FormMessage').removeAttr('disabled');
							$('#page_chatroom_disabled_message').hide();
							$('#page_chatroom_button_increase').live('click',function(e) {
								e.preventDefault();
								z_chatroom_height = z_chatroom_height + 20;
								if (z_chatroom_height > z_chat_maxheight) {
									z_chatroom_height = z_chat_maxheight;
								}
								$.cookie('chatroom_height',z_chatroom_height,{ expires: 30, domain: z_site_cookie_domain, path: '/' });
								$('#page_chatroom_messages').css('height',z_chatroom_height + 'px');
//__needed?								$("#page_chatroom_messages").attr({ scrollTop: $("#page_chatroom_messages").attr("scrollHeight") });
								$('#windowConsoleBodyTableCellLeftBody').css('height',($('#windowConsoleBodyTableCellCenterBody').height() - 5) + 'px');
								$('#windowConsoleBodyTableCellRightBody').css('height',($('#windowConsoleBodyTableCellCenterBody').height() - 5) + 'px');
								$('#page_chatroom_FormMessage').focus();
							});
							$('#page_chatroom_button_decrease').live('click',function(e) {
								e.preventDefault();
								z_chatroom_height = z_chatroom_height - 20;
								if (z_chatroom_height < z_chat_minheight) {
									z_chatroom_height = z_chat_minheight;
								}
								$.cookie('chatroom_height',z_chatroom_height,{ expires: 30, domain: z_site_cookie_domain, path: '/' });
								$('#page_chatroom_messages').css('height',z_chatroom_height + 'px');
								$('#windowConsoleBodyTableCellLeftBody').css('height',($('#windowConsoleBodyTableCellCenterBody').height() - 5) + 'px');
								$('#windowConsoleBodyTableCellRightBody').css('height',($('#windowConsoleBodyTableCellCenterBody').height() - 5) + 'px');
//								$(body).css('margin-bottom',$('#windowConsole').height() + 'px');
//								$("#page_chatroom_messages").attr({ scrollTop: $("#page_chatroom_messages").attr("scrollHeight") });
								zChat.resetUpdate();
								zChat.updateWindow();
								$('#page_chatroom_FormMessage').focus();
							});

							$('#page_chatroom_Form').live('submit',function(e) {
								e.preventDefault();
								if ($('#page_chatroom_FormMessage').val()) {
									zChat.addMessage();
								}
							});
							zChat.enableChatUpdate();
							zChat.timeoutReset();
							zChat.resetUpdate();
							$('#page_chatroom_FormMessage').focus();
//							zChat.updateWindow();
							z_chat_disabled = 0;
						},

		enableChatUpdate:	function(e) {
							if (!z_chat_refresh) {
								z_chat_refresh = setInterval('zChat.checkStatus()',z_chat_refresh_rate * 1000);
							}
						},

		disableChat:		function(e) {
							zChat.disableChatUpdate();
//future									zChat.setHideUsers();
//									$('#page_chatroom_Header').hide();
							$('#page_chatroom_Form').die('submit');
							$('#page_chatroom_button_increase').die('click');
							$('#page_chatroom_button_decrease').die('click');
							$('#page_chatroom_FormMessage').attr('disabled','disabled');
							$('#page_chatroom_Form').live('submit',function(e) {
								e.preventDefault();
								return false;
							});
							$('#page_chat_inner').live('click',function(e) {
								zChat.joinChat();
								zChat.enableChat();
							});
							zChat.showDisabled();
						},

		disableChatUpdate:	function(e) {
//alert('clearInterval');
							clearInterval(z_chat_refresh);
							z_chat_refresh = 0;
						},

		checkStatus:		function(e) {
//							if ((forceflag) || ((z_chat_timestamp + (z_chat_refresh_rate * 1000)) <= z_timeStamp())) {
								if (zChat.timeoutCheck()) {
									new $.ajax({
										type: 'post',
										url: '/ajaxflag.x',
										data: 'cmd=chatroom_lastid&siteid=' + z_site_id + '&chatroom=' + z_user_chatroom + '&userid=' + z_user_id + '&token=' + z_user_token,
										success: function(responseText) {
//alert('AJAX: chatroom_lastid(' + responseText + ')');
//alert('(' + responseText + ')');
												var	z_retval = parseInt(responseText);
//alert('retval(' + z_retval + ')(' + z_chatroom_lastid + ')');
												if (z_retval > z_chatroom_lastid) {
//alert('updateWindow()');
//													zChat.resetUpdate();
													zChat.updateWindow();
//													z_chatroom_lastid = z_retval;
												}
//alert('(' + responseText + ')');
											}
									});
								}
//							}
						},

		leaveChat:		function(e) {
							z_chat_timedout = 1;
							new $.ajax({
								type: 'post',
								url: '/ajaxchat.x',
								data: 'cmd=chatroom_leave&token=' + z_user_token,
								success: function(responseText) {
											if (responseText.length > 0) {
//alert('responseText(' + responseText + ')');
												var num = parseInt(responseText);
//__save_2012.01.09												zChat.updateWindow();
											}
										}
							});
							zChat.disableChatUpdate();
//__save_2012.01.09							$('#page_chatroom_Form').die('submit');
//__save_2012.01.09							$('#page_chatroom_Form').live('submit',function(e) {
//__save_2012.01.09								e.preventDefault();
//__save_2012.01.09								return false;
//__save_2012.01.09							});
						},

		joinChat:			function(e) {
							z_chat_timedout = 0;
							new $.ajax({
								type: 'post',
								url: '/ajaxchat.x',
								data: 'cmd=chatroom_join&chatroom=' + z_user_chatroom + '&token=' + z_user_token,
								success: function(responseText) {
											if (responseText.length > 0) {
//alert('responseText(' + responseText + ')');
												var num = parseInt(responseText);
												zChat.updateWindow();
											}
										}
							});
							zChat.enableChatUpdate();
						},
/* moved to server-side .. 20110717
*/

		timeoutReset:		function(e) {
							if (!z_chat_timeout) {
								zChat.joinChat();
							}
							z_chat_timeout = z_timeStamp() + (z_user_chatroom_timeout * 1000);
						},

		timeoutCheck:		function(e) {
							if (z_timeStamp() > z_chat_timeout) {
								zChat.leaveChat();
								zChat.disableChat();
//alert('timeout!');
							} else {
								return(1);
							}
						},

		slashWho:			function(e) {
							var responseText = '';
							$.get('/ajaxchat.x?cmd=chat_slash_who&chatroomid=' + $('#page_chatroom_Room').val() + '&token=' + z_user_token, function(responseText) {
//alert(responseText);
								if (responseText.length > 0) {
									$('#page_chatroom_messages').append(responseText);
									$('#page_chatroom_messages').attr({ scrollTop: $('#page_chatroom_messages').attr('scrollHeight') });
								}
							});
						},

//		scrollMessages:	function(e) {
//							$('#page_chatroom_messages').attr({ scrollTop: $('#page_chatroom_messages').attr('scrollHeight') });
//						},

		addMessage:		function(e) {
							if ($('#page_chatroom_FormMessage').val()) {
								zChat.disableChatUpdate();
								if ((z_timeStamp() - z_chat_lastinput) > 500) {
									z_chat_lastinput = z_timeStamp();
//alert('(data: cmd=chat_post&chatroom=' + $('#page_chatroom_Room').val() + '&message=' + $('#page_chatroom_FormMessage').val() + ')');
									new $.ajax({
										type: 'post',
										url: '/ajaxchat.x',
										data: 'cmd=chatroom_message_add&message=' + $('#page_chatroom_FormMessage').val() + '&token=' + z_user_token,
										success: function(responseText) {
													if (responseText.length > 0) {
//alert('responseText(' + responseText + ')');
														var num = parseInt(responseText);
														if (num == 10) {
															zChat.slashWho();
														} else {
															zChat.timeoutReset();
															z_chat_refresh_rate = z_chat_refresh_rate_active;
															zChat.enableChatUpdate();
															zChat.resetUpdate();
															zChat.updateWindow();
														}
													}
												}
									});
								}
								$('#page_chatroom_FormMessage').val('');
								$('#page_chatroom_FormMessage').focus();
							}
						},

//future		setHideUsers:		function(e) {
//future							z_chat_hide_users = 1;
//future							$('#page_chatroom_BodyUsers').hide();
//future							$('#page_chatroom_BodyDivider').hide();
//future							$('#page_chatroom_ButtonHideUsers').hide();
//future							$('#page_chatroom_ButtonShowUsers').show();
//future							$('#formMessage').focus();
//future						},

//future		setShowUsers:		function(e) {
//future							z_chat_hide_users = 0;
//future							$('#page_chatroom_BodyUsers').show();
//future							$('#page_chatroom_BodyDivider').show();
//future							$('#page_chatroom_ButtonShowUsers').hide();
//future							$('#page_chatroom_ButtonHideUsers').show();
//future							$('#formMessage').focus();
//future						},

		setNormalMode:		function(e) {
							if (z_chat_full_mode) {
								z_chat_full_mode = 0;
								$(document).unbind('keyup');
//								$('html').css('overflow','visible');
								$('html').css('overflow','auto');
								$('#page_chatroom').css('position','relative');
								$('#page_chatroom').css('top',z_chat_save_top);
								$('#page_chatroom').css('left',z_chat_save_left);
								$('#page_chatroom_messages').css('height',z_chat_save_height + 'px');
								$('#page_chatroom').css('width',z_chat_save_width + 'px');
								$('#page_chatroom_messages').css('vertical-align','bottom');
								$('#page_chatroom_button_normalmode').hide();
								$('#page_chatroom_button_fullmode').show();
//								$('#page_chatroom_messages').attr({ scrollTop: $('#page_chatroom_messages')[0].attr('scrollHeight') });
//								$('#page_chatroom_messages').attr({ scrollTop: $('#page_chatroom_messages')[0].scrollHeight });
								$('#page_chatroom_messages').scrollTop($('#page_chatroom_messages')[0].scrollHeight - $('#page_chatroom_messages').height());
								$('#page_chatroom_FormMessage').focus();
							}
						},

		setFullMode:		function(e) {
							z_chat_full_mode = 1;
							if (!z_chat_save_page_height) {
								z_chat_save_page_height = $('#page').height();
								z_chat_save_height = $('#page_chatroom_messages').height();
								z_chat_save_width = $('#page_chatroom').width();
								z_chat_save_top = $('#page_chatroom').css('top');
								z_chat_save_left = $('#page_chatroom').css('left');
							}
							$('#page_chatroom').css('position','fixed');
							$('#page_chatroom').css('top','0');
							$('#page_chatroom').css('left','0');
							z_height = ($(window).height() - $('#page_chatroom').height()) + $('#page_chatroom_messages').height();
							$('#page_chatroom_messages').css('height',z_height + 'px');
//$('html, body').animate({ scrollTop: 0 },'slow');
$('html, body').scrollTop(0,0);
$('#page_chatroom_messages').css('height',(z_height - 40) + 'px');
$('#page_chatroom').css('top','40px');
$('html').css('overflow','hidden');
							$('#page_chatroom').css('width','100%');
							$('#page_chatroom_messages').css('vertical-align','bottom');
							$('#page_chatroom_button_fullmode').hide();
							$('#page_chatroom_button_normalmode').show();
//							$('#page_chatroom_messages').attr({ scrollTop: $('#page_chatroom_messages')[0].scrollHeight });
							$(document).unbind('keyup');
							$(document).keyup(function(e) {
								  if (e.keyCode == 27) {
								  	zChat.setNormalMode();
								  }
							});
							$('#page_chatroom_FormMessage').focus();
						},

		showDisabled:		function(e) {
							$('.page-chat-footer-disabled').height($('.page-chat-footer').height());
							$('.page-chat-footer').fadeOut('slow',function(e) {
								$('.page-chat-footer-disabled').fadeIn('slow');
//								$('.page-chat-header-buttons').show().css({visibility: 'hidden'});
//								$('.page-chat-header-buttons').fadeOut('slow');
							});
							$('.page-chat-header-buttons').fadeOut('slow');
							$('#page_chat_inner').css('cursor','pointer');
							z_chat_disabled = 1;
						},

		showChat:			function(e) {
							if ($('#page_chatroom').is(':hidden')) {
								$('#page_chatroom').slideDown('400', function() {
									$('#page_chatroom').show();
								});
								$('#page_header_chatroom_show').hide();
								$('#page_header_chatroom_hide').show();
								$.get('/ajax.x?cmd=page_chatroom_show&token=' + z_user_token, function(responseText) {
									if (responseText.length > 0) {
									}
								});
								$('#page_chatroom_FormMessage').focus();
							}
						},

		hideChat:			function(e) {
							if ($('#page_chatroom').length != 0) {
								if (!$('#page_chatroom').is(':hidden')) {
									$('#page_chatroom').slideUp('400', function() {
										$('#page_chatroom').hide();
									});
										$('#page_header_chatroom_hide').hide();
								$('#page_header_chatroom_show').show();
									$.get('/ajax.x?cmd=page_chatroom_hide&token=' + z_user_token, function(responseText) {
										if (responseText.length > 0) {
										}
									});
								}
							}
						},

		resetUpdate:		function(e) {
							z_chat_lastupdate = 0;
						},

		updateWindow:		function(showall,e) {
							if ((showall) || ((z_chat_lastupdate + (z_chat_refresh_rate * 1000)) <= z_timeStamp())) {
								z_chat_lastupdate = z_timeStamp();
								var responseText = '';
								$.get('/ajaxchat.x?cmd=chatroom_show&lastid=' + z_chatroom_lastid + '&timedout=' + z_chat_timedout + '&token=' + z_user_token, function(responseText) {
									var	z_chatroom_data = responseText.split('_____BREAK_____');
									var	z_chatroom_messages = z_chatroom_data[3];
									z_chatroom_lastid = parseInt(z_chatroom_data[0]);
									$('.page-chat-messages').css('position','static');
									$("#page_chatroom_messages").append(z_chatroom_messages);
									if (showall) {
										$('#page_chatroom_messages').hide();
//										$('#page_chatroom_messages').fadeIn(200).scrollTop($('#page_chatroom_messages')[0].scrollHeight - $('#page_chatroom_messages').height());
										$('#page_chatroom_messages').scrollTop($('#page_chatroom_messages')[0].scrollHeight - $('#page_chatroom_messages').height(),function() {
											$('#page_chatroom_messages').fadeIn(200);
										});
										z_chat_first = 0;
									} else {
										if (z_chat_first) {
//											$('.page-chat-messages').hide();
											$('#page_chatroom_messages').scrollTop($('#page_chatroom_messages')[0].scrollHeight - $('#page_chatroom_messages').height());
//											$('.page-chat-messages').fadeIn(300);
											z_chat_first = 0;
										} else {
											$('#page_chatroom_messages').animate({ scrollTop: $('#page_chatroom_messages')[0].scrollHeight - $('#page_chatroom_messages').height() },300);
										}
									}
								});
							}

						}
	}				


/*
* XOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOX
*
* start
*
* XOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOX
*/


$(document).ready(function() {
//	$('body').css('display','none');
//	$('body').fadeIn(200);
	z_updateClientTime();
	$('#pageAlertButtonHide').live('click',function(e) {
		$.post('/ajax.x',{ cmd: 'pageflags_remove_mail', siteid: z_site_id, userid: z_user_id, token: z_user_token }, function(responseText) {
			if (responseText.length > 0) {
				z_pageAlertsHide();
			}
		});
	});
	z_pageDimmerReset();
	z_pageCheckFlags();
	var	z_interval_pageCheckFlags = setInterval("z_pageCheckFlags()",20000);
	z_user_update_energy_recovery();
	z_site_energy_refresh = setInterval('z_user_update_energy_recovery()',1200);
	$('#container').live('mouseleave',function(e) {
		$('[id^=pageSubmenu_]').hide();
	});
	$('[id^=pageButton_]').live('mouseenter',function(e) {
		$('[id^=pageSubmenu_]').hide();
		$('#pageSubmenu_' + buttonid).show();
		var buttonid = $(this).attr('id').split("_").pop();
		var submenu_top = $(this).offset().top + 40;
		$('#pageSubmenu_' + buttonid).css('position','absolute');
		$('#pageSubmenu_' + buttonid).show();
		$('#pageSubmenu_' + buttonid).offset({ top: submenu_top, left: $(this).offset().left - 2 });
	});
	$('[id^=pageSubmenu_]').live('mouseleave',function(e) {
		var buttonid = $(this).attr('id').split("_").pop();
		$('#pageSubmenu_' + buttonid).hide();
	});

/* ... profile links ... */

	$('[id^=profilelink_]').live('mouseenter',function(e) {
		$(this).addClass('page-link-hover');
	});
	$('[id^=profilelink_]').live('mouseleave',function(e) {
		$(this).removeClass('page-link-hover');
	});
	$('[id^=profilelink_]').live('click',function(e) {
		var	z_data = $(this).attr('id').split('_');
		var	z_username = z_data[1];
		window.location = '/' + z_username;
	});

/* ... item links ... */

	if (z_user_mobile) {
		$('[id^=itemlink_]').live('click',function(e) {
			var	z_data = $(this).attr('id').split('_');
			var	itemid = z_data[1];
			window.location = '/item.x?itemid=' + itemid;
		});
	}
	$('[id^=itemlink_]').live('mouseenter',function(e) {
		var	z_data = $(this).attr('id').split('_');
		var	itemid = z_data[1];
		z_showAtCursor('itemCard_' + itemid,e);
		if (z_user_mobile) {
			$(this).css('cursor','pointer');
		}
	});
	$('[id^=itemlink_]').live('mousemove',function(e) {
		var	z_data = $(this).attr('id').split('_');
		var	itemid = z_data[1];
		z_showAtCursor('itemCard_' + itemid,e);
	});
	$('[id^=itemlink_]').live('mouseleave',function(e) {
		var	z_data = $(this).attr('id').split('_');
		var	itemid = z_data[1];
		$('#itemCard_' + itemid).hide();
		if (z_user_mobile) {
			$(this).css('cursor','auto');
		}
	});

/* ... button links ... */

	$('.button-disabled').live('click',function(e) {
		e.preventDefault();
		return false;
	});
	$('.button-disabled-small').live('click',function(e) {
		e.preventDefault();
		return false;
	});
	$('.button-disabled-large').live('click',function(e) {
		e.preventDefault();
		return false;
	});
	$('.button-pagelink-disabled').live('click',function(e) {
		e.preventDefault();
		return false;
	});

/* ... page links ... */

	$('[id^=page_link_]').addClass('page-link');
	$('[id^=page_link_]').live('mouseenter',function(e) {
		$(this).css('cursor','pointer');
//		$(this).css('text-decoration','underline');
		$(this).addClass('page-link-hover');
	});
	$('[id^=page_link_]').live('mouseleave',function(e) {
		$(this).css('cursor','auto');
//		$(this).css('text-decoration','none');
		$(this).removeClass('page-link-hover');
	});
	$('#page_link_members').click(function(e) {
		window.location = z_url_members;
	});
	$('#page_link_members_online').click(function(e) {
		window.location = z_url_members_online;
	});
	$('#page_link_members_chat').click(function(e) {
		window.location = z_url_members_chat;
	});

/* ... page help links ... */

	$('[id^=page_help_link_]').addClass('page-link');
	$('[id^=page_help_link_]').live('mouseenter',function(e) {
		$(this).css('cursor','pointer');
//		$(this).css('text-decoration','underline');
		$(this).addClass('page-link-hover');
	});
	$('[id^=page_help_link_]').live('mouseleave',function(e) {
		$(this).css('cursor','auto');
//		$(this).css('text-decoration','none');
		$(this).removeClass('page-link-hover');
	});
	if (z_user_mobile) {
//		$('[id^=page_help_link_]').live('click',function(e) {
		$('[id^=page_help_link_]').click(function(e) {
			var helpid = $(this).attr('id').split("_").pop();
			window.location = z_url_faq + '?helpid=' + helpid;
			return false;
		});
	} else {
//		$('[id^=page_help_link_]').live('click',function(e) {
		$('[id^=page_help_link_]').click(function(e) {
			var helpid = $(this).attr('id').split("_").pop();
			$.get('/ajax.x?cmd=page_help&helpid=' + helpid + '&token=' + z_user_token, function(responseText) {
				if (responseText.length > 0) {
					$('#page_help_message').html(responseText);
					z_pageHelpShow();
				}
			});
		});
//		$('[id^=pageHelp]').live('click',function(e) {
		$('[id^=pageHelp]').click(function(e) {
			z_pageHelpHide();
		});
	}


	$('[id^=page_alert_button_delete_]').live('click',function(e) {
		e.preventDefault();
		var id = $(this).attr('id').split("_").pop();
		$.post('/ajax.x',{ cmd: 'user_alert_delete', siteid: z_site_id, alertid: id, token: z_user_token }, function(responseText) {
//alert(responseText);
			z_pageAlertUpdate();
		});
	});
	$('[id^=ignore_link_]').live('click',function(e) {
		e.preventDefault();
		return false;
	});


/* ... chatroom ... */

	$('#page_header_chatroom_show').live('click',function(e) {
		if ($('#page_chatroom').length == 0) {
			$('#page_chatroom_ajax').load('/ajax.x?cmd=page_chatroom_include&token=' + z_user_token,function(e) {
//alert('test');
				zChat.showChat();
				zChat.enableChatUpdate();
			});
//				$('#page_chatroom_ajax').load('/ajax.x?cmd=page_chatroom_include&token=' + z_user_token);
//			} else {
//				zChat.showChat();
		} else {
			zChat.showChat();
			zChat.enableChatUpdate();
		}
	});
	$('#page_header_chatroom_hide').live('click',function(e) {
		zChat.hideChat();
//__save_2012.01.09			zChat.disableChatUpdate();
		zChat.leaveChat();
	});
});  

$(window).resize(function(e) {
//__FUTURE			$('#<?= $GLOBALS['flag_program']; ?>Window').zCenter();
	z_pageDimmerReset();
});

$(window).scroll(function(e) {
	$('[id^=pageSubmenu_]').hide();
});

$(window).ready(function() {
//__FUTURE			$('#<?= $GLOBALS['flag_program']; ?>Window').zCenter();
});

