/**
 * common functions
 */
//window.onerror = function() { return true; }

try {
//	window.event.cancelBubble = true;
} catch (e) {
}

try {
//	e.stopPropagation();
} catch (e) {
}

/**
*
*  Javascript sprintf
*  http://www.webtoolkit.info/
*
*
**/

sprintfWrapper = {

    init : function () {

        if (typeof arguments == "undefined") { return null; }
        if (arguments.length < 1) { return null; }
        if (typeof arguments[0] != "string") { return null; }
        if (typeof RegExp == "undefined") { return null; }

        var string = arguments[0];
        var exp = new RegExp(/(%([%]|(\-)?(\+|\x20)?(0)?(\d+)?(\.(\d)?)?([bcdfosxX])))/g);
        var matches = new Array();
        var strings = new Array();
        var convCount = 0;
        var stringPosStart = 0;
        var stringPosEnd = 0;
        var matchPosEnd = 0;
        var newString = '';
        var match = null;

        while (match = exp.exec(string)) {
            if (match[9]) { convCount += 1; }

            stringPosStart = matchPosEnd;
            stringPosEnd = exp.lastIndex - match[0].length;
            strings[strings.length] = string.substring(stringPosStart, stringPosEnd);

            matchPosEnd = exp.lastIndex;
            matches[matches.length] = {
                match: match[0],
                left: match[3] ? true : false,
                sign: match[4] || '',
                pad: match[5] || ' ',
                min: match[6] || 0,
                precision: match[8],
                code: match[9] || '%',
                negative: parseInt(arguments[convCount]) < 0 ? true : false,
                argument: String(arguments[convCount])
            };
        }
        strings[strings.length] = string.substring(matchPosEnd);

        if (matches.length == 0) { return string; }
        if ((arguments.length - 1) < convCount) { return null; }

        var code = null;
        var match = null;
        var i = null;

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

            if (matches[i].code == '%') { substitution = '%' }
            else if (matches[i].code == 'b') {
                matches[i].argument = String(Math.abs(parseInt(matches[i].argument)).toString(2));
                substitution = sprintfWrapper.convert(matches[i], true);
            }
            else if (matches[i].code == 'c') {
                matches[i].argument = String(String.fromCharCode(parseInt(Math.abs(parseInt(matches[i].argument)))));
                substitution = sprintfWrapper.convert(matches[i], true);
            }
            else if (matches[i].code == 'd') {
                matches[i].argument = String(Math.abs(parseInt(matches[i].argument)));
                substitution = sprintfWrapper.convert(matches[i]);
            }
            else if (matches[i].code == 'f') {
                matches[i].argument = String(Math.abs(parseFloat(matches[i].argument)).toFixed(matches[i].precision ? matches[i].precision : 6));
                substitution = sprintfWrapper.convert(matches[i]);
            }
            else if (matches[i].code == 'o') {
                matches[i].argument = String(Math.abs(parseInt(matches[i].argument)).toString(8));
                substitution = sprintfWrapper.convert(matches[i]);
            }
            else if (matches[i].code == 's') {
                matches[i].argument = matches[i].argument.substring(0, matches[i].precision ? matches[i].precision : matches[i].argument.length)
                substitution = sprintfWrapper.convert(matches[i], true);
            }
            else if (matches[i].code == 'x') {
                matches[i].argument = String(Math.abs(parseInt(matches[i].argument)).toString(16));
                substitution = sprintfWrapper.convert(matches[i]);
            }
            else if (matches[i].code == 'X') {
                matches[i].argument = String(Math.abs(parseInt(matches[i].argument)).toString(16));
                substitution = sprintfWrapper.convert(matches[i]).toUpperCase();
            }
            else {
                substitution = matches[i].match;
            }

            newString += strings[i];
            newString += substitution;

        }
        newString += strings[i];

        return newString;

    },

    convert : function(match, nosign){
        if (nosign) {
            match.sign = '';
        } else {
            match.sign = match.negative ? '-' : match.sign;
        }
        var l = match.min - match.argument.length + 1 - match.sign.length;
        var pad = new Array(l < 0 ? 0 : l).join(match.pad);
        if (!match.left) {
            if (match.pad == "0" || nosign) {
                return match.sign + pad + match.argument;
            } else {
                return pad + match.sign + match.argument;
            }
        } else {
            if (match.pad == "0" || nosign) {
                return match.sign + match.argument + pad.replace(/0/g, ' ');
            } else {
                return match.sign + match.argument + pad;
            }
        }
    }
}

sprintf = sprintfWrapper.init;

/** Friends functions **/

function addToFriends(iFriendID) {
	if ($('#invFrnd'+iFriendID).attr('invited') != -1) {
		$('#invFrnd'+iFriendID).attr('oldvalue', $('#invFrnd'+iFriendID).html());
		$('#invFrnd'+iFriendID).html(procText);
		if ($('#invFrnd'+iFriendID).attr('invited') == 0) {
			$('#invFrnd'+iFriendID).attr('invited', -1);
			$.getJSON("/api/js/friend/add.php", { id: iFriendID }, function(aData){
				addToFrndsResp(aData);
			});
		} else {
			$('#invFrnd'+iFriendID).attr('invited', -1);
			$.getJSON("/api/js/friend/cancel.php", { id: iFriendID }, function(aData){
				cnlToFrndsResp(aData);
			});
		}
	}
}

function addToFrndsResp(aData) {
	if (aData['errors'] == '') {
		$('#invFrnd'+aData['id']).attr('invited', 1);
		$('#invFrnd'+aData['id']).html(cancelFrndText);
		oMasterNotifier.alert(sNewsFrndInvd, -1);
	} else {
		$('#invFrnd'+aData['id']).attr('invited', 0);
		$('#invFrnd'+aData['id']).attr('oldvalue');
	}
}

function cnlToFrndsResp(aData) {
	if (aData['errors'] == '') {
		$('#invFrnd'+aData['id']).attr('invited', 0);
		$('#invFrnd'+aData['id']).html(addFrndText);
		oMasterNotifier.alert(sNewsFrndInvCnl, -1);
	} else {
		$('#invFrnd'+aData['id']).attr('invited', 1);
		$('#invFrnd'+aData['id']).attr('oldvalue');
	}
}

function appToFriends(iFriendID) {
	if ($('#invFrnd'+iFriendID).attr('accepted') != -1) {
		$('#invFrnd'+iFriendID).attr('oldvalue', $('#invFrnd'+iFriendID).html());
		$('#invFrnd'+iFriendID).attr('accepted', -1);
		$('#invFrnd'+iFriendID).html(procText);
		$.getJSON("/api/js/friend/approve.php", { id: iFriendID }, function(aData){
			appFrndsResp(aData, -1);
		});
	}
}

function appFrndsResp(aData) {
	if (aData['errors'] == '') {
		$('#invFrnd'+aData['id']).attr('accepted', 1);
		$('#invFrnd'+aData['id']).attr('invited', 1);
		$('#invFrnd'+aData['id']).click(eval('function() { addToFriends('+aData['id']+'); }'));
		$('#invFrnd'+aData['id']).html(rmvFrndText);
		oMasterNotifier.alert(sNewsFrndApp, -1);
	} else {
		$('#invFrnd'+aData['id']).attr('accepted', 0);
		$('#invFrnd'+aData['id']).attr('oldvalue');
	}
}

/**
 * polling functions
 *
 * Used by the browser to keep the user up to date with their live events, i.e. chats and notifications
 */

/**
 * Used to allow access to the poller in timeouts
 */
var oMasterPoll = null;

/**
 * Always use this to get the poller
 */
function getPoller() {
	oMasterPoll = new poll();
	return oMasterPoll;
}

/**
 * The main poller class
 */
function poll() {
	this.schedual = 1000; // Milliseconds between polls
	this.handlers = new Array();
	this.stack = new Array();
}

/**
 * Start polling the server
 */
poll.prototype.start = function() {
	sendRequest = false;
	handlerStack = {};
	for (handleId in this.handlers) {
		if (this.handlers[handleId].active) {
			this.handlers[handleId].counter += this.schedual;
			if (this.handlers[handleId].counter >= this.handlers[handleId].schedual) {
				handlerStack[this.handlers[handleId].id] = this.handlers[handleId].params();
				this.handlers[handleId].counter = 0;
				sendRequest = true;
			}
		}
	}
	if (sendRequest) {
		$.getJSON('/api/js/poll.php', handlerStack, function(aData) { oMasterPoll._respons(aData); });
	} else {
		this.tout = setTimeout('oMasterPoll.start()', this.schedual);
	}
}

/**
 * Passes the feedback from the server to each of the handlers
 */
poll.prototype._respons = function(aData) {
	if (aData != false) {
		for (iDataKey in aData) {
			this.handlers[iDataKey].run(aData[iDataKey]);
		}
	}
	this.tout = setTimeout('oMasterPoll.start()', this.schedual);
}

/**
 * Add a new handler
 */
poll.prototype.regHandler = function(oHandler) {
	this.handlers[oHandler.id] = oHandler;
}

/**
 * The poll handler class should be used to wrap functions to handle feedback from the poll script
 */
function pollHandler(fCallback, iId) {
	this.active = false;
	this.run = fCallback;
	this.schedual = 5000;
	this.id = iId;
	this.params = function() { return 1; };
	this.counter = this.schedual;
}

/**
 * Add a new handler
 */
pollHandler.prototype.setSchedual = function(iMiliseconds) {
	this.schedual = iMiliseconds;
	this.counter = this.schedual;
}

/**
 * Enable this handler, i.e. make the requests
 */
pollHandler.prototype.enable = function() {
	this.active = true;
	this.counter = this.schedual;
}

/**
 * Disable this handler, i.e. do not make the requests
 */
pollHandler.prototype.disable = function() {
	this.active = false;
	this.counter = 0;
}

/**
 * Toggle the handler's enabled status
 */
pollHandler.prototype.toggle = function() {
	if (this.active) {
		this.disable();
	} else {
		this.enable();
	}
}

// Start polling the server for new data once the browser is ready
if (bIsLogedIn) {
	$(document).ready(function(){
	  oPoll = getPoller();
	  oPoll.start();
	});
}

/**
 * chatting functions
 *
 * Used to create and manage dynamic chat boxes
 */

/**
 * Used to allow access to the poller in timeouts
 */
var oMasterChat = null;

/**
 * Always use this to get the poller
 */
function getChatter(sParentElementId) {
	oMasterChat = new chat();
	oMasterChat.parentId = sParentElementId;
	return oMasterChat;
}

function chat() {
	this.rooms = new Array();
	this.allClosed = 0;
	this.chatHandler = new pollHandler(function(aData) { oMasterChat._chatRespons(aData) }, 2);
	this.chatHandler.setSchedual(2000);
	this.chatHandler.params = function() { return oMasterChat.getRUTimes(); };
	this.chatHandler.enable();
	oMasterPoll.regHandler(this.chatHandler);

	this.sUsersToGet = '';
	this.chatUserHandler = new pollHandler(function(aData) { oMasterChat._chatUserRespons(aData) }, 3);
	this.chatUserHandler.params = function() { return oMasterChat.sUsersToGet; };
	oMasterPoll.regHandler(this.chatUserHandler);

	// Get the last message read IDs
	if ($.cookie('llr')) {
		this.getLastLinesRead();
	} else {
		this.lastLinesRead = {};
	}
}

chat.prototype.getLastLinesRead = function() {
	//this.lastLinesRead = 0;
	aTmp = [];
	eval('aTmp = '+$.cookie('llr')+';');

	this.lastLinesRead = new Array();
	for (iKey in aTmp[0]) {
		this.lastLinesRead[aTmp[0][iKey]] = aTmp[1][iKey];
	}
}

chat.prototype.setLastLinesRead = function(iRoomId, iLastLineRead) {
	if (iRoomId) {
		this.rooms[iRoomId].lastLineRead = iLastLineRead;
	}
	sLlrLIds = '[';
	sLlrRIds = '[';
	for (iKey in this.rooms) {
		sLlrRIds += this.rooms[iKey].id+',';
		sLlrLIds += this.rooms[iKey].lastLineRead+',';
	}
	if (sLlrLIds.length == 1) {
		sLlrRIds += ']';
		sLlrLIds += ']';
	} else {
		sLlrRIds = sLlrRIds.substr(0, sLlrRIds.length-1)+']';
		sLlrLIds = sLlrLIds.substr(0, sLlrLIds.length-1)+']';
	}
	$.cookie('llr', '['+sLlrRIds+','+sLlrLIds+']', { expires: 7, path: '/', domain: '.quechup.com' });
}

chat.prototype.getUnreadCount = function() {
	iUnreadCount = 0;
	for (iKey in this.rooms) {
		iUnreadCount += this.rooms[iKey].unreadCount;
	}
	return iUnreadCount;
}

chat.prototype.roomCount = function() {
	iRoomCount = 0;
	for (iKey in this.rooms) {
		iRoomCount++;
	}
	return iRoomCount;
}

chat.prototype.markUnread = function() {
	$('#ChatsMaximize').addClass('chatUnread');
}

chat.prototype.markRead = function() {
	$('#ChatsMaximize').removeClass('chatUnread');
}

chat.prototype.invite = function(iRoomId, iChatUserId, sParentElementId) {
	if (iRoomId != 0) {
		params = { roomid: iRoomId, userid: iChatUserId, pid: sParentElementId }
	} else {
		params = { userid: iChatUserId, pid: sParentElementId }
	}
	$.getJSON('/api/js/chat/invite.php', params, function(aData) { oMasterChat._inviteRespons(aData); });
}

chat.prototype._inviteRespons = function(aData) {
	if (aData['errors'] == '') {
		this.create(aData['roomid'], aData['alias'], aData['pid']);
		if ($.cookie('allchatclosed') == 1) {
			this.allMinimize();
		}
		if ($.cookie('chatopen') != aData['roomid']) {
			$('#ChatsContainer').accordion('activate', this.rooms[aData['roomid']].key);
			$.cookie('chatopen', aData['roomid'], { expires: 7, path: '/', domain: '.quechup.com' });
		}
	} else {
		if (aData['error'] == -2) {
			$.blockUI({ fadeOut: 0, message: '<div id="chatNotFreeZone" class="bgPale"><div class="clearfix"><a href="#" onclick="$.unblockUI(function() { $(\'#chatNotFreeZone\').remove(); }); return false;" class="msgComp-x" title="click to close message window">x</a></div><h5 id="msgWait" class="jhide">'+sTextNoChatFreeZoneTitle+'</h5><div id="msgForm">'+sTextNoChatFreeZoneBody+'</div></div>', css: { top: '133px', width: '600px', left: ( ($(window).width() / 2) - 300) }, applyPlatformOpacityRules: true });
		} else if (aData['error'] == -1) {
			$.blockUI({ fadeOut: 0, message: '<div id="chatNotQConnect" class="bgPale"><div class="clearfix"><a href="#" onclick="$.unblockUI(function() { $(\'#chatNotQConnect\').remove(); }); return false;" class="msgComp-x" title="click to close message window">x</a></div><h5 id="msgWait" class="jhide">'+sTextNoChatQConnectTitle+'</h5><div id="msgForm">'+sTextNoChatQConnectBody+'</div></div>', css: { top: '133px', width: '600px', left: ( ($(window).width() / 2) - 300) }, applyPlatformOpacityRules: true });
		}
	}
}

var iTimeLastDropped = 0;
chat.prototype.create = function(iRoomId, sAlias, sParentElementId) {

	// If a chat box already exists for this room then simply place it in focus
	if ($('#Chat'+iRoomId).is('div')) {
		this.rooms[iRoomId].show();
		$('#Chat'+iRoomId+' .line').focus();
	} else {
		this.rooms[iRoomId] = new room(iRoomId);
		//$('#'+this.parentId).prepend('<div id="Chat'+iRoomId+'" roomid="'+iRoomId+'" class="drop-chats chatConv">'+$('#ChatTemplate').html()+'</div>');
		$('#ChatsMinimize').parent().append('<div id="Chat'+iRoomId+'" roomid="'+iRoomId+'" class="drop-chats chatConv">'+$('#ChatTemplate').html()+'</div>');
		$('#Chat'+iRoomId+' .chatHead').attr('roomid', iRoomId);
		$('#Chat'+iRoomId+' .closebtn').attr('roomid', iRoomId);
		$('#Chat'+iRoomId+' .title').attr('roomid', iRoomId);
		$('#Chat'+iRoomId+' .title').html(sAlias);
		$('#Chat'+iRoomId+' .chatCnt').attr('id', 'ChatCnt'+iRoomId);
		$('#Chat'+iRoomId+' form').submit(function() {
				text = $('#Chat'+iRoomId+' .line').val();
				$('#Chat'+iRoomId+' .line').val('');
				if (text.length == 0) {
					return false;
				}
				oMasterChat.rooms[iRoomId].addLine(iUserId, sUserAlias, text, false, false, "/images/photos/"+sUserAvatar+"35x70");
				oMasterChat.rooms[iRoomId].sendLine(iUserId, sUserAlias, text);
				return false;
			});
		$(".drop-chats").droppable({
				accept: ".friend",
				tolerance: 'pointer',
				activeClass: 'dropActive',
				hoverClass: 'dropHover',
				drop: function(ev, ui) {
					// This has been added to stop the drop event from happening more then once
					// for each drop made. It's not a good solution, just a patch of the symtom,
					// but has been used to expedeate the launch
					oTmpDate = new Date();
					if (oTmpDate.getTime() - iTimeLastDropped > 2000) {
						iTimeLastDropped = oTmpDate.getTime();
						if ($(this).attr('roomid')) {
							chats.invite($(this).attr('roomid'), $(ui.draggable).attr('userid'), 'Chats');
						} else {
							chats.invite(0, $(ui.draggable).attr('userid'), 'Chats');
						}
					}
				}
			});

		if (!this.lastLinesRead[iRoomId]) {
			if ($.cookie('allchatclosed') == 1) {
				this.allMinimize();
			}
			$('#ChatsContainer .bgPale').removeClass('selected');
			$('#Chat'+iRoomId+' .bgPale').addClass('selected');
			$.cookie('chatopen', iRoomId, { expires: 7, path: '/', domain: '.quechup.com' });
		} else {
			if (($.cookie('chatopen') == iRoomId)/* || ($.cookie('chatopen') == -1)*/) {
				//if ($.cookie('chatopen') == -1) {
				//	$.cookie('chatopen', iRoomId, { expires: 7, path: '/' });
				//}
				$('#ChatsContainer .bgPale').removeClass('selected');
				$('#Chat'+iRoomId+' .bgPale').addClass('selected');
			}
		}

		this._initAccordion();
		this.setLastLinesRead();
	}
}

chat.prototype._initAccordion = function() {
	$('#ChatsContainer').accordion({
		active: '.selected',
		selectedClass: 'active',
		autoheight: false,
		alwaysOpen: false,
		header: ".bgPale"
	}).bind("click.bgPale", function(event, ui) {
			if ($('.active', $(this)).length) {
				iTmpRoomId = $('.active', $(this)).attr('roomid');
				$.cookie('chatopen', null);
				$.cookie('chatopen', iTmpRoomId, { expires: 7, path: '/', domain: '.quechup.com' });
				oMasterChat.rooms[iTmpRoomId].viewLatestLine();
				oMasterChat.setLastLinesRead(iTmpRoomId, oMasterChat.rooms[iTmpRoomId].lastLineRecieved);
				oMasterChat.rooms[iTmpRoomId].markRead();
			} else {
				$.cookie('chatopen', 0, { expires: 7, path: '/', domain: '.quechup.com' });
			}
		});
	if (this.allClosed == 1) {
		this.allMinimize(true);
	}
}

chat.prototype.close = function(iRoomId) {
	$('#ChatsContainer').accordion('activate', null);
	this.rooms[iRoomId].close();
	this.rooms[iRoomId].hide();
	$('#Chat'+iRoomId).remove();
	delete this.rooms[iRoomId];
	if (this.roomCount() == 0) {
		$('#ChatsMinimize').addClass('jhide');
		$('#ChatsShadow').addClass('jhide');
		$('#ChatsContainer').removeClass('ChatsBorder');
	}
	this.setLastLinesRead();
}

//not in use as accordian does it all(?)
chat.prototype.minimize = function(iRoomId) {
	wizard.changeAccordion("activate", index + ($(this).is(".next") ? 1 : -1));
	$('#Chat'+iRoomId+' .chatCnt').slideToggle();
}

chat.prototype.allMinimize = function(bNoCookie) {
	if ($('#ActiveChatCount').text() != '0') {
		allMinimisedStatus = 0;
		$('#ChatsMaximize').height($('#Chats').height()-8);
		$('#ChatsMaximize h4').css('marginTop',($('#ChatsMaximize').height()/2)-25);
		$('#Chats').animate( {width: 'toggle'},'fast','',function(){ $('#ChatsMaximize').animate({width: 12, opacity: 'toggle'},'fast'); } );
		if (!bNoCookie) {
			if ($.cookie('allchatclosed') == 0) {
				$.cookie('allchatclosed', 1, { expires: 7, path: '/', domain: '.quechup.com' });
				this.allClosed = 1;
			} else {
				if (this.getUnreadCount() == 0) {
				}
				$.cookie('allchatclosed', 0, { expires: 7, path: '/', domain: '.quechup.com' });
				this.allClosed = 0;
			}
		}
	}
}
/*
chat.prototype.maximize = function() {
	$('#ChatsMinimized').animate({width: 0, opacity: 'toggle'},'fast','', function() {$('#Chats').animate( {width: 'toggle'},'fast'); } );
}
*/

chat.prototype._chatUserRespons = function(aData) {
	if (!aData['errors']) {
		for (iChatUserId in aData['users']) {
			this.rooms[aData['users'][iChatUserId]['r']].addUser(iChatUserId, aData['users'][iChatUserId]['a'], aData['users'][iChatUserId]['f'], aData['users'][iChatUserId]['p']);
			$('#Chat'+aData['users'][iChatUserId]['r']+' .user'+iChatUserId).html(aData['users'][iChatUserId]['a']);
		}
		this.sUsersToGet = '';
		this.chatUserHandler.disable();
	}
}

/**
 * Sorts out the feedback from the server into each of the rooms available
 */
chat.prototype._chatRespons = function(aData) {
	if (!aData['errors']) {
		for (iRoomId in aData['new']) {
			this.create(aData['new'][iRoomId][0]['id'], aData['new'][iRoomId][0]['n'], this.parentId);
			for (iUserKey in aData['new'][iRoomId][1]) {
				this.rooms[iRoomId].addUser(aData['new'][iRoomId][1][iUserKey]['id'], aData['new'][iRoomId][1][iUserKey]['a'], aData['new'][iRoomId][1][iUserKey]['f'], aData['new'][iRoomId][1][iUserKey]['p']);
			}
		}
		chatCount = 0;
		for (iRoomId in aData['rooms']) {
			chatCount++;

			// If the room has not been checked before, then load all posts, otherwise
			// the posts made by this user should be skipped as they should already be
			// present
			if (this.rooms[iRoomId].lastUpdated == 0) {
				for (iLineKey in aData['rooms'][iRoomId][0]) {

					if (aData['rooms'][iRoomId][2]) {
						for (iUserKey in aData['rooms'][iRoomId][2]) {
							this.rooms[iRoomId].addUser(aData['rooms'][iRoomId][2][iUserKey]['id'], aData['rooms'][iRoomId][2][iUserKey]['a'], aData['rooms'][iRoomId][2][iUserKey]['f'], aData['rooms'][iRoomId][2][iUserKey]['p']);
						}
					}

					// If this user exists locally then use it, otherwise, use a default value and request it
					if (!this.rooms[iRoomId].users[aData['rooms'][iRoomId][0][iLineKey]['id']]) {
						if (aData['rooms'][iRoomId][0][iLineKey]['dt']) {
							this.rooms[iRoomId].addLine(aData['rooms'][iRoomId][0][iLineKey]['id'], 'Loading', aData['rooms'][iRoomId][0][iLineKey]['t'], aData['rooms'][iRoomId][0][iLineKey]['dt'], aData['rooms'][iRoomId][0][iLineKey]['lid']);
						} else {
							this.rooms[iRoomId].addLine(aData['rooms'][iRoomId][0][iLineKey]['id'], 'Loading', aData['rooms'][iRoomId][0][iLineKey]['t'], aData['rooms'][iRoomId][0][iLineKey]['lid']);
						}
						this.sUsersToGet = aData['rooms'][iRoomId][0][iLineKey]['id']+','+iRoomId+'|'+this.sUsersToGet;
						this.chatUserHandler.enable();
					} else {
						if (aData['rooms'][iRoomId][0][iLineKey]['dt']) {
							this.rooms[iRoomId].addLine(aData['rooms'][iRoomId][0][iLineKey]['id'], this.rooms[iRoomId].users[aData['rooms'][iRoomId][0][iLineKey]['id']].alias, aData['rooms'][iRoomId][0][iLineKey]['t'], aData['rooms'][iRoomId][0][iLineKey]['dt'], aData['rooms'][iRoomId][0][iLineKey]['lid'], this.rooms[iRoomId].users[aData['rooms'][iRoomId][0][iLineKey]['id']].avatar);
						} else {
							this.rooms[iRoomId].addLine(aData['rooms'][iRoomId][0][iLineKey]['id'], this.rooms[iRoomId].users[aData['rooms'][iRoomId][0][iLineKey]['id']].alias, aData['rooms'][iRoomId][0][iLineKey]['t'], aData['rooms'][iRoomId][0][iLineKey]['lid'], this.rooms[iRoomId].users[aData['rooms'][iRoomId][0][iLineKey]['id']].avatar);
						}
					}
					this.rooms[iRoomId].lastUpdated = aData['rooms'][iRoomId][1];
				}
			} else {
				for (iLineKey in aData['rooms'][iRoomId][0]) {
					if (iUserId != aData['rooms'][iRoomId][0][iLineKey]['id']) {
						if (!this.rooms[iRoomId].users[aData['rooms'][iRoomId][0][iLineKey]['id']]) {
							if (aData['rooms'][iRoomId][0][iLineKey]['dt']) {
								this.rooms[iRoomId].addLine(aData['rooms'][iRoomId][0][iLineKey]['id'], 'Loading', aData['rooms'][iRoomId][0][iLineKey]['t'], aData['rooms'][iRoomId][0][iLineKey]['dt'], aData['rooms'][iRoomId][0][iLineKey]['lid']);
							} else {
								this.rooms[iRoomId].addLine(aData['rooms'][iRoomId][0][iLineKey]['id'], 'Loading', aData['rooms'][iRoomId][0][iLineKey]['t'], aData['rooms'][iRoomId][0][iLineKey]['lid']);
							}
							this.sUsersToGet = aData['rooms'][iRoomId][0][iLineKey]['id']+','+iRoomId+'|'+this.sUsersToGet;
							this.chatUserHandler.enable();
						} else {
							if (aData['rooms'][iRoomId][0][iLineKey]['dt']) {
								this.rooms[iRoomId].addLine(aData['rooms'][iRoomId][0][iLineKey]['id'], this.rooms[iRoomId].users[aData['rooms'][iRoomId][0][iLineKey]['id']].alias, aData['rooms'][iRoomId][0][iLineKey]['t'], aData['rooms'][iRoomId][0][iLineKey]['dt'], aData['rooms'][iRoomId][0][iLineKey]['lid'], this.rooms[iRoomId].users[aData['rooms'][iRoomId][0][iLineKey]['id']].avatar);
							} else {
								this.rooms[iRoomId].addLine(aData['rooms'][iRoomId][0][iLineKey]['id'], this.rooms[iRoomId].users[aData['rooms'][iRoomId][0][iLineKey]['id']].alias, aData['rooms'][iRoomId][0][iLineKey]['t'], aData['rooms'][iRoomId][0][iLineKey]['lid'], this.rooms[iRoomId].users[aData['rooms'][iRoomId][0][iLineKey]['id']].avatar);
							}
						}
					}
					this.rooms[iRoomId].lastUpdated = aData['rooms'][iRoomId][1];
				}
			}
		}

		// Update the chat count & make minimizer vis
		$('#ActiveChatCount').html(chatCount+'');
		if (chatCount!=0) {
			if ($.cookie('allchatclosed') != this.allClosed) {
				this.allClosed = $.cookie('allchatclosed');
				this.allMinimize(true);
			}
			$('#ChatsMinimize').removeClass('jhide');
			$('#ChatsShadow').removeClass('jhide');
			$('#ChatsContainer').addClass('ChatsBorder');
		}
	}
}

/**
 * Get the Room Update Times, which are the times each room last recieved an update
 */
chat.prototype.getRUTimes = function() {
	aRoomTimes = '';
	for (iRoomId in this.rooms) {
		aRoomTimes += iRoomId+'_'+this.rooms[iRoomId].lastUpdated+'-';
	}
	return aRoomTimes;
}

function room(iRoomId) {
	this.assignKeys();
	this.id = iRoomId;
	this.lastAlias = "";
	this.lastLineRecieved = 0;
	this.unreadCount = 0;
	this.users = new Array();
	this.lastUpdated = 0;
	if (oMasterChat.lastLinesRead[iRoomId]) {
		this.lastLineRead = oMasterChat.lastLinesRead[iRoomId];
	} else {
		this.lastLineRead = 0;
	}
}

room.prototype.assignKeys = function() {
	chatCount = 0;
	for (iRoomKey in oMasterChat.rooms) {
		chatCount++;
	}
	this.key = chatCount;
}

room.prototype.addUser = function(iChatUserId, sAlias, sAvatar, iAvatarPresent) {
	this.users[iChatUserId] = new user(iChatUserId, sAlias, sAvatar, iAvatarPresent);
}

room.prototype.delUser = function(iChatUserId, sAlias) {
	delete this.users[iChatUserId];
}

room.prototype.close = function() {
	$.getJSON('/api/js/chat/close.php', { roomid: this.id });
	this.assignKeys();
}

room.prototype.addLine = function(iChatUserId, sAlias, sText, sLineTime, iLineId, sAvatar) {
	if (iUserId == iChatUserId) {
		sCurrentUserClass = " CurrentUser";
	} else {
		sCurrentUserClass = "";
	}
	if (!sLineTime) {
		sLineTime = '';
	}
	if (this.lestAlias != sAlias) {
		this.lestAlias = sAlias;
		if (iUserId != iChatUserId) {
			$('#Chat'+this.id+' .text').append('<div class="clearfix"></div><img src="'+sAvatar+'" align="left" /><h6 class="user'+iChatUserId+''+sCurrentUserClass+'"><div class="date">'+sLineTime+'</div><a href="/profile/view/'+sAlias+'" title="view '+sAlias+'\'s profile">'+sAlias+'</a></h6>'+sText+'<br />');
		} else {
			$('#Chat'+this.id+' .text').append('<div class="clearfix"></div><img src="'+sAvatar+'" align="left" /><h6 class="user'+iChatUserId+''+sCurrentUserClass+'"><div class="date">'+sLineTime+'</div>'+sAlias+'</h6>'+sText+'<br />');
		}
	} else {
		$('#Chat'+this.id+' .text').append(sText+'<br />');
	}
	//go to bottom of scrolling wrapper div to show latest msg
	this.viewLatestLine();

	if (iLineId) {
		this.lastLineRecieved = iLineId;
		if (!$('#Chat'+this.id+' .chatConv').hasClass('active') && (this.lastLineRecieved > this.lastLineRead)) {
			this.markUnread();
		} else if (this.lastLineRecieved > this.lastLineRead) {
			oMasterChat.setLastLinesRead(this.id, this.lastLineRecieved);
		}
	}
}

room.prototype.incUnreadCount = function() {
	this.unreadCount++;
	$('#UnreadLinesCount').html('('+oMasterChat.getUnreadCount()+')');
}

room.prototype.resetUnreadCount = function() {
	this.unreadCount = 0;
	if (oMasterChat.getUnreadCount() == 0) {
		$('#UnreadLinesCount').html('');
	} else {
		$('#UnreadLinesCount').html('('+oMasterChat.getUnreadCount()+')');
	}
}

room.prototype.viewLatestLine = function() {
	if (jQuery.browser.msie && jQuery.browser.version == 7) { // IE7 being a pain in the arse...
		sOffSet = parseInt(($('#Chat'+this.id+' .text').height() - $('#Chat'+this.id+' .txtWrapper').height()+15),10);
		if (sOffSet > 0) {
			$('#Chat'+this.id+' .text').css('marginTop', '-'+sOffSet);
		}
	} else {
		$('#Chat'+this.id+' .txtWrapper').scrollTop($('#Chat'+this.id+' .text').innerHeight());
	}
}

room.prototype.markUnread = function() {
	$('#Chat'+this.id+' .bgPale').addClass('chatUnread');
	if (oMasterChat.allClosed == 1) {
		oMasterChat.markUnread();
	}
	this.incUnreadCount();
}

room.prototype.markRead = function() {
	$('#Chat'+this.id+' .bgPale').removeClass('chatUnread');
	if (oMasterChat.getUnreadCount() == 0) {
		oMasterChat.markRead();
	}
	this.resetUnreadCount();
}

room.prototype.sendLine = function(iChatUserId, sAlias, sText) {
	$.getJSON('/api/js/chat/post.php', { roomid: this.id, text: sText });
}

room.prototype.show = function() {
	$('#Chat'+this.id).show();
}

room.prototype.hide = function() {
	$('#Chat'+this.id).hide();
}

function user(iChatUserId, sAlias, sAvatar, iAvatarPresent) {
	this.valid = 80;
	this.id = iRoomId;
	this.alias = sAlias;
	if (iAvatarPresent) {
		this.avatar = "/images/photos/"+sAvatar+"35x70";
	} else {
		this.avatar = "/api/images/processimage.php?o=1&w=35&h=70&f=/../images/photos/"+sAvatar;
	}
}

/** New notifier functions **/

/**
 * Used to allow access to the notifier in timeouts
 */
var oMasterNotifier = null;

/**ignore_user_abort
 * Always use this to get the poller
 */
function getNotifier(sParentElementId) {
	oMasterNotifier = new notfier(sParentElementId);
	return oMasterNotifier;
}

function notfier(sParentElementId) {
	this.maxItems = 5;
	this.displayDuration = 10000;
	this.container = $(sParentElementId);
	this.newsArea = $(sParentElementId+' div');
	this.hideTimer = null;
	this.container.hoverIntent( function() { clearTimeout(oMasterNotifier.hideTimer); }, function() { oMasterNotifier.hideTimer = setTimeout('oMasterNotifier.hide();', oMasterNotifier.displayDuration); } );
}

notfier.prototype.alert = function(sText, iType) {
	$('div', this.newsArea).slice(this.maxItems-1).remove();
	if (!iType) {
		iType = -1;
	}
	if (iType > -1) {
		this.newsArea.prepend('<div>'+sText+'<div class="txt-sm txt-r"><a href="#" onclick="oMasterNotifier.disableType('+iType+'); $(this).parent().slideUp(); return false;">'+sNewsTextDontShow+'</a><div></div><hr />');
		this.show();
		clearTimeout(this.hideTimer);
		this.hideTimer = setTimeout('oMasterNotifier.hide();', this.displayDuration);
	} else {
		$.blockUI({
			message: '<div class="popup">'+sText+'</div>',
			css: {
				padding: '10px',
				backgroundColor: '#000',
				border: '5px solid #B8B8B8',
				opacity: '0.7',
				color: '#FFFFFF'
			},
			overlayCSS:  {
				opacity: '0'
			}
		});
		$('.blockOverlay').attr('title','Click to unblock').click(function() { $.unblockUI() });

		setTimeout(function() { $.unblockUI() }, 1000);
	}
}

notfier.prototype.show = function() {
	//this.container.show();
	//this.container.animate({ left: "0px" }, "slow");
	this.container.show("slow");
}

notfier.prototype.hide = function() {
	clearTimeout(this.hideTimer);
	this.container.hide("slow", function() {
			oMasterNotifier.newsArea.html('');
		});
	/*this.container.animate({ left: "-150px" }, "slow", function() {
			oMasterNotifier.container.hide();
			oMasterNotifier.newsArea.html('');
		});
	*/
}

notfier.prototype.disableType = function(iType) {
	$.getJSON('/api/js/member/stopNews.php', { m: iType, t: 'Popup' });
}

if (bIsLogedIn) {
	$(document).ready(function() {
		oNotifier = getNotifier('#newsBox');
		newsHandler = new pollHandler(function(aData) { newsRespons(aData) }, 5);
		newsHandler.setSchedual(5000);
		newsHandler.enable();
		oMasterPoll.regHandler(newsHandler);
	});
}

function newsRespons(aData) {
	if (!aData['errors']) {
		for (iNewsKey in aData) {
			if (aData[iNewsKey]['d']['r']) {
				sDesc = getDescription(aData[iNewsKey]['t'], aData[iNewsKey]['a'], aData[iNewsKey]['d']['r']);
			} else {
				sDesc = getDescription(aData[iNewsKey]['t'], aData[iNewsKey]['a'], aData[iNewsKey]['d']);
			}
			oMasterNotifier.alert(sDesc, aData[iNewsKey]['t']);
		}
	}
}

function getDescription(iType, sAlias, aData, bShowFull) {
	msg = '';
	sAlias = '<a href="/profile/view/'+escape(sAlias)+'/">'+sAlias+'</a>';
	switch (iType) {
		case '1':
			msg += sprintf(sNewsTextNewFriend, sAlias);

			// For some reason the array size here of aData always returns 'undefined' this is
			// very odd but not spoken about anywhere online, the following code works around
			// this for the time being
			size = 0;
			for (iFriendKey in aData) {
				size++;
			}
			if (size == 1) {
				if (iFriendKey != iUserId) {
					msg += ' <a href="/profile/view/'+escape(aData[iFriendKey]['a'])+'/">'+aData[iFriendKey]['a']+'</a>.';
				} else {
					msg += sNewsTextYou+'.';
				}
			} else {
				//msg += ': <br />';
				for (iFriendKey in aData) {
					if (iFriendKey != iUserId) {
						msg += ' <a href="/profile/view/'+escape(aData[iFriendKey]['a'])+'/">'+aData[iFriendKey]['a']+'</a>, ';
					} else {
						msg += sNewsTextYou+', ';
					}
				}
				msg = msg.substring(0, msg.length-2);
			}
			break;
		case '2':
			size = 0;
			for (iKey in aData) {
				size++;
			}
			if (size == 1) {
				msg += sprintf(sNewsTextNewBlog, sAlias, iKey);
				for (iKey in aData) {
					if (aData[iKey]['t']) {
						msg += '<br /><a href="/blog/entry/view/id/'+iKey+'/">'+aData[iKey]['t']+'</a>';
					}
				}
			} else {
				msg += sprintf(sNewsTextNewBlogs, sAlias);
				for (iKey in aData) {
					msg += '<br /><a href="/blog/entry/view/id/'+iKey+'/">'+aData[iKey]['t']+'</a>';
				}
			}
			break;
		case '3':
			size = 0;
			for (iKey in aData) {
				size++;
			}
			if (bShowFull) {
				if (size == 1) {
					msg += sprintf(sNewsTextNewPhoto+'<div class="float-l pp" style="width: 80%;"> ', sAlias, iKey);
				} else {
					msg += sprintf(sNewsTextNewPhotos+'<div class="float-l pp" style="width: 80%;"> ', sAlias);
				}
				for (iKey in aData) {
					if (aData[iKey]['p']) {
						msg += '<a href="/gallery/photo/view/id/'+iKey+'/"><img src="/images/photos/'+aData[iKey]['f']+'120x120" alt="'+aData[iKey]['t']+'" class="ph pl" /></a> ';
					} else {
						msg += '<a href="/gallery/photo/view/id/'+iKey+'/"><img src="/api/images/processimage.php?o=1&w=120&h=120&f=/../images/photos/'+aData[iKey]['f']+'" alt="'+aData[iKey]['t']+'"  class="ph pl" /></a> ';
					}
				}
				msg += '</div>';
			} else {
				if (size == 1) {
					msg += sprintf(sNewsTextNewPhotos, sAlias, iKey);
				} else {
					msg += sprintf(sNewsTextNewPhotos, sAlias);
				}
			}
			break;
		case '4':

			if (bShowFull) {
				msg += '<div class="float-l"><a href="/blog/entry/view/id/'+aData['id']+'/"><img src="/images/iconBlog.png" alt="'+aData['t']+'" class="ph pl" /></a></div>';
				msg += '<div sytle="float: left;">'+aData['t']+'</div><div class="float-l newsComment"><q class="rslt-bubble">'+aData['b']+'</q>';
			}

			if (aData['a2'] != sUserAlias) {
				sUserName = ' <a href="/profile/view/'+escape(aData['a2'])+'/">'+aData['a2']+"</a>";
			} else {
				sUserName = sNewsTextYou;
			}
			msg += sprintf(sNewsTextNewBlogComment, sAlias, aData['id'], sUserName);
			if (bShowFull) {
				msg += '</div>';
			}
			break;
		case '5':
			msg += sprintf(sNewsTextProfileUpdated, sAlias);
			break;
		case '6':
			size = 0;
			for (iKey in aData) {
				size++;
			}
			if (bShowFull) {
				if (size == 1) {
					msg += sprintf(sNewsTextNewVideo+'<div class="float-l"> ', sAlias, iKey);
				} else {
					msg += sprintf(sNewsTextNewVideos+'<div class="float-l"> ', sAlias);
				}

				for (iKey in aData) {
					msg += '<a href="/gallery/video/view/id/'+iKey+'/"><img src="'+aData[iKey]['f']+'" alt="'+aData[iKey]['t']+'" class="ph pl" style="width: 120px;" /></a> ';
				}
				msg += '</div>';
			} else {
				if (size == 1) {
					msg += sprintf(sNewsTextNewVideo, sAlias, iKey);
				} else {
					msg += sprintf(sNewsTextNewVideos, sAlias);
				}
			}
			break;
		case '7':
			msg += sprintf(sNewsTextNewMessage, sAlias);
			break;
		case '8':
			// The aData variable for quick messages holds the type index for the message
			switch (aData*1) {
				case iQuickMessageTypeHi:
					msg += sprintf(sQuickMessageTextHi, sAlias);
					msg += '&nbsp;<img src="/images/emoHi.gif" alt="Hi" align="absmiddle" />';
					break;
				case iQuickMessageTypeSmile:
					msg += sprintf(sQuickMessageTextSmile, sAlias);
					msg += '&nbsp;<img src="/images/emoSmile.gif" alt="Smile" align="absmiddle" />';
					break;
				case iQuickMessageTypeWink:
					msg += sprintf(sQuickMessageTextWink, sAlias);
					msg += '&nbsp;<img src="/images/emoWink.gif" alt="Wink" align="absmiddle" />';
					break;
				case iQuickMessageTypeKiss:
					msg += sprintf(sQuickMessageTextKiss, sAlias);
					msg += '&nbsp;<img src="/images/emoKiss.gif" alt="Kiss" align="absmiddle" />';
					break;
				default:
					msg += sprintf(sQuickMessageTextHi, sAlias);
					msg += '&nbsp;<img src="/images/emoHi.gif" alt="Hi" align="absmiddle" />';
			}
			break;
		case '9':
			msg = aData;
			break;
		case '10':
			if (bShowFull) {
				if (aData['p']) {
					msg += '<div class="float-l"><a href="/gallery/photo/view/id/'+aData['id']+'/"><img src="/images/photos/'+aData['f']+'120x120" alt="'+aData['t']+'" class="ph pl" /></a></div>';
				} else {
					msg += '<div class="float-l"><a href="/gallery/photo/view/id/'+aData['id']+'/"><img src="/api/images/processimage.php?o=1&w=120&h=120&f=/../images/photos/'+aData['f']+'" alt="'+aData['t']+'"  class="ph pl" /></a></div>';
				}
				msg += '<div class="float-l newsComment"><q class="rslt-bubble">'+aData['b']+'</q>';
			}

			if (aData['a2'] != sUserAlias) {
				sUserName = ' <a href="/profile/view/'+escape(aData['a2'])+'/">'+aData['a2']+"</a>";
			} else {
				sUserName = sNewsTextYou;
			}
			msg += sprintf(sNewsTextNewPhotoComment, sAlias, aData['id'], sUserName);

			if (bShowFull) {
				msg += '</div>';
			}
			break;
		case '11':
			msg += sprintf(sNewsTextNewInvite, sAlias);
			break;
		case '13':
			if (bShowFull) {
				msg += '<div class="float-l"><a href="/gallery/video/view/id/'+aData['id']+'/"><img src="'+aData['f']+'" width="120" alt="'+aData['t']+'" class="ph pl" /></a></div>';
				msg += '<div class="float-l newsComment"><q class="rslt-bubble">'+aData['b']+'</q>';
			}

			if (aData['a2'] != sUserAlias) {
				sUserName = ' <a href="/profile/view/'+escape(aData['a2'])+'/">'+aData['a2']+"</a>";
			} else {
				sUserName = sNewsTextYou;
			}
			msg += sprintf(sNewsTextNewVideoComment, sAlias, aData['id'], sUserName);

			if (bShowFull) {
				msg += '</div>';
			}
			break;
		case '14':
			msg += sprintf(sNewsTextNewStatus, sAlias, aData);
			break;
		case '15':
			if (bShowFull) {
			}
			msg += sprintf(sNewsTextTaggedYou, sAlias);
			msg += aData['t'];
			break;
	}
	return msg;
}

/**
 * image rotating functions
 */

var rotating = false;
function rotate(oSourceImg, sDirection) {
	if (rotating === false) {
		rotating = oSourceImg;
		photoMan = rotating.siblings('.photoManDiv');
		photoMan.hide();
		rotating.after('<div id="rotatingMessage" class="rotatingImage"><img src="/images/ajax-loader.gif" align="absmiddle" border="0"> Rotating...</div>');
		height = oSourceImg.height();
		width = oSourceImg.width();
		// settings for photoManDiv width and height
		pmWidth = height + 12;
		pmTop = width - 7;
		$('#rotatingMessage').height(height);
		$('#rotatingMessage').width(width);
		rotating.hide();
		rotating.one('load', null, function() {
				if (rotating !== false) {
					$('#rotatingMessage').remove();
					rotating.show();
					photoMan.show();
					rotating = false;
				}
			});

		// The 'rand' paramiter is being sent to stop the browser caching the image
		if (sDirection == 'right') {
			rotating.attr('src', '/api/images/processimage.php?f='+oSourceImg.attr('photoid')+'&o=2&a=90&rand='+Math.random());
			rotating.width(height);
			rotating.height(width);
			photoMan.find('a.icoClock').css('top', pmTop);
			photoMan.find('a.icoCounter').css('top', pmTop);
			photoMan.css('width', pmWidth);
		} else {
			rotating.attr('src', '/api/images/processimage.php?f='+oSourceImg.attr('photoid')+'&o=2&a=270&rand='+Math.random());
			rotating.width(height);
			rotating.height(width);
			photoMan.find('a.icoClock').css('top', pmTop);
			photoMan.find('a.icoCounter').css('top', pmTop);
			photoMan.css('width', pmWidth);
		}
	} else {
		alert(sErrorRotateBussy);
	}
}

/**
 * image cropping functions
 */

function crop(oSourceImg, iX, iY, iW, iH) {
	oSourceImg.attr('cropping', 1);
	oSourceImg.after('<div id="croppingMessage" class="croppingImage" style="border: 1px solid black;">cropping...</div>');
	$('#croppingMessage').height(oSourceImg.height())
	$('#croppingMessage').width(oSourceImg.width())
	oSourceImg.hide();
	oSourceImg.one('load', null, function() {
			$('.croppingImage', $(this).parent()).remove();
			$(this).show();
			$(this).attr('cropping', 0);
		});

	// The 'rand' paramiter is being sent to stop the browser caching the image
	oSourceImg.attr('src', '/api/images/processimage.php?f='+oSourceImg.attr('photoid')+'&o=3&x='+iX+'&y='+iY+'&w='+iW+'&h='+iH+'&rand='+Math.random());
}

/**
 * paging functions
 */

function paging(iCurrentPage, iItemCount, iItemsPerPage, fCallBack, sTarget) {
	sPagingHtml = '';

	if (iItemCount == iItemsPerPage) {
		iPages = iCurrentPage+1;

		if (iPages < 3) {
			iPages = 3;
		}
	} else {
		iPages = iCurrentPage;
	}

	for (i=1; i<=iPages; i++) {
		if (i != iCurrentPage) {
			//sPagingHtml += '<a href="#" onclick="$(\''+sTarget+' table\').fadeOut(\'fast\', function() { '+sprintf(fCallBack, i)+'; }); return false;">'+i+'</a>&nbsp;';
			sPagingHtml += '<a href="#" onclick="'+sprintf(fCallBack, i)+'; return false;">'+i+'</a>&nbsp;';
		} else {
			sPagingHtml += '<span class="pageCur">'+i+'</span>&nbsp;';
		}
	}

	return sPagingHtml;
}

function getDistance(lat1, lng1, lat2, lng2) {
	xdiff = Math.abs(lat1 - lat2);
	ydiff = Math.abs(lng1 - lng2);

	// find approximate distance in metres
	dist = Math.sqrt(Math.pow(xdiff,2) + Math.pow(ydiff,2));
	// convert to miles
	km    = Math.round(dist * 0.001);
	miles = Math.round(dist * 0.000621371192);
	// create output array
	dist = {"km": km , "miles": miles};
	return dist;
}

function addUBUser(iBlockUserId) {
	if (confirm('Are you sure you wish to block all contact from this member?')) {
		$.getJSON('/api/js/member/adduserblock.php', { uid: iBlockUserId }, function(aData) { addUBUserRsp(aData); });
	}
}

function addUBUserRsp(aData) {
	if (!aData['error']) {
		$('.blockedUserAdd'+aData['uid']).hide();
		$('.blockedUserDel'+aData['uid']).show();
		$('.contactUserBox'+aData['uid']).slideUp();
		oMasterNotifier.alert('Member successfully added to your Blocked User List.<br /><a href="/member/privacy/">Manage my list</a>', -1);
	}
}

var aDelUBU = '';
function delUBUData(iBlockedUserId) {
	if (!iBlockedUserId) {
		aDelUBU = '';
		$('input:checked', $('#blocklist')).each(function() { aDelUBU += ','+$(this).val(); });
		$.getJSON('/api/js/member/deluserblock.php', { d: aDelUBU }, function(aData) { delUBUDataRsp(aData); });
	} else {
		if (confirm('Are you sure you wish to allow this member to contact you again?')) {
			$.getJSON('/api/js/member/deluserblock.php', { d: ','+iBlockedUserId }, function(aData) { delUBUDataRsp(aData); });
		}
	}
}

function delUBUDataRsp(aData) {
	if (!aData['error']) {
		$('input:checked', $('#blocklist')).parent().parent().slideUp(function() { $('input:checked', $('#blocklist')).parent().parent().remove() ;});
		$('#rspmessage').slideUp();
		$('.blockedUserDel'+aData['uid']).hide();
		$('.blockedUserAdd'+aData['uid']).show();
		$('.contactUserBox'+aData['uid']).slideDown();
		oMasterNotifier.alert('Member successfully removed from your Blocked User List.<br /><a href="/member/privacy/">Manage my list</a>', -1);
	}
}

/**
 * Cookie plugin
 *
 * Copyright (c) 2006 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */

/**
 * Create a cookie with the given name and value and other optional parameters.
 *
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Set the value of a cookie.
 * @example $.cookie('the_cookie', 'the_value', { expires: 7, path: '/', domain: 'jquery.com', secure: true });
 * @desc Create a cookie with all available options.
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Create a session cookie.
 * @example $.cookie('the_cookie', null);
 * @desc Delete a cookie by passing null as value. Keep in mind that you have to use the same path and domain
 *       used when the cookie was set.
 *
 * @param String name The name of the cookie.
 * @param String value The value of the cookie.
 * @param Object options An object literal containing key/value pairs to provide optional cookie attributes.
 * @option Number|Date expires Either an integer specifying the expiration date from now on in days or a Date object.
 *                             If a negative value is specified (e.g. a date in the past), the cookie will be deleted.
 *                             If set to null or omitted, the cookie will be a session cookie and will not be retained
 *                             when the the browser exits.
 * @option String path The value of the path atribute of the cookie (default: path of page that created the cookie).
 * @option String domain The value of the domain attribute of the cookie (default: domain of page that created the cookie).
 * @option Boolean secure If true, the secure attribute of the cookie will be set and the cookie transmission will
 *                        require a secure protocol (like HTTPS).
 * @type undefined
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */

/**
 * Get the value of a cookie with the given name.
 *
 * @example $.cookie('the_cookie');
 * @desc Get the value of a cookie.
 *
 * @param String name The name of the cookie.
 * @return The value of the cookie.
 * @type String
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */
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 validateForm() {
	var isValid = true;
	$('.required').each(function() {
			$('.error', $(this).parent()).remove();
			if ($(this).val() == '') {
				$(this).focus();
				$(this).parent().append('<span class="error">This field is required.</span>');
				isValid = false;
			}
		});
	return isValid;
}

function membersOnly() {
	$.blockUI({ fadeOut: 0, message: '<div id="membersOnly" class="bgPale"><div class="clearfix"><a href="#" onclick="$.unblockUI(function() { $(\'#membersOnly\').remove(); }); return false;" class="msgComp-x" title="click to close message window">x</a></div><h5>Quechup Members Only</h5> This feature is restricted to Quechup Members only. To access this <button type="button" class="frmBtn" onmousedown="window.location=\'/join/\';">Register now</button></div>', css: { top: '133px', width: '600px', left: ( ($(window).width() / 2) - 300) }, applyPlatformOpacityRules: true });
}

function premiumOnly() {
	$.blockUI({ fadeOut: 0, message: '<div id="premiumOnly" class="bgPale"><div class="clearfix"><a href="#" onclick="$.unblockUI(function() { $(\'#premiumOnly\').remove(); }); return false;" class="msgComp-x" title="click to close message window">x</a></div><h5>Premium Members Only</h5> This feature is restricted to Premium Members only. To access this <button type="button" class="frmBtn" onmousedown="window.location=\'/member/subscribe/\';">Upgrade now</button></div>', css: { top: '133px', width: '600px', left: ( ($(window).width() / 2) - 300) }, applyPlatformOpacityRules: true });
}

function setStatusText(sStatusText) {
	if (!sStatusText) {
		sStatusText = '';
	} else if (sStatusText == sTextDoingNow) {
		sStatusText = '';
	}
	$.getJSON("/api/js/member/setstatustext.php", { st: sStatusText }, function() { oMasterNotifier.alert('Your status has been changed', -1); });
}
