/**
 * App javascript functions
 *
 * @package    UTPC
 * @subpackage javascript
 * @author     Real Deal Marketing, www.realdealmarketing.net
 * @copyright  All rights reserved
 * @version    1.0
 */

if (typeof(asyncUrl) == 'undefined')
{
	var asyncUrl = '/async/';
}

var app =
{
	to: null,			/* main timeout object */
	interval: 60000, 	/* timeout interval in miliseconds */
	max_count:  100, 	/* how long to refesh before stop refreshing (user is gone) so it will refresh for max_count * interval miliseconds */
	counter:      0,	/* Refresh counter */

/**
 * Display error message if async controller fails
 *
 */
	requestError: function (s)
	{
		str = 'Sorry, there was an error. ';
		if (typeof(s) != 'undefined')
		{
			str += s;
		}
		sysMessage.addError (str);
	},

/**
 * Application updats, mainly to refresh session and / or load system messages and notifications
 *
 */
	updates: function (params)
	{
		if (typeof(params) == 'undefined') 	{ var params = ''; }

		$.ajax({
			type: "GET",
			url: asyncUrl,
			cache: false,
			data: "c=application"+params,
			success: function(msg)
			{
				$("#appUpdatesContainer").html(msg);
				var status = msg.substring(0, 1);
				var text   = msg.substring(1,msg.length);
				$("#sysMsgContainer .infoNotification").remove();
				if (status == "1")	 { sysMessage.add(text, "Notification"); }
				else if (status > 0) { sysMessage.addMessage (text); }
			}
		});

		if (this.counter++ > this.max_count) { this.stop(); }
	},

/**
 * Show "quick add" container and set focus to input field
 *
 */
	quickAdd: function ()
	{
		$('#quickAddContainer').show();
		$('#quickAddName').focus();
	},

/**
 * submit "quick add" form
 *
 */
	quickAddSubmit: function (a)
	{
		if (a == 'new')	{ $("#quickAddForm #quickAddAction").val(a); }
		else			{ $("#quickAddForm #quickAddAction").val('add-quick'); }

		$("#quickAddForm").submit();
	},

/**
 * Clear timeout and stop any further timout action
 *
 */
	stop: function ()
	{
		clearInterval (this.to);
		this.to = null;
	},

/**
 * Which settings content is currently loaded
 *
 */
	settings_loaded: '',

/**
 * load custom settings content
 *
 */
	loadSettings:function (v)
	{
		if (this.settings_loaded != v)
		{
			this.settings_loaded = v;
			async.load ("c=settings&a="+v,'settingsContainer .content');
		}

		$("#settingsContainer").slideDown('fast');
	},

/**
 * Hide settings container
 *
 */
	hideSettings: function ()
	{
		$("#settingsContainer").slideUp('fast');
	},

/**
 * Init drop down containers
 *
 */
	DropDownContainer:
	{
		init: function()
		{
			$(".dropdownLink").click (function (e) {
				$('#'+this.id+'DropdownContainer').toggle();
/*
				if ($('#'+this.id+'DropdownContainer').is(':visible')) {	$('#'+this.id+'DropdownContainer').slideUp();
				} else { $('#'+this.id+'DropdownContainer').slideDown(); }
*/
				return false;
			});
		}
	},

/**
 * Display tooltips for all elements with class ".tooltip" and title set
 */
	tooltip: function()
	{
		var xOffset=10;
		var yOffset=20;
		$(".tooltip").hover (
			function(e)
			{
				this.t = this.title;
				this.title = "";
				$("body").append("<p id='tooltip'>"+ this.t +"</p>");
				$("#tooltip").css("top",(e.pageY - xOffset) + "px")	.css("left",(e.pageX + yOffset) + "px").show(); //fadeIn("fast");
			},
			function()
			{
				this.title = this.t;
				$("#tooltip").remove();
			}
		);
		$(".tooltip").mousemove(function(e)
		{
			$("#tooltip").css("top",(e.pageY - xOffset) + "px").css("left",(e.pageX + yOffset) + "px");
		});
	},

	doc:
	{
		toggle: function (id)	{ $(id).toggleClass('invisible'); },
		show: function (id)	{ $(id).removeClass('invisible'); },
		hide: function (id)	{ $(id).addClass('invisible');   },
		toggleSlide: function (id, speed)
		{
			if (!is_defined(speed))	{ speed = 'fast'; }
			if ($(id).hasClass('invisible'))
			{
				$(id).slideDown(speed).removeClass('invisible');
			}
			else
			{
				$(id).slideUp(speed).addClass('invisible');
			}
		},
		showSlide: function (id)	{ $(id).slideDown().removeClass('invisible'); },
		hideSlide: function (id)	{ $(id).slideUp().addClass('invisible');   },
		scrollTo:  function(id, speed)
		{
			id 	  = isset(id) ? id : 'body';
			speed = isset(speed) ? speed : 500;
			var offset = $(id).offset();
			$("html:not(:animated),body:not(:animated)").animate({ scrollTop: offset.top}, speed);
		}
	},

/**
 * Display countdown and execute callback function
 *
 * obj 		- object to show actual number
 * from 	- countdown from
 * to		- countdown until 'to'
 * callback - function to call if reach 'to'
 * @return bool
 */
	countdown: function(obj, from, to, callback)
	{
		$('#' + obj).html(from);
		if (from > to)
		{
			from = from - 1;
			setTimeout("app.countdown('" + obj + "', " + from + ", " + to + ", '" + callback+ "')", 1000)
		}
		else
		{
			if (typeof(callback) != 'undefined')	{ eval(callback); }
		}
	},

/**
 * Initialize and start application
 */
	start: function ()
	{
		$("#quickAddToggle").click (function (e) { app.quickAdd(); });

		if (user_id > 0)
		{
			// set update interval
			this.to = setInterval("app.updates('&a=check-messages')", this.interval);
		}

		// initialize all inline editable fields
		$('.editableText').inlineEdit();

		// initialize tooltips
		app.tooltip();

		app.DropDownContainer.init ();

		// start object
		wld.start();

		sysMessage.start();
	}
};


/**
 * ==========================================================================================================
 *
 * WLD (WhiteLabelDating) javascript functions
 *
 * @package    UTPC
 * @subpackage javascript
 * @author     Real Deal Marketing, www.realdealmarketing.net
 * @copyright  All rights reserved
 * @version    1.0
 *
 * ==========================================================================================================
 */

var wld = {

/**
 * Users related js functions
 *
 */
	Users:
	{
		id: 0,
		show: '',
		print: 0,
		user_loaded: false,

		profile:
		{
			view: function (id)
			{
				async.load ('c=profile&a=view&id='+id, 'data', true);
			},

			statusEdit:function ()
			{
				var w = parseInt($("#statusText").width());

				if (w < 250)
				{
					w = 250;
				}

				$("#user_status").css('width', w+'px');
				$("#statusText").toggle();
				$("#statusEdit").toggle();
				if ($("#user_status").is(":visible"))
				{
					$('#user_status').select().focus();
				}
			},

			statusUpdate: function ()
			{
				var a = $("#user_status").val();
				if (a != '')
				{
					if ($('#statusText').text() != a)
					{
						async.load ('c=user&a=update_status&status='+a, 'statusText');
					}
					this.statusEdit();
				}
				else
				{
					alert ("Please enter text");
				}
			}

		},

		checkUsername: function(msg)
		{
			msg = isset(msg) ? msg : 'Please, insert desired screen name';
			var u = $("#signup_username").val();
			if (u == "") 	{ return $('#usernameAvailableResponse').text(msg); }
			async.load ("c=register&a=check-username&username=" + u, "usernameAvailableResponse");
		},

		changeUsername: function ()
		{
			async.load ('c=account_edit&a=change-username', 'dialogContainer .content', true);
		},

		init: function (id, show, print)
		{
			this.id   = (isNaN(id) || typeof(id) == 'undefined') ? 1 : parseInt(id);
			this.show = (isNaN(show) || typeof(show) == 'undefined') ? '' : show;
			this.print= (isNaN(print) || typeof(print) == 'undefined') ? 0 : 1;
		}
	},

/**
 * inline select functions
 *
 */
	InlineSelect:
	{
		toggle: function (what, id)
		{
			var refS = "#inline"+what+"Select"+id;
			var refO = "#inline"+what+"Options"+id;
			$(".inlineOptions").not(refO).hide();

			if ($(refO).is(':visible'))
			{
				$(refO).hide();
			}
			else
			{
				var offset = $(refS).offset();
				var sh     = $(refS).height();
				$(refO).css('left', offset.left+'px', 'top', offset.top+sh+'px').show();
			}
		},

		hide: function (what, id)
		{
			$("#inline"+what+"Options"+id).hide();
		},

		submit: function (c, what, id, v)
		{
			var refS = "#inline"+what+"Select"+id;
			var refO = "#inline"+what+"Options"+id;
			var t = $(refO+" #opt"+v).html();
			$(refO+" LI.selected").removeClass('selected');
			$(refO+" #opt"+v).addClass('selected');

			if ($(refS).html() == t)
			{
				wld.InlineSelect.hide(what, id);
			}
			else
			{
				$.ajax({
					type: "GET",
					url: asyncUrl,
					cache:false,
					data: "c="+c+"_inline_update&a="+what+"&id="+id+"&v="+ v,
					success: function(msg)
					{
						if (msg != "1") { sysMessage.addWarning (what+" not updated, "+msg); }
						else 			{ sysMessage.addMessage (what+" updated"); $(refS).html(t); }

						wld.InlineSelect.hide(what, id);
					},
					error: function(msg) { app.requestError(); }
				});
			}
		}

	},

/**
 * Drag and drop related js functions
 *
 */
	DragAndDrop:
	{
		init: function()
		{
			$(".dndw").draggable({helper: 'clone', scroll: true});

			$(".dnddroppable").droppable({
				accept: ".dndw",
				activeClass: 'droppable-active',
				hoverClass: 'droppable-hover',
				drop: function(ev, ui) { wld.add($(ui.draggable).attr('id')); }
			});
		}
	},

/**
 * Load list of users
 *
 */
	loadUsers: function (name)
	{
		async.load ('c=users&a=select&name='+name, 'usersContainer', true);
	},


/**
 * Main GK init function
 *
 */

	controller: 'home',

	init: function (controller)
	{
		this.controller = controller;
	},

	start: function ()
	{
	},


/**
 * Inbox functions
 *
 */
	Messages:
	{
		function_loaded: false,

		handler: function (new_hash, initial)
		{
			if (!initial || location.hash != '')
			{
				PN_page = PN_Navigator.getPageFromUrl();
				var thread_id = 0;
				if (location.hash.match('&thread'))
				{
					var temp = new Array();
					temp = location.href.split('#');
					if (typeof(temp[1]) != "undefined")
					{
						temp = temp[1].split('&');
						if (typeof(temp[1]) != "undefined")
						{
							thread_id = parseInt(temp[1].replace('thread', ''));                                            
							async.load ('c=message&thread_id='+thread_id, 'messages', false, 'wld.Messages.loadMessages()');
							return false;
						}
					}
				}

				async.load ('c='+ controller +'&page=' + PN_page, 'results');
				$('#messages').html('').slideUp();
				$('#threads').slideDown();
				PN_Navigator.update();
			}
		},

		loadMessages: function()
		{
			$('#threads').slideUp();
			$('#messages').slideDown();
		},

		showThreads: function()
		{
			$('#messages').html('').slideUp();
			$('#threads').slideDown();
			PN_page = PN_Navigator.getPageFromUrl();
			location.hash = "#page" + PN_page;
		},

		loadThread: function (id)
		{
			if ($("#thread_" + id).hasClass("unread"))
			{
				$("#thread_" + id).removeClass ('unread').addClass ('read');
				$("#thread_" + id + " h5 strong").removeClass ('msgUnread').addClass('msgRead');
			}
			PN_page = PN_Navigator.getPageFromUrl();
			var append2hash= "&thread" + id;
			location.hash = "#page" + PN_page + append2hash;
		},

		earlierMessages: function (id, page)
		{
			$.ajax({
				type: "POST",
				url: asyncUrl,
				data: 'c=message&a=earlier-messages&thread_id=' + id + '&page=' + (parseInt(page) + 1),
				success: function(msg)	{ $('#threadMessages').prepend(msg); },
				error: function(msg) 	{ sysMessage.addError(msg); }
			});
		},

		sendMessageForm: function(obj, username)
		{
        	async.post.exec ('c=message&a=new&username='+username, 0 , "$('#dialogContainer .content').html(msg);", 'sysMessage.addError(msg.substr(1))');
		},

		hideOnClick: function(child_el, parent_el, class_name)
		{
			$('body').bind("click", function (e)
			{
				if (!$(e.target).hasClass(class_name) && $('#' + child_el).length > 0 && $(e.target).parents('#' + parent_el).length == 0)
				{
					$('#' + parent_el).hide();
				}
			});

		},
		sendNewMessage: function(error_msg)
		{
			if (this.validateMessageForm(error_msg) != false)
			{
				$('#send_message_btn1').hide();
                var please_wait_id = 'please_wait_' + $('#form_send_message_btn1').attr('id');
                $('#form_send_message_btn1').prepend("<span id='" + please_wait_id + "'>please wait...</span>");

                if ($('#dialogContainer form').serialize())
                {
					async.post.exec ($('#dialogContainer form').serialize(), 1 , "wld.Messages.reloadThreads();", 
                    	"$('#"+please_wait_id+"').remove();$('#send_message_btn1').show(); $('#send_message_btn1').blur()");
                    return false;
				}
                return true;
			}
		},

		validateMessageForm: function(error_msg)
		{
			if ($.trim($('#send_message_body').val()) != '' || $.trim($('#reply_text').val()) != '') return true;
			alert(error_msg);
			$('#send_message_body').focus();
			$('#reply_text').focus();
			return false;
		},

		replyMessage: function(error_msg)
		{
			if (this.validateMessageForm(error_msg) != false)
			{
				var id = $('#thread_id').val();
                async.post.exec ($('#reply_message').serialize(), 0,  "$('#replyResponse').html(msg);", 'sysMessage.addError(msg.substr(1))');
			}
		},

		updateAfterReply: function()
		{
			$('#reply_text').val('');
			$('#threadMessages').append($('#lastMessage').html());

			if ($('#lastMessage .messageBody').length > 0)
			{
				var num_of_messages = parseInt($('.threadInfo #num_of_messages').html());
				var thread_info = $('.threadInfo').html();
				thread_info = thread_info.replace(num_of_messages, (num_of_messages + 1));
				$('.threadInfo').remove();
				$('#earlierMessages').before('<p class="threadInfo">' + thread_info + '</p>');
			}
			sysMessage.start();
		},

		select: function(type)
		{
			switch (type)
			{
				case "none":
					$('#threads input[type="checkbox"]').attr("checked", "");
				break;
				case "read":
					$('#threads li.read input[type="checkbox"]').attr("checked", "checked");
					$('#threads li.unread input[type="checkbox"]').attr("checked", "");
				break;
				case "unread":
					$('#threads li.unread input[type="checkbox"]').attr("checked", "checked");
					$('#threads li.read input[type="checkbox"]').attr("checked", "");
				break;
				default:
					$('#threads input[type="checkbox"]').attr("checked", "checked");
				break;
			}

			this.toggleAction();
		},

		show: function(type)
		{
			switch (type)
			{
				case "read":
					$('#threads li.unread').hide();
					$('#threads li.read').show();
					$('#threads .filtered P').hide();
					$('#threads .filtered P.read').show();
				break;
				case "unread":
					$('#threads li.unread').show();
					$('#threads li.read').hide();
					$('#threads .filtered P').hide();
					$('#threads .filtered P.unread').show();
				break;
				default:
					$('#threads li').show();
					$('#threads .filtered P').hide();
				break;
			}

			this.toggleAction();
		},

		action: function(action, msg)
		{
			if (action == 'delete-message' && !confirm(msg))
			{
				return false;
			}
			var page = (isNaN(PN_page) || typeof(PN_page) == 'undefined') ? 1 : PN_page;
			var data = ($('#threads input[type="checkbox"]:checked').serialize());
			async.load ('c=inbox&a=' + action + '&' + data + '&page=' + page, 'results');
		},

		deleteThread: function(thread_id, msg)
		{
			if (!confirm(msg))
			{
				return false;
			}
			var page = (isNaN(PN_page) || typeof(PN_page) == 'undefined') ? 1 : PN_page;
			async.exec ('c=inbox&a=delete-message&thread=' + thread_id + '&page=' + page, 0, "wld.Messages.reloadThreads(); wld.Messages.showThreads();", 'sysMessage.addError(msg.substr(1))');
		},

		toggleAction: function()
		{
			$('#threads li').removeClass ('selected');
			if ($('#threads input[type="checkbox"]:checked').length == 0)
			{
				$('.msgActions input[type="button"]').attr('disabled','disabled');
				$('.msgActions input[type="button"]').removeClass('actionButton');
			}
			else
			{
				$('#threads input[type="checkbox"]:checked').parent().parent().addClass ('selected');
				$('.msgActions input[type="button"]').attr('disabled','');
				$('.msgActions input[type="button"]').addClass('actionButton');
			}

		},

		check: function()
		{
			async.load ('c=inbox&a=check-messages', 'appMsgContainer');
		},

		wait: function()
		{
			var wait_text = '<div id="waitInformation">' + $("#session_expired").html() + '</div>';
			$('#please_wait_' + $('#form_send_message_btn1').attr('id')).hide();
			$('#form_send_message_btn1').prepend(wait_text);
			$('#reply_message').append(wait_text);
			$('#send_message_btn1').hide();
			$('#reply_message_button').hide();
			$('#replyResponse').html('');
			sysMessage.clearAll();
			app.countdown('wait_time', $('#wait_time').html(), 0, 'wld.Messages.clearWait();');
		},

		limitReached: function()
		{
			var restriction_text = '<div id="messagesLimitReachedInformation">' + $("#session_expired").html() + '</div>';
			$('#please_wait_' + $('#form_send_message_btn1').attr('id')).hide();
			$('#form_send_message_btn1').prepend(restriction_text);
			$('#reply_message').append(restriction_text);
			$('#send_message_btn1').hide();
			$('#reply_message_button').hide();
			$('#replyResponse').html('');
			sysMessage.clearAll();
		},

		clearWait: function()
		{
			$('#send_message_btn1').show();
			$('#reply_message_button').show();
			$('#waitInformation').remove();
			$('#send_message_body').focus();
			$('#reply_text').focus();
		},
		scrollToReply: function()
		{
			$('html, body').animate({scrollTop: $("#reply_message").offset().top}, 400);
			$('#reply_text').focus();
		},

		listMembers: function(type, container)
		{
			if ($('#' + container).is(':visible'))	{ $('#' + container).slideUp(); } else { $('#' + container).slideDown(); }
			async.once (false, 'c=list_' + type + '&a=list_simple', container);
		},

		reloadThreads: function()
		{
			Dialog.close();
			if ($('#threads').length > 0)
			{
				async.load ('c=inbox', 'results');
			}
		}
	},

/**
 * Photos related functions
 */
	Photos:
	{
		controller: 'photos',
		showAvatar: function () { async.load ('c=' + this.controller + '&a=avatar', 'data'); },
		showPublic: function () { async.load ('c=' + this.controller + '&a=public', 'data'); },
		show: function () { async.load ('c=' + this.controller + '&a=public', 'data'); },
		showEdit: function (id, section)
		{
			var action = (!isset (section) || section == '') ? 'edit' : 'edit-' + section;
			async.load ('c=' + this.controller + '&a=' + action + '&id=' + id, 'data');
		},
		showPending: function () {async.load ('c=' + this.controller + '&a=pending', 'data'); },
		progress: function() { async.load ('c=' + this.controller + '&a=progress', 'public-photos-progress');	},

		Galleries:
		{
			controller: 'photos_album',
			show: function (id) { async.load ('c=' + this.controller + "&a=view&id=" + id, 'data'); },
			showNew: function ()
			{
				var loaded = parseInt ($('#upload_photo_is_new').val(), 10);
				if (!loaded)
				{
					async.load ('c=' + this.controller  + '&a=create', 'data');
				}
			},
			showPending: function (id) { if (typeof(id) == 'undefined') { id = 0; } async.load ('c=' + this.controller + '&a=pending&id=' + id, 'data'); },
			showEdit: function (id, section)
			{
				var action = (!isset (section) || section == '') ? 'edit' : 'edit-' + section;
				async.load ('c=' + this.controller + '&a=' + action + '&id=' + id, 'data');
			},
			progress: function() { async.load ('c=' + this.controller + '&a=progress', 'gallery-photos-progress'); }
		}
	},

/**
 * Flirts
 *
 */
	Flirts: {
		__this__: this,
		controller: 'flirts',

		showForm: function (sender, username)
		{
			async.load ('c=flirts&a=new&username='+username, 'dialogContainer .content', true);
		},

		send: function (sender)
		{
			$('#send_message_btn1').hide();
			var please_wait_id = 'please_wait_' + $('#form_send_message_btn1').attr('id');
			$('#form_send_message_btn1').prepend("<span id='" + please_wait_id + "'>please wait...</span>");
			async.post.exec ($('#flirtFormContainer form').serialize(), 1, "wld.Messages.reloadThreads();", 
                    "$('#"+please_wait_id+"').remove();$('#send_message_btn1').show(); $('#send_message_btn1').blur()");
		},

		toggleCategory: function (sender, id)
		{
			var target = $('#flirtCategory'+id);
			if (target.is(':visible')) return;
			$('.flirtCategory').slideUp();
			target.slideDown();
		},

		toggleFancy: function (sender)
		{
			$('.fancy').removeClass('selected');
			$(sender).addClass('selected');
		}
	},


/**
 * User lists
 *
 */
	UserLists:
	{
		__this__: this,

		/**
		 * Get controller name
		 *
		 * @param	{String}	listName
		 */
		getController: function (listName)
		{
			switch (listName.toLowerCase ())
			{
				case 'favorites':	case 'favoriteFormContainer':	return 'list_favorites';
				case 'blocked':		case 'blockFormContainer':		return 'list_blocked';
				case 'private':		case 'privateFormContainer':	return 'list_private';
				case 'requests':	case 'requestFormContainer':	return 'list_requests';
				case 'ignored':		case 'ignoreFormContainer':		return 'list_ignored';
				case 'reports':		case 'reportFormContainer':		return 'users_reports';
				case 'visits':										return 'autolist_visits';
				case 'favoritized':									return 'autolist_favorites';
			}
		},

		/**
		 * Get list name for list controller
		 *
		 * @param	{String}	controllerName
		 */
		getListName: function (controllerName)
		{
			var container = '';
			switch (controllerName.toLowerCase())
			{
				case 'autolist_history':	container = 'my-visits-data';			break;
				case 'autolist_visits':		container = 'who-visited-me-data';		break;
				case 'list_requests':		container = 'private-requests-data';	break;
				case 'list_private':		container = 'private-data';				break;
				case 'list_blocked':		container = 'blocked-data';				break;
				case 'autolist_favorites':	container = 'who-favorited-me-data';	break;
				case 'list_favorites':		container = 'my-favorites-data';		break;
			}

			var n = $("#" + container);
			return (n.size() > 0) ? container : 'data';
		},

		/**
		 * Display add-to-list form in a modal dialog
		 *
		 * @param	{Object}	sender
		 * @param	{String}	username
		 * @param	{String}	listName
		 */
		showForm: function (sender, username, listName)
		{
			Dialog.load ('c=' + this.getController (listName) + '&a=new&username=' + username, true);
		},

		/**
		 * Shorthand methods for this.showForm
		 *
		 * @param	{Object}	sender
		 * @param	{String}	username
		 */
		favoriteForm:	function (sender, username)	{ this.showForm (sender, username, 'favorites'); },
		blockForm: 		function (sender, username)	{ this.showForm (sender, username, 'blocked'); },
		privateForm:	function (sender, username)	{ this.showForm (sender, username, 'private'); },
		requestForm:	function (sender, username)	{ this.showForm (sender, username, 'requests'); },
		ignoreForm:		function (sender, username)	{ this.showForm (sender, username, 'ignored'); },
		reportForm:		function (sender, username)	{ this.showForm (sender, username, 'reports'); },

		/**
		 * Load specific page of listing
		 *
		 * @param	{String}	controller
		 * @param	{Integer}	page
		 */
		gotoPage: function (controller, page)
		{
			var a = ($('.members_simple_list').length > 0) ? 'list_simple' : '';                      
			async.load ('c=' + controller + '&a=' + a + '&page=' + page, this.getListName (controller));
		},

		/**
		 * Toggle display layout
		 *
		 * @param	{String}	listName
		 * @param	{String}	listType
		 */
		toggleListView:	function (listName, listType)
		{
			$("#toggleColumnView_" + listName).removeClass ('currentView');
			$("#toggleThumbView_" + listName).removeClass ('currentView');
			$("#toggleBrowseView_" + listName).removeClass ('currentView');

			switch (listType)
			{
				case 'browse' :
					$('#list_' + listName).removeClass('columnView').removeClass('thumbView').addClass( 'browse');
					$("#toggleBrowseView_" + listName).addClass ('currentView');
				break;
				case 'column' :
					$('#list_' + listName).removeClass('browse').removeClass('thumbView').addClass ('columnView');
					$("#toggleColumnView_" + listName).addClass ('currentView');
				break;
				case 'thumb' :
					$('#list_' + listName).removeClass('browse').removeClass('columnView').addClass ('thumbView');
					$("#toggleThumbView_" + listName).addClass ('currentView');
				break;
			}

			$.cookie("listView_" + listName, listType);
		},

		/**
		 * Store list layout value in cookie
		 *
		 * @param	{String}	listName
		 */
		setListView: function (listName)
		{
			switch ($.cookie ("listView_" + listName))
			{
				default:
				case 'column':	this.toggleListView (listName, 'column');	break;
				case 'thumb':	this.toggleListView (listName, 'thumb');	break;
				case 'browse':	this.toggleListView (listName, 'browse');	break;
			}
		},

		/**
		 * Add to list
		 *
		 * @param	{Object}	sender
		 */
		add: function (sender)
		{
			var form = $('.addToList form');
			// trim spaces and limit to 255 characters
			form.find('input [type="text"], textarea').each (
				function (idx, el)
				{
					el = $(el);
					el.val($.trim(el.val()).substr (0,255));
				}
			);
			async.post.exec (form.serialize (), 1, "Dialog.close()");
		},

		/**
		 * Remove from list
		 *
		 * @param	{Object}	sender
		 * @param	{String}	username
		 * @param	{String}	listName
		 */
		remove: function (sender, username, listName)
		{
			if (!listName)
			{
				listName = $(sender).parents().filter('div.addToList').attr ('id');
			}

			async.post.exec ('c=' + this.getController (listName) + '&a=delete&username=' + username, 1, "Dialog.close()");

			// remove all previously deleted, since there is only one-level undo
			$('.userList .deleted').remove ();

			this.toggleDisplay (username, listName);
		},

		/**
		 * Remove html elements after succesful removal from db
		 *
		 * @param	{Object}	sender
		 * @param	{String}	listName
		 * @param	{String}	checked
		 */
		__delete: function (sender, listName, checked)
		{
			// remove all previously deleted from DOM
			$('.userList .deleted').remove ();

			// disable undo
			$('.userList .actions .undoLink').addClass ('invisible');
			$('.userList .actions .removeLink').removeClass ('invisible');

			// create list of user IDs
			var userIds = [];
			checked.each (function (idx, el) { userIds[idx] = $(el).val (); });
			userIds = 'user_id[]=' + userIds.join ('&user_id[]=');

			// delete them
			async.post.exec ('c=' + this.getController (listName) + '&a=delete&' + userIds, 1);

			// remove all selected items from DOM
			checked.parents().filter('LI').remove ();
		},

		/**
		 * remove all from list
		 *
		 * @param	{Object}	sender
		 * @param	{String}	listName
		 */
		removeAll: function (sender, listName)
		{
			var checked = $('#list_' + listName + ' :checkbox');
			if (!checked.length)	{ return false; }
			if (!confirm ('This action will remove all from your "' + listName + '" list.'))		{ return false; }
			this.__delete (sender, listName, checked);
		},

		/**
		 * remove selected from list
		 *
		 * @param	{Object}	sender
		 * @param	{String}	listName
		 */
		removeSelected: function (sender, listName)
		{
			var checked = $('#list_' + listName + ' :checked');
			if (!checked.length)	{ return false; }
			if (!confirm ('Are you sure you want to remove selected from your "' + listName + '" list?'))	{ return false; }
			this.__delete (sender, listName, checked);
		},

		/**
		 * Undo remove
		 *
		 * @param	{Object}	sender
		 * @param	{String}	username
		 * @param	{String}	listName
		 */
		undelete: function (sender, username, listName)
		{
			async.post.exec ('c=' + this.getController (listName) + '&a=undo&username=' + username, 1, "Dialog.close()");
			this.toggleDisplay (username, listName);
		},

		/**
		 * toggle Undo / Remove
		 *
		 * @param	{String}	username
		 * @param	{String}	listName
		 */
		toggleDisplay: function (username, listName)
		{
			var userList = $('.userList');
			if (userList.length)
			{
				var userItem = userList.find('#userId_' + username + '_' + listName);
				userItem.toggleClass ('deleted');
				userItem.find('.actions .undoLink').toggleClass ('invisible');
				userItem.find('.actions .removeLink').toggleClass ('invisible');
			}
		},

		/**
		 * Accept request for private list
		 *
		 * @param	{Object}	sender
		 * @param	{String}	username
		 * @param	{String}	listName
		 */
		accept: function (sender, username, listName)
		{
			if (!listName) listName = $(sender).parents().filter('div.addToList').attr ('id');
			async.post.exec ('c='+this.getController(listName)+'&a=accept&username='+username, 1, "Dialog.close()");
			async.load ('c=account&a=list-private', 'data', 1);
		},

		/**
		 * Withdraw request for private list
		 *
		 * @param	{Object}	sender
		 * @param	{String}	username
		 * @param	{String}	listName
		 */
		withdraw: function (sender, username, listName)
		{
			if (!listName)	{ listName = $(sender).parents().filter('div.addToList').attr ('id'); }
			async.post.exec ('c=' + this.getController (listName) + '&a=withdraw&username=' + username, 1, "Dialog.close()");
		}
	},

/**
 * My account
 */
	Account:
	{
		/**
		 * Load current users' progress
		 */
		progress: function () { async.load ('c=account&a=profile-progress', 'aside .profileProgress'); }
	},

/**
 * Napisati komentar gde se ovo koristi
 */
	Shouts:
	{
		load: function(status)
		{
			if (typeof (status) == 'undefined')
			{
				status = '';
			}

			async.load ('c=shouts&a=get&status='+status, 'shoutsContainer');
		},

		reply: function(id, usr)
		{
			if (id == '' || usr == '')
			{
				return false;
			}

			$("input[name='at_shout_id']").val(id);
			$('#shout').val("@" + usr + ' ').focus();
		},

		submit: function()
		{
			var data = $('#formShout').serialize();

			if (data == '')
			{
				return false;
			}
			async.exec ('c=shouts&a=add&' + data, 1, 'wld.Shouts.load()');
		},

		remove: function()
		{
			// not implemented
			return false;
		}
	},

/**
 * Napisati komentar gde se ovo koristi
 */
	Forms:
	{
		inputLimit: function (id, limit, infodiv, msg, error_msg)
		{
			var text 	    = $(id).val();
			var textlength = text.length;

			msg 	   = (isset(msg) || msg != '') 			   ? msg 	   : '';
			error_msg = (isset(error_msg) || error_msg != '') ? error_msg : 'Too long';

			if(textlength >= limit)
			{
				$(infodiv).html(error_msg);
				$(id).val(text.substr(0, limit));
				return false;
			}
			$(infodiv).html((limit - textlength) + msg);
		}
	},

/**
 * Used on members profile page
 */
	Profile:
	{
		getLastShout: function(id)
		{
			if (typeof(id) == 'undefined' || id == '')	{ return; }
			async.load ('c=profile&a=last-shout&id=' + id, 'profileExtendedShout', false);
		}
	},

/**
 * Used in order to control Search forms behavior
 */
	Browse:
	{
		handler: function (new_hash, initial)
		{
			if ( (location.hash == '') || (location.hash == '#') || (location.hash.match('basic;')) || (location.hash.match('advanced;')) || (location.hash.match('interests;')) || (location.hash.match('tab0;')) || (location.hash.match('tab1;')) ) return;

			if (!initial || location.hash != '' || location.hash != '#')
			{
				if (typeof(form_values) == 'undefined') { form_values = ''; }

				PN_page = PN_Navigator.getPageFromUrl();

				if (location.hash.match(';searchbasic'))
				{
					controller = 'search';
					form_values = $('#searchbasic').serialize();
					PN_hash_append = ';searchbasic';
				}

				if (location.hash.match(';searchadvanced'))
				{
					controller = 'search';
					form_values = $('#searchadvanced').serialize();
					PN_hash_append = ';searchadvanced';
				}

				if (location.hash.match(';searchinterests'))
				{
					controller = 'interests';
					form_values = $('#searchinterests').serialize();
					PN_hash_append = ';searchinterests';
				}

				if (location.hash.match(';searchcustom'))
				{
					form_values = $('#searchcustom').serialize();
					PN_hash_append = ';searchcustom';
				}

				var hr = location.href;
				hr = hr.substring(hr.indexOf("?")+1);

				if (form_values == '') form_values = hr;
				async.load ('c='+ controller +'&page=' + PN_page + '&' + form_values, 'results', 1, 'wld.Search.showResults()');

				PN_Navigator.update();
			}
		},

		search: function (id)
		{
			this.hashControl(';'+id);
			async.load ('c=search&a='+id+'&' + $('#search'+id).serialize(), 'results', 1, 'wld.Search.showResults()');
		},

		hashSwitch: function (set2hash)
		{
			PN_hash_append = set2hash;
			location.hash = set2hash;
		},

		hashControl: function (append2hash)
		{
			PN_hash_append = append2hash;
			location.hash = "#page1" + append2hash;
		}
	},

/**
 * Used in Search
 */
	Search:
	{
		showResults: function ()
		{
			$("#searchFormsRefine").slideDown();
		},

		refine: function ()
		{
			$("#searchForms").slideDown();
			$("#searchFormsRefine").slideUp();
			location.hash = '';
		},
		findByUsername: function(username)
		{
			async.load ('c=search&a=by_username&username=' + username, 'results', 1, 'wld.Search.showResults()');
		},
		find: function (id)
		{
			wld.Browse.hashControl(';' + id);
		}
	}
};


/**
 * On document load start app
 *
 */

$(document).ready ( function()
{
	app.start();
});
