var locale = new Object();
locale.write = 'Write message';
locale.reply = 'Your reply';
locale.view_photo = 'View photo';
locale.gallery = 'View gallery';
locale.friends = 'Friends';
locale.guestbook = 'Guestbook';
locale.messages = 'Message archive';
locale.gifts = 'Give a gift';
locale.remove = 'Remove friend';
locale.add = 'Invite to friends';
locale.change_status = 'Friendship status';
locale.notify_tab = 'Notify\'s';
locale.send = 'Send';
locale.close = 'Close';
locale.new_messages = 'Messages (%s)';
locale.profile = 'My profile';
locale.complain = 'File a complaint';
locale.flash_new_message = '* New message *';
locale.view_profile = 'View profile';
locale.open_chat = 'Open chat';
locale.addremove_friend = 'Add / Remove friend';
locale.blogs = 'Blog';

locale.photo_edit_com = 'Edit comment';
locale.photo_move_to = 'Move photo';
locale.photo_set_default = 'Set default';
locale.photo_delete = 'Delete photo';

locale.complain_select_reasoin = 'Please select reason.';
locale.complain_fill_reasoin = 'Please fill custom reason.';

locale.friends_recently = 'Recently added';
locale.friends_all = 'All friends';
locale.friends_invite = 'Invite friends';
locale.friends_find = 'Find friends';
locale.new_sys_notty = '*New notification*';
locale.new_chat_notty = '*New message*';

var calendar = {
	months : [ 'January', 'February', 'March', 'April', 'May', 'June', 'July',
			'August', 'September', 'October', 'November', 'December' ],
	days : [ 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday',
			'Saturday' ]
};

var currentX = -1;
var currentY = -1;

var leftmenuTimer = null;

var menuTimer = null;
var showPhoneBlock = 0;
var phoneTimer = null;
var showMenuBlock = 0;
var friendMenuBlock = 0;
var friendMenuTimer = null;

var isMsie = false;
var isMozilla = false;
var isOpera = false;
var isSafari = false;
var lastMsgId = '';
var messagePoll = new Array();
var init = false;
var title = null;
var profile = null;
var informer = null;
var user = null;
var message = null;
var active = false;
var flashing_timer = null;
var the_title = window.document.title;

var smile_path = '/skins/smiles/'
var smiles = new Array();
smiles[':)'] =	'-1px';
smiles[';)'] =	'-18px';
smiles[':P'] =	'-36px';
smiles[':]'] =	'-54px';
smiles[':D'] =	'-72px';
smiles['8}'] =	'-90px';
smiles[':`('] = '-108px';
smiles[':`)'] = '-162px';
smiles[':('] =	'-126px';
smiles['=0'] =	'-144px';
smiles['(h)'] = '-180px';
smiles['(k)'] = '-198px';
smiles['(c)'] = '-216px';
smiles['(f)'] = '-234px';


var flash_timer     = null;
var sys_title_data = new Array(locale.new_sys_notty, '*Fizzer.ph*', window.document.title);
var chat_title_data = new Array(locale.new_chat_notty, '*Fizzer.ph*', window.document.title);
var title_index = 0;

var sys_notifier_active = false;
var chat_notifier_active = false;


var my_array = 0;
var glob_id = 0;
/**
 * Detect current browser and set mouse handler
 */
function detectBrowsers() {
	jQuery.each(jQuery.browser, function(i, val) {
		if (i.toLowerCase() != "version" && val) {
			var name = i.charAt(0).toUpperCase() + i.substr(1);
			eval('is' + name + ' = true;');
		}
	});
	document.onmousemove = trackMouse;
}

/**
 * Mouse movement tracking handler
 */
function trackMouse(e) {
	var x = 0;
	var y = 0;
	if (isMsie) {
		// must be IE
		try {
			x = event.clientX + document.documentElement.scrollLeft;
			y = event.clientY + document.documentElement.scrollTop;
		} catch (e) {
		}
	} else {
		try {
			x = e.pageX;
			y = e.pageY;
		} catch (e) {
		}
	}
	currentX = (x < 0 ? 0 : x);
	currentY = (y < 0 ? 0 : y);
}

function showPhoto(pht_id, x, y) {
	menuTimer = setTimeout('showPhotoMenu(' + pht_id + ',' + x + ',' + y +');', 500);
}

function hidePhoto() {
	if (menuTimer) {
		clearTimeout(menuTimer);
		menuTimer = null;
	}
	if (showMenuBlock == 1) {
		showMenuBlock = 0;
		setTimeout('hidePhotoMenu()', 500);
	}
}

function showPhotoMenu(pht_id, x, y) {
	if (showMenuBlock == 1) {
		return;
	}

	var menu = '<table class="content_menu_gallery content_menu" cellpadding="0" cellspacing="0" style="width: 146px;">'
				+ '<tr class="header">'
					+ '<td class="side_center" style="background: url(/skins/1/gallery/context_menu.png) repeat-y top left;">'
						+ '<div style="width: 142px"><p onclick="hidePhoto(); setDefaultPhoto('
							+ pht_id + ');"><img src="/skins/_.png" class="setdefault" alt="" />' + locale.photo_set_default + '<\/p></div>'
						+ '<div style="width: 142px"><p onclick="hidePhoto(); editPhotoDescr('
							+ pht_id + ');"><img src="/skins/_.png" class="editcomment" alt="" />' + locale.photo_edit_com + '<\/p></div>'
						+ '<div style="width: 142px"><p onclick="hidePhoto(); movePhoto(\'' + pht_id
							+ '\');"><img src="/skins/_.png" class="movephoto" alt="" />' + locale.photo_move_to + '<\/p></div>'
						+ '<div style="width: 142px"><p onclick="hidePhoto(); deletePhoto('
							+ pht_id + ');"><img src="/skins/_.png" class="deletephoto" alt="" />' + locale.photo_delete + '<\/p></div>'
					+ '<\/td>'
				+ '</tr>'
				+ '<tr>'
					+ '<td style="height: 8px; width: 146px; background: url(/skins/1/gallery/context_bottom.png) no-repeat top left;"></td>'
				+ '</tr>'
			+ '</table>';

	displayBlock(menu, "contextmenu", x, y, 0, 1);
}

function hidePhotoMenu() {
	if (showMenuBlock == 0) {
		obj = document.getElementById('contextmenu');
		// obj.innerHTML = '';
		obj.style.left = '-500px';
		obj.style.top = '-500px';
	}
}
/**
 * Start menu generation timer. It's needed so that browser is able to calculate
 * new mouse positions witch are cathed by userland onmousemove handler
 */
function showMenu(id, nick, photo, add_html, timeout, skip) {
	if (typeof add_html == "undefined") {
		add_html = '';
	}
	if (typeof timeout == "undefined") {
		timeout = 500;
	}
	if (typeof skip == "undefined") {
		skip = true;
	} else {
		skip = false;
	}
	menuTimer = setTimeout('showContextMenu("' + id + '", "' + nick + '", "'
			+ photo + '", "' + escape(add_html) + '", ' + skip + ');', timeout);
}

/**
 * Generate menu HTML and draws it
 */
function showContextMenu(id, nick, photo, add_html, skip) {
	if (showMenuBlock == 1) {
		return;
	}
	if (skip) {
		add_html += '<p onclick="hideMenu(); $.FizzerDialogAJAX(\''
				+ locale.addremove_friend
				+ '\', \'/ajax/friends/addRemove/'
				+ id + '.html\');"><img src="/skins/_.png" class="addremovefriend" alt="" />' + locale.addremove_friend + '<\/p>';
	}
	var menu = '<table class="content_menu" cellpadding="0" cellspacing="0">'
			+ '<tr class="header">'
			+ '<td class="center_header" colspan="3"></td>'
			+ '</tr>'
			+ '<tr>'
			+ '<td class="side_left"></td>'
			+ '<td class="side_center">'
			+ '<p onclick="dropMenu(); $(\'#fizzercenter\').FizzerHREF(\'/profile/user/'
			+ id
			+ '.html\');"><img src="/skins/_.png" class="viewprofile" alt="" />'
			+ locale.view_profile
			+ '<\/p>'
			+ '<p class="popupajax" onclick="dropMenu();" href="/gallery/viewmainphoto/'
			+ id
			+ '.html"><img src="/skins/_.png" class="preview" alt="" />'
			+ locale.view_photo
			+ '<\/p>'
			+ '<p onclick="dropMenu(); $(\'#fizzercenter\').FizzerHREF(\'/gallery/user/'
			+ id
			+ '.html\');"><img src="/skins/_.png" class="view-gallery" alt="" />'
			+ locale.gallery
			+ '<\/p>'
			+ '<p onclick="dropMenu(); $.fizzerchat.livechat(\''
			+ id
			+ '\',\''
			+ nick
			+ '\',\'focus\');"><img src="/skins/_.png" class="sendmessage" alt="" />'
			+ locale.open_chat
			+ '<\/p>'
			+ '<p onclick="dropMenu(); $(\'#fizzercenter\').FizzerHREF(\'/guestbook/user/'
			+ id
			+ '.html\');"><img src="/skins/_.png" class="guestbook" alt="" />'
			+ locale.guestbook
			+ '<\/p>'
			+ '<p onclick="dropMenu(); $(\'#fizzercenter\').FizzerHREF(\'/blogs/entries/'
			+ id
			+ '.html\');"><img src="/skins/_.png" class="blogs" alt="" />'
			+ locale.blogs
			+ '<\/p>'
			+ '<p onclick="dropMenu(); $(\'#fizzercenter\').FizzerHREF(\'/extras/gifts/'
			+ id
			+ '.html\');"><img src="/skins/_.png" class="makegift" alt="" />'
			+ locale.gifts
			+ '<\/p>'
			+ '<p onclick="dropMenu(); $(\'#fizzercenter\').FizzerHREF(\'/friends/friendlist/'
			+ id
			+ '.html\');"><img src="/skins/_.png" class="friends" alt="" />'
			+ locale.friends
			+ '<\/p>'
			+
			// '<p class="messages" onclick="dropMenu();
			// $(\'#fizzercenter\').FizzerHREF(\'/messages/show/'+id+'.html\');">'+locale.messages+'<\/p>'+
			unescape(add_html)
			+ '<p onclick="dropMenu(); $.FizzerDialogAJAX(\''
			+ locale.complain + '\', \'/ajax/profile/complain/' + id
			+ '.html\');"><img src="/skins/_.png" class="complain" alt="" />' + locale.complain + '<\/p>' + '<\/td>'
			+ '<td class="side_right"></td>' + '</tr>' + '<tr class="header">'
			+ '<td class="center_bottom" colspan="3"></td>' + '</tr>'
			+ '</table>';
	displayBlock(menu, "contextmenu");
}

/**
 * Set timer for context menu hiding. Timer is needed because moving mouse over
 * context menu itself generates onmouseout within the image itself
 */
function hideMenu() {
	if (menuTimer) {
		clearTimeout(menuTimer);
		menuTimer = null;
	}
	if (showMenuBlock == 1) {
		showMenuBlock = 0;
		setTimeout('hideContextMenu()', 500);
	}
}

/**
 * Drop menu before AJAX CALL
 *
 * @return
 */
function dropMenu() {
	if (menuTimer) {
		clearTimeout(menuTimer);
		menuTimer = null;
	}
	if (showMenuBlock == 1) {
		showMenuBlock = 0;
		hideContextMenu();
	}
}

/**
 * Hide block after timeout if hide flag is 0
 */
function hideContextMenu() {
	if (showMenuBlock == 0) {
		//$('#contextmenu').fadeout('slow', function() {
			obj = document.getElementById('contextmenu');
			obj.innerHTML = '';
			obj.style.left = '-500px';
			obj.style.top = '-500px';
		//});

	}

	if (showPhoneBlock) {
		phoneFlag();
	}
}

/**
 * Calculate block drawing position taking into account browser window borders
 */
function calculatePosition(id) {
	var tabW = document.getElementById(id).offsetWidth;
	var tabH = document.getElementById(id).offsetHeight;

	if (window.innerWidth) {
		var winW = window.innerWidth;
		var winH = window.innerHeight;
	} else if (document.documentElement && document.documentElement.clientWidth) {
		var winW = document.documentElement.clientWidth;
		var winH = document.documentElement.clientHeight;
	} else if (document.body) {
		var winW = document.body.clientWidth;
		var winH = document.body.clientHeight;
	}

	if (window.pageYOffset) {
		var scrT = window.pageYOffset;
	} else if (document.documentElement && document.documentElement.scrollTop) {
		var scrT = document.documentElement.scrollTop;
	} else if (document.body) {
		var scrT = document.body.scrollTop;
	}

	if (currentX > winW - tabW) {
		currentX = winW - tabW - 25;
	} else {
		currentX = currentX + 5;
	}

	if ((currentY - scrT) > (winH - tabH)) {
		currentY = scrT + winH - tabH - 5;
	} else {
		currentY = currentY + 10;
	}
}

/**
 * Write HTML to specified element and show it near the mouse pointer
 */
function displayBlock(html, id, x, y, gm, beginning) {
	if (typeof x == "undefined") {
		x = 0;
	}
	if (typeof y == "undefined") {
		y = 0;
	}
	if (typeof gm == "undefined") {
		gm = 0;
	}
	if (typeof beginning == "undefined") {
		beginning = 0;
	}

	var obj = document.getElementById(id);
	obj.innerHTML = html;
	calculatePosition(id);
	if (gm > 0) {
		while(currentX + x + 520 > window.innerWidth) {
			x = x - 10;
		}
	}
	if (beginning > 0) {
		obj.style.left = x + 'px';
		obj.style.top = y+120 + 'px';
	} else {
		obj.style.left = (currentX + x) + 'px';
		obj.style.top = (currentY + y) + 'px';
	}
	showMenuBlock = 1;
	showPhotoBlock = 1;
	showPhoneBlock = 1;

	$.AjaxCall();

}

/**
 * Load specified url in current window/tab
 */
function goTo(url, opener) {
	if (typeof opener != "undefined") {
		window.opener.location.href = url;
	} else {
		window.location.href = url;
	}
}

/**
 * Show and hide element
 *
 */
function showHideIt(id) {
	var obj = document.getElementById(id);
	obj.style.display = (obj.style.display == "none") ? "" : "none";
	return false;
}

/**
 * Check radio button, according to selected vote mark
 */
function AddMark(obj) {
	obj.parentNode.getElementsByTagName('input')[0].checked = "checked";
	return false;
}

/**
 * Uncheck all checkboxes under specified name
 */
function uncheck(name) {
	var el = document.getElementsByName(name);
	for ( var i = 0; i < el.length; ++i) {
		el[i].checked = false;
	}
}

function getSmiles(split) {
	return '<img onclick="write_smile(this); return false;" src="/skins/_.png" title=":)" style="cursor: pointer; background: url(\'/skins/smiles/smiles.png\') -1px 0px;" height="18" hspace="2" vspace="1" width="18" \/>'
			+ '<img onclick="write_smile(this); return false;" src="/skins/_.png" title=";)" style="cursor: pointer; background: url(\'/skins/smiles/smiles.png\') -18px 0px;" height="18" hspace="2" vspace="1" width="18" \/>'
			+ '<img onclick="write_smile(this); return false;" src="/skins/_.png" title=":P" style="cursor: pointer; background: url(\'/skins/smiles/smiles.png\') -36px 0px;" height="18" hspace="2" vspace="1" width="18" \/>'
			+ '<img onclick="write_smile(this); return false;" src="/skins/_.png" title=":]" style="cursor: pointer; background: url(\'/skins/smiles/smiles.png\') -54px 0px;" height="18" hspace="2" vspace="1" width="18" \/>'
			+ '<img onclick="write_smile(this); return false;" src="/skins/_.png" title=":D" style="cursor: pointer; background: url(\'/skins/smiles/smiles.png\') -72px 0px;" height="18" hspace="2" vspace="1" width="18" \/>'
			+ '<img onclick="write_smile(this); return false;" src="/skins/_.png" title="8}" style="cursor: pointer; background: url(\'/skins/smiles/smiles.png\') -90px 0px;" height="18" hspace="2" vspace="1" width="18" \/>'
			+ '<img onclick="write_smile(this); return false;" src="/skins/_.png" title=":`(" style="cursor: pointer; background: url(\'/skins/smiles/smiles.png\') -108px 0px;" height="18" hspace="2" vspace="1" width="18" \/>'
			+ (typeof split != "undefine" && split ? '<br \/>' : '')
			+ '<img onclick="write_smile(this); return false;" src="/skins/_.png" title=":`)" style="cursor: pointer; background: url(\'/skins/smiles/smiles.png\') -162px 0px;" height="18" hspace="2" vspace="1" width="18" \/>'
			+ '<img onclick="write_smile(this); return false;" src="/skins/_.png" title=":(" style="cursor: pointer; background: url(\'/skins/smiles/smiles.png\') -126px 0px;" height="18" hspace="2" vspace="1" width="18" \/>'
			+ '<img onclick="write_smile(this); return false;" src="/skins/_.png" title="=0" style="cursor: pointer; background: url(\'/skins/smiles/smiles.png\') -144px 0px;" height="18" hspace="2" vspace="1" width="18" \/>'
			+ '<img onclick="write_smile(this); return false;" src="/skins/_.png" title="(h)" style="cursor: pointer; background: url(\'/skins/smiles/smiles.png\') -180px 0px;" height="18" hspace="2" vspace="1" width="18" \/>'
			+ '<img onclick="write_smile(this); return false;" src="/skins/_.png" title="(k)" style="cursor: pointer; background: url(\'/skins/smiles/smiles.png\') -198px 0px;" height="18" hspace="2" vspace="1" width="18" \/>'
			+ '<img onclick="write_smile(this); return false;" src="/skins/_.png" title="(c)" style="cursor: pointer; background: url(\'/skins/smiles/smiles.png\') -216px 0px;" height="18" hspace="2" vspace="1" width="18" \/>'
			+ '<img onclick="write_smile(this); return false;" src="/skins/_.png" title="(f)" style="cursor: pointer; background: url(\'/skins/smiles/smiles.png\') -234px 0px;" height="18" hspace="2" vspace="1" width="18" \/>';
}

function giftUser(id, nick, photo) {
	menuTimer = setTimeout('showGiftMenu("' + id + '", "' + nick + '", "'
			+ photo + '");', 500);
}

function showActivity(photo, text, link) {
	menuTimer = setTimeout('showActivityBlock("' + photo + '", "' + text
			+ '", "' + link + '");', 500);
}

/**
 * Draws user's photo
 */
function showActivityBlock(photo, text, link) {
	if (showMenuBlock == 1) {
		return;
	}

	link = link || '';

	if ( link != '' ) {
		a1 = 	'<a href="#" class="none" onclick="dropMenu(); return $(\'#fizzercenter\').FizzerHREF(\''
				+ link
				+ '\');">';
		a2 = 	'</a>';

	} else {
		a1 = '';
		a2 = '';
	}

	var menu = '<table class="content_menu" cellpadding="0" cellspacing="0">'
			+ '<tr class="header">'
			+ '<td class="center_header" colspan="3"></td>'
			+ '</tr>'
			+ '<tr>'
			+ '<td class="side_left"></td>'
			+ '<td class="side_center center">'
			+ a1
			+ '<img src="'
			+ photo
			+ '" alt="" \/>'
			+ a2
			+ '<div class="nick" style="margin: 10px;">'
			+ a1
			+ text
			+ a2
			+ '<\/div>' + '<\/td>'
			+ '<td class="side_right"></td>' + '</tr>' + '<tr class="header">'
			+ '<td class="center_bottom" colspan="3"></td>' + '</tr>'
			+ '</table>';

	displayBlock(menu, "contextmenu");
}

/**
 * Draws user's photo
 */
function showGiftMenu(id, nick, photo) {
	if (showMenuBlock == 1) {
		return;
	}
	var menu = '<table class="content_menu" cellpadding="0" cellspacing="0">'
			+ '<tr class="header">'
			+ '<td class="center_header" colspan="3"></td>'
			+ '</tr>'
			+ '<tr>'
			+ '<td class="side_left"></td>'
			+ '<td class="side_center center">'
			+ '<a href="#" onclick="dropMenu(); return $(\'#fizzercenter\').FizzerHREF(\'/profile/user/'
			+ id
			+ '.html\');">'
			+ '<img src="'
			+ photo
			+ '" alt="" \/>'
			+ '<\/a>'
			+ '<div class="nick">'
			+ '<a href="#" onclick="dropMenu(); return $(\'#fizzercenter\').FizzerHREF(\'/profile/user/'
			+ id + '.html\');">' + nick + '<\/a>' + '<\/div>' + '<\/td>'
			+ '<td class="side_right"></td>' + '</tr>' + '<tr class="header">'
			+ '<td class="center_bottom" colspan="3"></td>' + '</tr>'
			+ '</table>';
	displayBlock(menu, "contextmenu");
}

/**
 * Let user to enter only numbers to text field
 */
function testKey(e) {
	// Make sure to use event.charCode if available
	var key = (typeof e.charCode == 'undefined' ? e.keyCode : e.charCode);

	// Ignore special keys
	if (e.ctrlKey || e.altKey || key < 32)
		return true;

	key = String.fromCharCode(key);
	return /\d/.test(key);
}

/**
 * Forward page according to pager data
 */
function goToPage(o, url, appurl) {
	var page = parseInt(o.page.value);

	if (appurl == "undefined") {
		appurl = '';
	}

	if (page) {
		var link = $(o).find('a');
		link.attr('href', url + page + appurl);
		link.click();
	}

	return false;
}

/**
 * Check if username or e-mail exists at DB
 *
 */
function checkUserSignup(obj, type) {

	return;

	var value = obj.value;
	if (value.length) {
		var send = type.replace('signup-', '');
		$.get('/ajax/signup/checkUser/' + send + '/' + value + '.html', {},
				function(resp) {
					if (resp == '1') {
						showUserSignupError(send);
					} else {
						hideUserSignupError(send);
					}
				});
	}
	return;
}

/**
 * Show error at signup form
 *
 */
function showUserSignupError(type) {
	var error = 'This ' + ((type == 'username') ? 'username' : 'e-mail');
	var cell = $('#signup-' + type);
	cell.html('<span class="error">' + error + ' already exists<br /></span>');
}

/**
 * Hide error at signup form if user changed username or e-mail
 *
 */
function hideUserSignupError(type) {
	var error = 'This ' + ((type == 'username') ? 'username' : 'e-mail');
	var cell = $('#signup-' + type);
	cell.empty();
}

function clearFlashingTimer() {
	clearTimeout(flashing_timer);
	flashing_timer = null;
}

function flashTitle(start) {
	if (start && active) {
		if (flashing_timer != null) {
			clearFlashingTimer();
		}
		flashing_timer = setTimeout('doFlashing(true)', 1000);
	} else {
		clearFlashingTimer();
		window.document.title = the_title;
	}
}

function doFlashing(action) {
	window.document.title = action ? locale.flash_new_message : the_title;
	flashing_timer = setTimeout('doFlashing(' + !action + ')', 1000);
}

function write_smile(obj) {
	var $text = $('#msg_editor').val() + obj.title + ' ';
	$('#msg_editor').val($text).focus();
}

function parseSmiles(msg) {
	var result = msg;
	for (smile in smiles) {
		if (result != null && result.length > 0) {
			var a = 0;
			var b = 0;
			var aReplace = '<img src="/skins/_.png" ' +
					'" class="smile" height="18" width="18" alt="' + smile + '"' +
					' align="baseline" '+
					'style="background: url(\'/skins/smiles/smiles.png\') '+smiles[smile]+' 0px;">';
			while (true) {
				a = result.indexOf(smile, b);
				if (a != -1) {
					result = result.substring(0, a) + aReplace
							+ result.substring(a + smile.length);
					b = a + aReplace.length;
				} else
					break;
			}
		}
	}
	return result;
}

$.ui.dialog.prototype._createButtons = function(buttons) {
	var self = this, hasButtons = false, uiDialogButtonPane = $('<div></div>')
			.addClass(
					'ui-dialog-buttonpane ' + 'ui-widget-content ' + 'ui-helper-clearfix');

	// if we already have a button pane, remove it
	this.uiDialog.find('.ui-dialog-buttonpane').remove();

	(typeof buttons == 'object' && buttons !== null && $.each(buttons,
			function() {
				return !(hasButtons = true);
			}));
	if (hasButtons) {
		$.each(buttons, function(name, fn) {
			$('<span></span>').addClass('input-button').html(
					$('<span></span>').text(name).append(
							$('<input type="button" />').click(function() {
								fn.apply(self.element[0], arguments);
							}))).appendTo(uiDialogButtonPane);
		});
		uiDialogButtonPane.appendTo(this.uiDialog);
	}
}

function showFriendsMenu(obj, id) {
	if (friendMenuTimer) {
		clearTimeout(friendMenuTimer);
		friendMenuTimer = null;
	}
	friendMenuBlock = true;
	if ($('#userFriendMenu').length == 0) {
		var html = '<ul id="userFriendMenu" style="display: none;">'
				+ '<li class="top">&nbsp;</li>'
				+ '<li class="menu_cell"><a onclick="hideFriendsMenu(); return $(\'#fizzercenter\').FizzerHREF(\'/friends/recent.html\');" href="/friends/recent.html">'
				+ locale.friends_recently
				+ '</a></li>'
				+ '<li class="menu_cell"><a onclick="hideFriendsMenu(); return $(\'#fizzercenter\').FizzerHREF(\'/friends/show.html\');" href="/friends/show.html">'
				+ locale.friends_all
				+ '</a></li>'
				+ '<li class="menu_cell"><a onclick="hideFriendsMenu(); return $(\'#fizzercenter\').FizzerHREF(\'/adressbook.html\');" href="/adressbook.html">'
				+ locale.friends_invite
				+ '</a></li>'
				+ '<li class="menu_cell"><a onclick="hideFriendsMenu(); return $(\'#fizzercenter\').FizzerHREF(\'/search.html\');" href="/search.html">'
				+ locale.friends_find + '</a></li>'
				+ '<li class="bottom">&nbsp;</li>' + '</ul>';
		$(obj).append(html);
		friendMenuTimer = setTimeout("$('#userFriendMenu').show();", 250);
	} else if ($('#userFriendMenu').css('display') == 'none' && friendMenuTimer == null) {
		friendMenuTimer = setTimeout("$('#userFriendMenu').show();", 250);
	}
}

function hideFriendsMenu() {
	friendMenuBlock = false;
	if (friendMenuTimer) {
		clearTimeout(friendMenuTimer);
		friendMenuTimer = null;
	}
	friendMenuTimer = setTimeout('hideFriendsMenuT()', 100);
}

function hideFriendsMenuT() {
	if (friendMenuBlock == false) {
		clearTimeout(friendMenuTimer);
		$('#userFriendMenu').hide();
		friendMenuTimer = null;
	}
}

/**
 * Get list of countries, cities, regions
 *
 */

jQuery.getCountries = function(id, def_country, do_next_select) {

	if (typeof def_country == "undefined" || def_country.length == 0) {
       	def_country = '';
	}

	$.getJSON("/ajax/location/getCountries/"+def_country, function(data) {

		var country = $('#' + id);

		country.attr("disabled", true);
		country.empty();
            country.append('<option value="">Select country</option>');
		$.each(data, function(i, item) {
			country.append('<option value="' + item.id + '" '
					+ ((item.st == 1) ? 'selected="selected"' : '') + '>'
					+ item.name + '</option>');
			if (item.st == 1) {
				def_country = item.id;
			}
		});

		if (country.html() != null) {
			country.attr("disabled", false);
			if (typeof do_next_select == "undefined" || do_next_select){
				$.getRegions('select-region', country.val());
			}
		}
	})
};

jQuery.getRegions = function(id, country_id, def_region, do_next_select) {

	if (typeof def_region == "undefined") {
		def_region = '';
	}

	var region = $('#' + id);
	region.empty();
	region.attr("disabled", true);

	var url = "/ajax/location/getRegions/" + country_id + '/' + def_region;
	$.getJSON(url, function(data) {
		if (data.length > 0) {
			region.append('<option value="">Select region</option>');
			$.each(data, function(i, item) {
				region.append('<option value="' + item.id + '" ' +
					((item.id == def_region) ? 'selected="selected"' : '') + '>'
					+ item.name + '</option>');
			});
			if (region.html() != null && region.html().length > 0) {
				region.attr("disabled", false);
			}
			if (region.val() != '' && do_next_select == true) {
				$.getCities('select-city', $('#select-country').val(), region.val());
			} else {
				$('#select-city').empty();
				$('#select-city').attr("disabled", true);
			}
		} else {

			region.empty();
			region.append('<option value="">No regions found</option>');

			if (typeof do_next_select == "undefined" || do_next_select) {
				$.getCities('select-city', $('#select-country').val());
			}

		}
	})
};

jQuery.getCities = function(id, country_id, reg_id, def_city, direction) {
	if (typeof reg_id == "undefined" || reg_id.length == 0) {
		reg_id = '';
	}

	var url = "/ajax/location/getCities/" + country_id + "/" + reg_id + "/" + def_city;
	$.getJSON(url, function(data) {

		var city = $('#' + id);

		city.attr("disabled", true);
		city.empty();

		city.append('<option value="">Select city</option>');
		$.each(data, function(i, item) {
			city.append('<option value="' + item.id + '"' +
				((item.id == def_city) ? ' selected="selected"' : '') + '>' +
				item.name + '</option>');
		});
		if (city.html().length > 0) {
			city.attr("disabled", false);
		} else {
			city.empty();
			city.append('<option value="">No cities found</option>');
		}
	})
};

jQuery.getSchools = function(id, direction, reg_id, city_id, def_school) {

	if (typeof city_id == "undefined" || city_id.length == 0) {
		city_id = '455313';
	}

	if (typeof reg_id == "undefined" || reg_id.length == 0) {
		reg_id = '455313';
	} else {
		reg_id = reg_id;
	}

	var url = "/ajax/schools/"+direction+"/" + reg_id + "/" + city_id;
	$.getJSON(url, function(data) {

		var schools = $('#' + id);

		schools.attr("disabled", true);
		schools.empty();

		schools.append('<option value="">Select</option>');
		$.each(data, function(i, item) {
			schools.append('<option value="' + item.sch_id  + '"'+
					((item.sch_id == def_school) ? ' selected="selected"' : '') + '>' +
					item.sch_name + '</option>');
		});
		if (schools.html().length > 0) {
			schools.attr("disabled", false);
		} else {
			schools.empty();
			schools.append('<option value="">No schools found</option>');
		}
	})
};

jQuery.getSections = function(id, sch_id, def_section) {

	if (typeof sch_id == "undefined" || sch_id.length == 0) {
		sch_id = '';
	}

	var url = "/ajax/schools/sections/" + sch_id;
	$.getJSON(url, function(data) {

		var section = $('#' + id);

		section.attr("disabled", true);
		section.empty();
		section.append('<option value="">Select</option>');
		$.each(data, function(i, item) {
			section.append('<option value="' + item.sct_id + '"' +
					((item.sct_id == def_section) ? ' selected="selected"' : '') + '>' +
					item.sct_name + '</option>');
		});
		if (section.html().length > 0) {
			section.attr("disabled", false);
		} else {
			section.empty();
			section.append('<option value="">No sections found</option>');
		}

	})
};
      /*
function currDate(timestamp) {
	var timer_dt = new Date();
	timer_dt.setTime(timestamp);

	var week_day = calendar.days[timer_dt.getDay()];
	var day = addZero(timer_dt.getDate());
	var month = calendar.months[timer_dt.getMonth()];
	var year = timer_dt.getFullYear();
	var hours = addZero(timer_dt.getHours());
	var minutes = addZero(timer_dt.getMinutes());
	var seconds = addZero(timer_dt.getSeconds());

	var curr_date = week_day + ', ' + day + ' ' + month + ' ' + year + ' - '
			+ hours + ":" + minutes;
	$('#head-date').html(curr_date);

	var new_timestamp = ((timestamp / 1000) + 1) * 1000;
	setTimeout(function() {
		currDate(new_timestamp)
	}, 60000);
}   */

function currDate(timestamp, places) {
	var timer_dt = new Date();
	timer_dt.setTime(timestamp);

	var week_day = calendar.days[timer_dt.getDay()];
	var day = addZero(timer_dt.getDate());
	var month = calendar.months[timer_dt.getMonth()];
	var year = timer_dt.getFullYear();
	var hours = addZero(timer_dt.getHours());
	var minutes = addZero(timer_dt.getMinutes());
	var seconds = addZero(timer_dt.getSeconds());


	for (i=0; i < places.length; i++) {

		if (places[i] == "top") {
			var curr_date = week_day + ', ' + day + ' ' + month + ' ' + year + ' - '
			+ hours + ":" + minutes;
			$('#head-date').html(curr_date);
		} else if (places[i] == "blogs") {
			if ($('#blog-date').length) {
				var curr_date = day + ' ' + month + ' ' + year + ' - ' + hours + ':' + minutes;
				$('#blog-date').html(curr_date);
			}

		}

	}



	if (typeof additional != "undefined") {
		for (i = 0; i < length(additional); i++) {

		}
	}

	var new_timestamp = ((timestamp / 1000) + 60) * 1000;
	setTimeout(function() {
		currDate(new_timestamp, places)
	}, 60000);
}

function addZero(num) {
	if (num < 10) {
		num = '0' + num;
	}
	return num;
}

function str_split ( f_string, f_split_length){
    f_string += '';

    if (f_split_length == undefined) {
        f_split_length = 1;
    }
    if (f_split_length > 0) {
        var result = [];
        while (f_string.length > f_split_length) {
            result[result.length] = f_string.substring(0, f_split_length);
            f_string = f_string.substring(f_split_length);
        }
        result[result.length] = f_string;
        return result;
    }
    return false;
}

function in_array (needle, haystack, argStrict) {
    var key = '', strict = !!argStrict;

    if (strict) {
        for (key in haystack) {
            if (haystack[key] === needle) {
                return true;
            }
        }
    } else {
        if (typeof(needle)=='string') {
            str = haystack.toString();
            return (str.search(needle) !== false);
        }

        for (key in haystack) {
            if (haystack[key] == needle) {
                return true;
            }
        }
    }

    return false;
}

function array_unique(array,numeric){
    var tem_arr = new Array();
    for(i=0;i < array.length;i++){
        if(numeric === true && typeof(array[i]) == 'string' && !isNaN(array[i])) {
        	array[i]=parseInt(array[i], 10);
        }
	    if(tem_arr.length == 0){
	        tem_arr[i] = array[i];
	    } else {
	    	var exist = false;
	        for(var j=0; j<tem_arr.length; j++){
	            if(tem_arr[j] === array[i]){
	                exist = true;
	            }
	        }
	        if(!exist){
	            if(array[i] != null){
	                tem_arr[i] = array[i];
	            }
			}
	    }
    }
    return tem_arr.join(' ').replace(/\s{2,}/g,' ').split(' ');
}

function test_password($password)
{
    if ($password.length == 0 )
    {
        return 0;
    }

    var $strength = 0;

    var $length = $password.length;

    /*** check if password is not all lower case ***/
    if($password.toLowerCase() != $password)
    {
        $strength += 5;
    }

    /*** check if password is not all upper case ***/
    if($password.toUpperCase() == $password)
    {
        $strength += 5;
    }

    /*** check string length is 8 - 10 chars ***/
    if($length >= 6 && $length <= 8)
    {
        $strength += 5;
    }

    /*** check if lenth is 10 - 15 chars ***/
    if($length >= 9 && $length <= 12)
    {
        $strength += 15;
    }

    /*** check if length greater than 15 chars ***/
    if($length > 12)
    {
        $strength += 20;
    }

    /*** get the numbers in the password ***/
    var $tmp = $password.match(/[0-9]+/);
    if (typeof $tmp == 'string') {
    	$strength += $tmp.length;
    }

    /*** check for special chars ***/
    var $tmp = $password.match(/[|!@#$%&*\/=?,;.:\-_+~^\\]+/);
    if (typeof $tmp == 'string') {
    	$strength += $tmp.length;
    }
    /*** get the number of unique chars ***/
    var $chars = str_split($password);
    var $num_unique_chars = array_unique($chars).length;
    $strength += $num_unique_chars * 3;
    /*** strength is a number 1-10; ***/
    $strength = $strength > 99 ? 99 : $strength;
    $strength = Math.floor($strength / 10 + 1);

    return $strength;
}

/* show flashing title about new notification */
function flash_title(id, action){
	if ((typeof id == 'undefined' && flash_timer == null) ||
		(typeof id != 'undefined' && id == 1)) {

		if (action == 'chat' && !sys_notifier_active) {
			var title = chat_title_data;
			chat_notifier_active = true;

		} else {
			var title = sys_title_data;
			sys_notifier_active = true;
		}

        window.document.title = title[title_index];
        title_index++

		if ((title_index+1) >= title.length) {
			title_index = 0;
		}
		flash_timer = setTimeout(function(){flash_title(1,action)}, 1000);
	}
}

/* switch off flashing title */
function close_flash_title(action){
	if (flash_timer != null){

		title_index = 0;

		if (action == 'chat' && !sys_notifier_active) {
			var title = chat_title_data;
			chat_notifier_active = false;

		} else {
			var title = sys_title_data;
			sys_notifier_active = false;
		}


		clearTimeout(flash_timer);
		flash_timer = null;
		window.document.title = title[2];
	}
}

function showRemoveGift(id)
{
	menuTimer = setTimeout('showMenuRemoveGift("'+id+'")', 500);
}

function showMenuRemoveGift(id)
{
	if (showMenuBlock == 1) {
		return;
	}

	var menu = '<table class="content_menu" cellpadding="0" cellspacing="0">'
			+ '<tr class="header">'
			+ '<td class="center_header" colspan="3"></td>'
			+ '</tr>'
			+ '<tr>'
			+ '<td class="side_left"></td>'
			+ '<td class="side_center">'
			+ '<p class="complain" onclick="dropMenu(); $.FizzerDialogAJAX(\''
			+ 'Remove Tomato' + '\', \'/ajax/extras/removeTomato.html\');">'
			+ 'Remove Tomato'
			+ '<\/p>'
			+ '<\/td>'
			+ '<td class="side_right"></td>' + '</tr>' + '<tr class="header">'
			+ '<td class="center_bottom" colspan="3"></td>' + '</tr>'
			+ '</table>';

	displayBlock(menu, "contextmenu");


}


//================================================================================================================================================
/**
 * Start menu generation timer. It's needed so that browser is able to calculate
 * new mouse positions witch are cathed by userland onmousemove handler
 */
function showGMenu(id, ids, arr) {
	if (typeof add_html == "undefined") {
		add_html = '';
	}
	if (typeof timeout == "undefined") {
		timeout = 500;
	}
	if (typeof skip == "undefined") {
		skip = true;
	} else {
		skip = false;
	}
	if (ids != glob_id) {
		glob_id = ids;
		showMenuBlock = 0;
		dropGMenu();
	}

	my_array = arr;
	menuTimer = setTimeout('showGCMenu("' + id + '","' + ids + '");', timeout);
}

/**
 * Generate menu HTML and draws it
 */
function showGCMenu(id, ids) {
	if (showMenuBlock == 1) {
		return;
	}

	var arr1 = my_array

	if (ids == 1) {
		var new_arr = arr1['Flowers'];
	} else if (ids == 2) {
		var new_arr = arr1['Ordinary gifts'];
	} else if (ids == 3) {
		var new_arr = arr1['Love'];
	} else if (ids == 4) {
		var new_arr = arr1['Extra gifts'];
	} else if (ids == 5) {
		var new_arr = arr1['Food'];
	} else if (ids == 6) {
		var new_arr = arr1['Sports'];
	} else if (ids == 7) {
		var new_arr = arr1['Gifts For Bullies'];
	} else if (ids == 8) {
		var new_arr = arr1['Charity gifts'];
	}


	var menu = '<div>'+
			   		'<div class="top1">'+
			   			'<div class="top2"></div>'+
			   		'</div>'+
			   		'<div class="mid1" style="height: 20px">'+
			   			'<div class="mid2" style="height: 20px"><div style="float: right"><img style="cursor: pointer" class="x-img" src="/skins/_.png" onclick="dropGMenu()"></div></div>'+
			   		'</div>'+
			   		'<div class="mid1">'+
			   			'<div class="mid2">'+
			   				'<div class="cont">';

	for (i = 0; i < new_arr.length; i++) {
		if (new_arr[i]['enc_usr_id'] == undefined) {
			ge = 'extra';
			urlend = '.html';
		} else {
			ge = "gift";
			urlend = '/' + new_arr[i]['enc_usr_id'] + '.html';
		}

		url = '/extras/' + ge + '/' + new_arr[i]['enc_exo_id'] + urlend;

		menu += '<div class="giftItem"><div class="imagegift" valign="middle"><a href="' + url + '" class="popupajax none" ftitle="Buy a present!">'+
				'<img src="/skins/extras/' + new_arr[i]['exo_id'] + '.png"/></a></div><div class="linkgift">'+
				'<center><a href="'+url+'" class="popupajax" ftitle="Buy a present!">'+new_arr[i]['exo_name']+'</a></center></div></div>';
	}
	menu +=    				'<div class="clear"></div></div>'+
						'</div>'+
					'</div>'+
					'<div class="bottom1">'+
						'<div class="bottom2"></div>'+
					'</div>'
			   '</div>';


	displayBlock(menu, id, -60, 0, 1);
}

function setFlag() {
	clearTimeout(menuTimer);
	menuTimer = null;
}


/**
 * Set timer for context menu hiding. Timer is needed because moving mouse over
 * context menu itself generates onmouseout within the image itself
 */
function hideGMenu() {
	if (menuTimer) {
		clearTimeout(menuTimer);
		menuTimer = null;
	}
	if (showMenuBlock == 1) {
		showMenuBlock = 0;
		setTimeout('hideGCMenu()', 500);
	}
}

/**
 * Drop menu before AJAX CALL
 *
 * @return
 */
function dropGMenu() {
	if (menuTimer) {
		clearTimeout(menuTimer);
		menuTimer = null;
	}
	if (showMenuBlock == 1) {
		showMenuBlock = 0;
		hideGCMenu();
	}
}
/**
 * Hide block after timeout if hide flag is 0
 */
function hideGCMenu() {
	if (showMenuBlock == 0) {
		obj = document.getElementById('contextmenu');
		obj.innerHTML = '';
		obj.style.left = '-500px';
		obj.style.top = '-500px';
	}
}


jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options = $.extend({}, options); // clone object since it's unexpected behavior if the expired property were changed
            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
        }
        // NOTE 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 phoneFlag() {
	clearTimeout(phoneTimer);
	phoneTimer = null;
	showPhoneBlock = 0;
}


function phonePopup() {
	phoneTimer = setTimeout('showPhoneMenu();', 200);
}

function showPhoneMenu() {
	if (showPhoneBlock == 1) {
		return;
	}
	var html =  "<div class='content_menu' style=''>"+
					"<div class='ph-popup-top'>"+
					"</div>"+
					"<div class='ph-popup-middle'>"+
						"<font class='ph-popup-text1'>Please enter you mobile number in this<br/> "+
						"format: COUNTRY CODE + AREA CODE<br/>"+
						"(if applicable) + MOBILE NUMBER. Do not<br/>"+
						"add a plus sign (+), spaces or zeroes.<br/>"+
						"See examples below:<br/></font>"+
						"<div class='spacer'></div><br/>"+
						"<img class='dotted-line' src='skins/_.png'/><br/>"+
						"<div><div style='float: left; padding-left: 5px;'>Country</div> <div style='float: right; padding-right: 130px;'>Format</div></div>"+
						"<img class='dotted-line' src='skins/_.png'/><br/>"+
						"<div class='spacer'></div>"+
						"<table class='ph-popup-table'>"+
							"<tr style='background: #efefef'>"+
								"<td><font class='ph-popup-text1'>Philippines</font></td>"+
								"<td>63 9XX 7654321</td>"+
							"</tr>"+
							"<tr>"+
								"<td><font class='ph-popup-text1'>United States</font></td>"+
								"<td>1 XXX 7654321</td>"+
							"</tr>"+
							"<tr style='background: #efefef'>"+
								"<td><font class='ph-popup-text1'>India</font></td>"+
								"<td>91 9X 87 654321</td>"+
							"</tr>"+
							"<tr>"+
								"<td><font class='ph-popup-text1'>United Kingdom</font></td>"+
								"<td>44 7987 654321</td>"+
							"</tr>"+
							"<tr style='background: #efefef'>"+
								"<td><font class='ph-popup-text1'>Guam</font></td>"+
								"<td>1 671 7654321</td>"+
							"</tr>"+
							"<tr>"+
								"<td><font class='ph-popup-text1'>Saipan</font></td>"+
								"<td>1 670 7654321</td>"+
							"</tr style='background: #efefef'>"+
							"<tr style='background: #efefef'>"+
								"<td><font class='ph-popup-text1'>Indonesia</font></td>"+
								"<td>62 11111111111</td>"+
							"</tr>"+
							"<tr>"+
								"<td><font class='ph-popup-text1'>Hong Kong</font></td>"+
								"<td>852 87654321</td>"+
							"</tr>"+
							"<tr style='background: #efefef'>"+
								"<td><font class='ph-popup-text1'>Spain</font></td>"+
								"<td>34 687654321</td>"+
							"</tr>"+
						"</table>"+
					"</div>"+
					"<div class='ph-popup-bottom'>"+
					"</div>"+
				"</div>";

	displayBlock(html, 'contextmenu', -10, -30, 0);
}
