// Cache phrases used in this file
window.vBulletin = window.vBulletin || {};
window.vBulletin.phrase = window.vBulletin.phrase || {};
window.vBulletin.phrase.precache = window.vBulletin.phrase.precache || [];
window.vBulletin.phrase.precache = $.merge(window.vBulletin.phrase.precache, [
	'ad_list_description',
	'add_subforum',
	'all',
	'applying_new_template',
	'are_you_sure_want_to_delete_ad_x',
	'cancel',
	'cannot_add_system_module',
	'cannot_remove_system_module',
	'check_to_hide_module',
	'choose_base_module',
	'choose_options_site_logo',
	'click_text_edit_title',
	'confirm_deletion_x',
	'create_new_custom_module',
	'delete',
	'do_you_want_to_cancel_editing_search_module',
	'do_you_want_to_exit_without_saving_page',
	'do_you_want_to_remove_channel',
	'do_you_want_to_remove_forum',
	'do_you_want_to_remove_module',
	'dropping_container_module_into_container_module_not_allowed',
	'drag_and_drop_module_here',
	'edit',
	'edit_custom_html_module',
	'edit_locationx_ad',
	'edit_navigation_item',
	'edit_search_module',
	'edit_site_logo',
	'error_adding_widgets',
	'error_cloning_widget',
	'error_deleting_page',
	'error_fetching_channels',
	'error_processing_site_logo',
	'error_processing_site_logo_image_hosting',
	'error_renaming_module_title',
	'error_retrieving_cloned_widget_template',
	'error_retrieving_configuration',
	'error_retrieving_list_user_groups',
	'error_retrieving_modules',
	'error_retrieving_navigation_bar_configuration',
	'error_retrieving_page_map',
	'error_retrieving_templates',
	'error_saving_forums',
	'error_saving_forums_code',
	'error_saving_configuration_module',
	'error_saving_navigation_bar_configuration',
	'error_saving_page',
	'error_saving_search_config',
	'error_saving_search_config_code',
	'error_saving_site_logo',
	'error_saving_site_logo_code',
	'error_uploading_logo',
	'exit_without_saving_page',
	'input_navigation_item_name',
	'input_target_url',
	'invalid_image_url',
	'main_navigation_bar',
	'make_category',
	'make_forum',
	'module_icon',
	'move_not_allowed',
	'my_custom_modules',
	'new_navigation_item',
	'new_subnavigation_item',
	'next',
	'no_ad_added',
	'no_configurations_found',
	'no_modules',
	'no_permission',
	'none',
	'overwrite_template_continue',
	'page_template_title_cannot_be_empty',
	'page_title_cannot_be_empty',
	'please_choose_overwrite_template_options',
	'please_enter_channel_title',
	'please_enter_new_module_title',
	'please_enter_new_template_name',
	'please_enter_page_name',
	'previous',
	'remove_channel',
	'remove_channel_q',
	'remove_forum',
	'remove_forum_q',
	'remove_module_q',
	'rename',
	'rename_custom_module',
	'save',
	'save_new_page',
	'save_page',
	'search_results',
	'select_edit_link_header',
	'sub_navigation_bar',
	'subchannels_will_be_deleted',
	'switch_template',
	'template_changes_will_be_lost',
	'forum_changes_will_be_lost',
	'this_url_is_already_used',
	'unable_to_delete_widget_instances',
	'uncheck_to_unhide_module',
	'user_group_settings',
	'warning_gcpuser',
	'you_are_here',
	'you_must_specify_a_screen_layout',
	'you_can_also_drag_and_drop_modules_here'
]);

(function($){

	var $pageEditorTabs, $pageManagerTabs, $managePagesTabs, customScrollbars = [];

	function resizePageEditorTabContentWidth(){
		//The Edit/New tab content div on the left (.panel-header-text) has a fixed width,
		//so we have to manually adjust the width of main content div on the right (.panel-main-content)
		//to maintain the fluid layout which has 80% wide content
		var $panelMainContent = $('#edit-page-dropdown .panel .panel-main-content:visible');
		if ($panelMainContent.length > 0) {
			var tabMainContentOuterWidth = parseFloat($panelMainContent.css('margin-left')) +
				parseFloat($panelMainContent.css('margin-right')) +
				parseFloat($panelMainContent.css('border-left-width')) +
				parseFloat($panelMainContent.css('border-right-width')) +
				parseFloat($panelMainContent.css('padding-left')) +
				parseFloat($panelMainContent.css('padding-right'));

			//resize panel main content width
			$('#edit-page-dropdown .panel .panel-main-content').width(
				$('#edit-page-dropdown .panel:visible').width() -
				$('#edit-page-dropdown .panel .panel-header-text:visible').outerWidth(true) -
				tabMainContentOuterWidth - 1);

			//resize form right gutter
			$('#edit-page-dropdown form .form-gutter-right').width(
				Math.ceil(($('#edit-page-dropdown form:visible').width() - $('#edit-page-dropdown .panel:visible').outerWidth(true)) / 2)
			);

			//resize custom scrollbar width
			if (customScrollbars.length) {
				var scrollbars = customScrollbars[$pageEditorTabs.tabs('option', 'selected')];
				if (scrollbars) {
					scrollbars.tinyscrollbar_update();
					// Update Scrollbar's anchor to the offset of selected template/layout if scrollbar is visible or enabled
					var selectedPanel = $("#edit-content > .tabs > .ui-tabs-panel:not(.ui-tabs-hide)");
					var selectedItem = selectedPanel.find('input:checked').closest('.list-item');
					if (selectedItem.length > 0 && !selectedPanel.find('.scrollbar').hasClass('disable')) {
						var selectedOffset = selectedItem.offset().left;
						var scroller = selectedPanel.find('.scroller');
						var scrollerOffset = scroller.offset().left + parseInt(selectedItem.css('margin-left'), 10);
						var selectedAnchor = selectedOffset - scrollerOffset;
						var maxAnchor = selectedPanel.find('.overview').width() - scroller.width();
						if (selectedAnchor > maxAnchor) selectedAnchor = maxAnchor;
						scrollbars.tinyscrollbar_update(selectedAnchor);
					}
				}
			}
		}
	}

	$(document).ready(function(){

		var currentLayout,
			$screenLayoutThumbnails,
			$templateThumbnails,
			sectionCount = [],
			$mainChannelSortable,
			$subChannelSortable,
			hasCanvasChanged = false,
			hasConfigChanged = false,
			channelsChanged = {},
			templatesLoaded = false,
			modulesLoaded = false,
			moduleInstancesLoaded = false,
			templateChanged = false,
			moduleDragStart = false,
			moduleOverCanvas = false,
			searchForm = false,
			newPage = false,
			moduleTemplates = {};


		function initPage(){
			bindFormReset('#edit-page-dropdown form').trigger('reset', function(){
				$('#save-content .template-name').addClass('hide');
				$('input[type=hidden]', this).each(function(){
					 this.value = this.defaultValue;
				});
			});

			//bind click handlers to the top nav bar items
			$('#main-navbar .main-nav .sb-menu a').live('click', function(){
				if (!$(this).hasClass('selected') && !$(document.body).hasClass('edit-mode')) {
					$('#main-navbar .main-nav a').removeClass('selected').closest('li').addClass('disabled');
					$(this).addClass('selected').closest('li').removeClass('disabled');
					$(document.body).addClass('edit-mode ' + this.id).removeClass('view-mode');
					$('#main-navbar ul.secondary-nav').addClass('disabled');
				}
				return false;
			});

			$('#main-navbar li.disabled a, #main-navbar ul.secondary-nav.disabled li, #main-navbar ul.secondary-nav.disabled li a').live('focus click mousedown', function(e){
				this.blur();
				e.stopPropagation();
				return false;
			});

			$('#sitebuilder-wrapper .lnkExitWithoutSaving').live('click', function() {
				if ($(this).closest('#edit-page-dropdown').length == 0) { //exclude New Page and Edit Page dropdown as it has confirm dialog when exiting
					$('#main-navbar ul.secondary-nav').removeClass('disabled');
				}
			});
			var $sbMenuListItem = $('#main-navbar li.sb-menu:not(.disabled)');

			$('#lnkEditPage', $sbMenuListItem).live('click', function()
			{
				if ($('#edit-page-dropdown-gutter').is(':hidden')) {

					vBulletin.assertUserHasAdminPermission('canusesitebuilder', function()
					{
						var hiddenModules = [];
						$('.hidden-widget-placeholder').each(function()
						{
							hiddenModules.push($(this).attr('widget-instance-id'));
						});

						function editPageInit()
						{
							newPage = false;

							onModuleAddOrRemove();
							toggleAllModuleContentVisibility(false, '.container-widget');
							$('.edit-mode .canvas-widget-list .canvas-widget').addClass('shadow');

							//show first tab by default
							$pageEditorTabs.tabs('select', 0);

							$('#header, #header-axd, #save-content').hide();
							$('#edit-content').show();
							$('#edit-page-dropdown .lnkSaveChanges .label').text(vBulletin.phrase.get('save_page'));

							$('#edit-page-dropdown-gutter').removeClass('hide').slideDown('slow', initializePageEditor);
						}

						if (hiddenModules.length == 0) {
							editPageInit();
						}
						else
						{
							//fetch hidden modules
							$.ajax({
								url:pageData.baseurl + '/index.php/ajax/fetch-hidden-modules',
								data: ({
									modules: hiddenModules
								}),
								type: 'POST',
								dataType: 'json',
								complete:function(){
									console.log('fetch-hidden-modules complete.');
									editPageInit();
								},
								success:function(result){
									console.log('fetch-hidden-modules successful! result:' + JSON.stringify(result));
									if ($.isArray(result)){
										if (result.length > 0){
											$.each(result, function(index, widget){
												var $module = $(widget.template).addClass('hidden-widget');

												$('.hidden-widget-placeholder[widget-instance-id="' + widget.widgetinstanceid + '"]')
													.replaceWith($module);
											});
										}
									}
									else { //widgets in the ajax response is not an array
										openAlertDialog({
											'title':vBulletin.phrase.get('error'),
											'message':vBulletin.phrase.get('invalid_server_response_please_try_again'),
											'iconType':'error'
										});
									}
								},
								error:function(xhr, statusText, error){
									console.log('fetch-hidden-modules failed! error:' + error);
									window.vBulletin.loadingIndicator.hide();
									openAlertDialog({
										'title':vBulletin.phrase.get('error'),
										'message':vBulletin.phrase.get('error_retrieving_modules', xhr.status),
										'iconType':'error'
									});
								}
							});
						}
					});
				}
				return false;
			});

			$('#lnkNewPage', $sbMenuListItem).live('click', function()
			{
				if ($('#edit-page-dropdown-gutter').is(':hidden')) {
					vBulletin.assertUserHasAdminPermission('canusesitebuilder', function()
					{
						newPage = true;

						$('.canvas-widget-list').empty();

						//show first tab by default
						$pageEditorTabs.tabs('select', 0);

						//default layout for new page is 70/30
						$('#change-layout .layout-border.selected').removeClass('selected');
						$('#layout-70-30').prev().trigger('click');
						hasCanvasChanged = false; //don't consider it as a canvas change

						$('#header, #header-axd, #save-content').hide();
						$('#edit-content').show();
						$('#edit-page-dropdown .lnkSaveChanges .label').text(vBulletin.phrase.get('save_new_page'));

						$('#edit-page-dropdown-gutter').removeClass('hide').slideDown('slow', initializePageEditor);
					});
				}
				return false;
			});

			$('#lnkHeader', $sbMenuListItem).live('click', function()
			{
				if ($('#admin-navbar-strip-gutter').is(':hidden')) {
					var $header = $('#header');
					var $headerCell = $('.header-cell', $header);
					var $siteLogoEditStrip = $('> .admin-only', $headerCell).addClass('hide-imp');

					vBulletin.assertUserHasAdminPermission('canusesitebuilder', function()
					{
						$('#admin-navbar-strip-gutter')
							.addClass('navbar-header')
							.removeClass('hide')
							.find('.prompt-text').text(vBulletin.phrase.get('select_edit_link_header'));

						//cover page header with overlay except the site logo
						var w = $headerCell.outerWidth();
						var pos = $header.position();
						$('.disable-overlay', $header).css({
							height: $header.innerHeight() + 'px',
							width: ($header.innerWidth() - w)  + 'px',
							left: (pos.left + w) + 'px',
							top: pos.top + 'px',
							display: 'block'
						});

						//locate where Site Logo Edit strip should be positioned (its parent has display:cell, so relative absolute positioning does not work)
						$siteLogoEditStrip
							.css({
								left: pos.left + 'px',
								top: pos.top + 'px',
								width: w - (parseInt($siteLogoEditStrip.css('padding-left')) + parseInt($siteLogoEditStrip.css('padding-right'))) + 'px'
							})
							.removeClass('hide-imp');
					});
				}
				return false;
			});
			$('.edit-mode.lnkHeader #header .site-logo > a').live('focus click mousedown', function(e)
			{
				this.blur();
				e.stopPropagation();
				return false;
			});


			// start navbar & footer edit UI +++++++++++++++++++++++++++++++++++++++++++++++++++++++++
			(function()
			{
				var $editNavbarItem = null;
				var $editNavbarItemContainer = null;
				var $editSubNavbarListContainer = null;
				var rollbackNavbarHTML = '';
				var rollbackSubnavHTML = '';
				var rollbackNavbarURL = '';
				var navbarType = ''; // 'navbar' or 'footer'

				var normalizeUrl = function(rawUrl)
				{
					if (!rawUrl)
					{
						return false;
					}
					if (rawUrl.match(/^https?:\/\//i))
					{
						return rawUrl;
					}

					if (rawUrl.substr(0, 1) == '/')
					{
						return pageData.baseurl + rawUrl;
					}

					return pageData.baseurl + '/' + rawUrl;
				};

				var createNavbarItem = function(itemPhrase, itemName, itemUrl, itemNewWindow, itemUserGroups, addSubnav)
				{
					itemNewWindow = (itemNewWindow == 'checked' || itemNewWindow == 'on' || itemNewWindow == '1' || itemNewWindow == 'true') ? '1' : '0';
					itemUserGroups = itemUserGroups || [];
					console.log('createNavbarItem... Name: ' + itemName + ' Url: ' + itemUrl + ' NewWindow: ' + itemNewWindow + ' UserGroups: ' + itemUserGroups);
					itemName = JShtmlEncode(itemName);

					var $li = $('<li />')
						.append(' <a href="#" class="navbar-item-delete" title="' + vBulletin.phrase.get('delete') + '">X</a> ')
						.append(itemName)
						.append(' <a href="#" class="navbar-item-edit">' + vBulletin.phrase.get('edit') + '</a> ')
						.data('item-phrase', itemPhrase)
						.data('item-name', itemName)
						.data('item-url', itemUrl)
						.data('item-newwindow', itemNewWindow)
						.data('item-usergroups', itemUserGroups);

					if (navbarType == 'footer')
					{
						addSubnav = false;
					}

					if (addSubnav)
					{
						$li.append(' <a href="#" class="navbar-item-opensubnav">&gt;</a> ');
					}

					return $li;
				};

				var getNavbarItemPosition = function($item)
				{
					return $item.prevAll('li').size();
				};

				var updateNavbarDisplay = function($newItem, doAction, movePositions)
				{
					// disable this
					return;
					// disable this

					if (doAction == 'add')
					{
						var targetAttr = $newItem.data('item-newwindow') == '1' ? ' target="_blank"' : '';
						$('#channel-tabbar ul').append('<li><a' + targetAttr + ' href="' + normalizeUrl($newItem.data('item-url')) + '">' + $newItem.data('item-name') + '</a></li>');
					}
					else if (doAction == 'update')
					{
						var targetAttr = $newItem.data('item-newwindow') == '1' ? ' target="_blank"' : '';
						var itemPos = getNavbarItemPosition($newItem);
						var $lis = $('#channel-tabbar ul li');
						$lis.eq(itemPos).replaceWith('<li><a' + targetAttr + ' href="' + normalizeUrl($newItem.data('item-url')) + '">' + $newItem.data('item-name') + '</a></li>');
					}
					else if (doAction == 'remove')
					{
						var itemPos = getNavbarItemPosition($newItem);
						var $lis = $('#channel-tabbar ul li');
						$lis.eq(itemPos).remove();
					}
					else if (doAction == 'move')
					{
						var $lis = $('#channel-tabbar ul li');
						var $move = $lis.eq(movePositions.from);

						$move.remove();

						if (movePositions.to > 0)
						{
							var targetPos = (movePositions.to > movePositions.from) ? (movePositions.to) : (movePositions.to - 1);
							var $target = $lis.eq(targetPos);
							$move.insertAfter($target);
						}
						else
						{
							$move.prependTo('#channel-tabbar ul');
						}
					}
				}

				/**
				 * Generate full navbar display from edit interface DOM
				 */
				var generateNavbarDisplay = function()
				{
					console.log('generateNavbarDisplay');

					var tabbarSelector = (navbarType == 'navbar') ? '#channel-tabbar ul' : '#footer-tabbar ul';
					var subtabbarSelector = (navbarType == 'navbar') ? '#channel-subtabbar ul' : '#footer-subtabbar ul';

					$(tabbarSelector).html('');
					$(subtabbarSelector).html('');

					$('#edit-navbar .navbar-ui-wrapper ul li').each(function()
					{
						var $newItem = $(this);
						var targetAttr = $newItem.data('item-newwindow') == '1' ? ' target="_blank"' : '';
						var selectedClass = $newItem.hasClass('selected') ? ' class="current"' : '';

						if (navbarType == 'footer')
						{
							selectedClass = '';
						}

						$(tabbarSelector).append('<li' + selectedClass + '><a' + targetAttr + ' href="' + normalizeUrl($newItem.data('item-url')) + '">' + $newItem.data('item-name') + '</a></li>');


						if ($newItem.hasClass('selected'))
						{
							// add subnav items
							console.log($newItem.data('subnav-element'));
							$($newItem.data('subnav-element')).find('li').each(function()
							{
								var $newItem = $(this);
								console.log($newItem.data('item-url'));
								var targetAttr = $newItem.data('item-newwindow') == '1' ? ' target="_blank"' : '';
								var selectedClass = $newItem.hasClass('selected') ? ' class="current"' : '';
								$(subtabbarSelector).append('<li' + selectedClass + '><a' + targetAttr + ' href="' + normalizeUrl($newItem.data('item-url')) + '">' + $newItem.data('item-name') + '</a></li>');
							});
						}
					});

				};

				var insertNavbarItem = function(itemPhrase, itemName, itemUrl, itemNewWindow, itemUserGroups, itemSubnav)
				{
					var $newItem = createNavbarItem(itemPhrase, itemName, itemUrl, itemNewWindow, itemUserGroups, true);
					console.log('insertNavbarItem... Name: ' + $newItem.data('item-name') + ' Url: ' + $newItem.data('item-url') + ' NewWindow: ' + $newItem.data('item-newwindow') + ' UserGroups: ' + $newItem.data('item-usergroups'));
					//$newItem.insertBefore($('.new-nav-item-container', $editNavbarItemContainer));
					$newItem.appendTo($editNavbarItemContainer);
					updateNavbarDisplay($newItem, 'add');

					if (itemSubnav)
					{
						var $subNavGroup = $('<ul />');
						$(itemSubnav).each(function()
						{
							var
								itemPhrase = this.phrase ? this.phrase : '',
								itemTitle = this.title ? this.title : '',
								itemUrl = this.url ? this.url : '',
								itemNewWindow = this.newWindow ? this.newWindow : '0',
								itemUserGroups = this.usergroups ? this.usergroups : [];

							var $newSubItem = createNavbarItem(itemPhrase, itemTitle, itemUrl, itemNewWindow, itemUserGroups, false);
							$newSubItem.appendTo($subNavGroup);
						});

						// make ul sortable
						(function()
						{
							var sortPrevPos = null;
							$subNavGroup.sortable(
							{
								//start: function(event, ui)
								//{
								//	sortPrevPos = getNavbarItemPosition($(ui.item));
								//},
								stop: function(event, ui)
								{
									//var sortCurrPos = getNavbarItemPosition($(ui.item));
									//updateNavbarDisplay(null, 'move', {from: sortPrevPos, to: sortCurrPos});
									//alert(sortPrevPos + ' ' + sortCurrPos);

									// update navbar display
									generateNavbarDisplay();
								}
							});
							$subNavGroup.disableSelection();
						})();
						$($subNavGroup).css('display', 'none');
						$subNavGroup.appendTo('#subnavbar-list-container');

						$newItem.data('subnav-element', $subNavGroup);
					}

					generateNavbarDisplay();
				};

				var updateNavbarItem = function($replace, itemName, itemUrl, itemNewWindow, itemUserGroups)
				{
					if ($replace.data('subnav-element'))
					{
						hasSubnav = true;
					}
					else
					{
						hasSubnav = false;
					}

					$newItem = createNavbarItem($replace.data('item-phrase'), itemName, itemUrl, itemNewWindow, itemUserGroups, hasSubnav);
					console.log('updateNavbarItem... Name: ' + $newItem.data('item-name') + ' Url: ' + $newItem.data('item-url') + ' NewWindow: ' + $newItem.data('item-newwindow') + ' UserGroups: ' + $newItem.data('item-usergroups'));

					if ($replace.data('subnav-element'))
					{
						$newItem.data('subnav-element', $replace.data('subnav-element'));
					}

					if ($replace.hasClass('selected'))
					{
						$newItem.addClass('selected');
					}

					$replace.replaceWith($newItem);
					//updateNavbarDisplay($newItem, 'update');
					generateNavbarDisplay();
				};

				/**
				 * Opens the edit interface for the header navbar and footer
				 *
				 * @param	string	Navbar type, either "navbar" or "footer"
				 */
				var openNavbarEditInterface = function(navbarTypeIn)
				{
					navbarType = navbarTypeIn;

					// save current navbar HTML for restoring
					if (navbarType == 'navbar')
					{
						rollbackNavbarHTML = $('#channel-tabbar ul').html();
						rollbackSubnavHTML = $('#channel-subtabbar ul').html();
						rollbackNavbarURL = $('#channel-tabbar ul li.current a').attr('href');
					}
					else
					{
						rollbackNavbarHTML = $('#footer-tabbar ul').html();
						rollbackSubnavHTML = $('#footer-subtabbar ul').html();
						rollbackNavbarURL = $('#footer-tabbar ul li.current a').attr('href');
					}

					$('#admin-navbar-strip-gutter')
						.removeClass()
						.addClass('navbar-' + navbarType);
					$('#header').add('#header-axd').hide();

					$('#edit-navbar #navbar-ui-container .navbar-ui-wrapper').remove();
					$('#edit-navbar #navbar-ui-container .subnavbar-ui-wrapper').remove();

					$('#edit-navbar .panel-header-text').hide();
					$('#edit-navbar #panel-header-' + navbarType).show();

					$('#edit-navbar').slideDown('slow', function()
					{
						window.vBulletin.loadingIndicator.show();
						$('body').css('cursor', 'wait');

						var apiMethod = (navbarType == 'navbar') ? 'loadHeaderNavbar' : 'loadFooterNavbar';

						// initialize the navbar edit ui
						$.ajax({
							url:pageData.baseurl + '/index.php/ajax/api/site/' + apiMethod,
							data:({
								siteId: 1,
								edit:   1
							}),
							type:'POST',
							dataType: 'json',
							complete:function()
							{
								window.vBulletin.loadingIndicator.hide();
								$('body').css('cursor', 'auto');
							},
							success:function(result)
							{
								console.log(apiMethod + ' successful! result:' + JSON.stringify(result));

								// MAIN NAVBAR
								$ul = $('<ul />');
								// add the "add new" item to the UI
								$newLink = $('<div />')
									.addClass('new-nav-item-container')
									.html('<a href="" class="new-nav-item">+ ' + vBulletin.phrase.get('new_navigation_item') + '</a>');
									//.appendTo($ul);
								$h3 = $('<h3 />').text(vBulletin.phrase.get('main_navigation_bar'));
								$('<div />')
									.addClass('navbar-ui-wrapper')
									.append($h3)
									.append($ul)
									.append($newLink)
									.appendTo('#navbar-ui-container');
								var sortPrevPos = null;
								$ul.sortable(
								{
									//start: function(event, ui)
									//{
									//	sortPrevPos = getNavbarItemPosition($(ui.item));
									//},
									stop: function(event, ui)
									{
										//var sortCurrPos = getNavbarItemPosition($(ui.item));
										//updateNavbarDisplay(null, 'move', {from: sortPrevPos, to: sortCurrPos});
										//alert(sortPrevPos + ' ' + sortCurrPos);
										generateNavbarDisplay();
									}
								});
								$ul.disableSelection();
								$editNavbarItemContainer = $ul;

								// SUB NAVBAR
								$ulContainerSub = $('<div />')
									.attr('id', 'subnavbar-list-container');
								// add the "add new" item to the UI
								$newLinkSub = $('<div />')
									.addClass('new-nav-item-container')
									.html('<a href="" class="new-nav-item">+ ' + vBulletin.phrase.get('new_subnavigation_item') + '</a>');
									//.appendTo($ul);
								$h3Sub = $('<h3 />').text(vBulletin.phrase.get('sub_navigation_bar'));
								$('<div />')
									.addClass('subnavbar-ui-wrapper')
									.append($h3Sub)
									.append($ulContainerSub)
									.append($newLinkSub)
									.appendTo('#navbar-ui-container')
									.hide();

								if (result)
								{
									console.log('result:');
									console.log(result);

									$(result).each(function()
									{
										var
											itemPhrase = this.phrase ? this.phrase : '',
											itemTitle = this.title ? this.title : '',
											itemUrl = this.url ? this.url : '',
											itemNewWindow = this.newWindow ? this.newWindow : '0',
											itemUserGroups = this.usergroups ? this.usergroups : [],
											itemSubnav = this.subnav ? this.subnav : [];

										insertNavbarItem(itemPhrase, itemTitle, itemUrl, itemNewWindow, itemUserGroups, itemSubnav);
									});

									console.log('Done adding items');
								}

								// select the first item by default
								$('#edit-navbar .navbar-ui-wrapper ul li').first().find('a.navbar-item-opensubnav').click();
							},
							error:function(xhr, statusText, error)
							{
								console.log(apiMethod + ' failed! error:' +  error);
								openAlertDialog({
									'title':vBulletin.phrase.get('error'),
									'message': vBulletin.phrase.get('error_retrieving_navigation_bar_configuration'),
									'iconType':'error',
									'onAfterClose':function(){
										$('#config-dialog').dialog('close');
									}
								});
								$('#config-dialog .loader').hide();
							}
						});
					});
				};

				// navbar open edit interface ---------------
				$('#lnkNavBar', $sbMenuListItem).live('click', function()
				{
					if ($('#edit-navbar').is(':hidden')) {
						vBulletin.assertUserHasAdminPermission('canusesitebuilder', function()
						{
							openNavbarEditInterface('navbar');
						});
					}
					return false;
				});

				// footer open edit interface ---------------
				$('#lnkFooter', $sbMenuListItem).live('click', function()
				{
					if ($('#edit-navbar').is(':hidden')) {
						vBulletin.assertUserHasAdminPermission('canusesitebuilder', function()
						{
							openNavbarEditInterface('footer');
						});
					}
					return false;
				});


				$('#lnkPageManager', $sbMenuListItem).live('click', function()
				{
					vBulletin.assertUserHasAdminPermission('canusesitebuilder', function()
					{
						//show first tab by default

						//onModuleAddOrRemove();
						toggleAllModuleContentVisibility(false);
						$('.edit-mode .canvas-widget-list .canvas-widget').addClass('shadow');

						//show first tab by default
						//$pageEditorTabs.tabs('select', 0);

						$('#header, #header-axd, #save-content').hide();
						$('#manage-page').show();
						$('#manage-page-dropdown .lnkSaveChanges .label').text(vBulletin.phrase.get('save_page'));

						$('#manage-page-dropdown').removeClass('hide').slideDown('slow', initializePageManager);
					});
					return false;
				});

				// page manager open edit interface ---------------
//				$('#lnkPageManager', $sbMenuListItem).live('click', function()
//				{
//					if ($('#edit-navbar').is(':hidden')) {
//						vBulletin.assertUserHasAdminPermission('canusesitebuilder', function()
//						{
//							openNavbarEditInterface('page_manager');
//						});
//					}
//					return false;
//				});
//
				// navbar new item -------------
				$('#edit-navbar').delegate('a.new-nav-item', 'click', function()
				{
					$editNavbarItem = null; // no item being edited, it's new

					if ($(this).closest('.navbar-ui-wrapper').size() > 0)
					{
						// man nav item
						$editNavbarItemContainer = $(this).closest('.navbar-ui-wrapper').find('ul');
					}
					else
					{
						// subnav item
						$editNavbarItemContainer = $(this).closest('.subnavbar-ui-wrapper').find('ul').filter(':visible');
					}

					$('#navbar-edit-name').val('');
					$('#navbar-edit-url').val('');
					$('#navbar-edit-newwindow').attr('checked', false);
					// @todo -- set to "all" usergroups here
					$('#navbar-edit-item').removeClass('hide');
					$('#navbar-edit-name').focus();

					return false;
				});

				// navbar new/edit item save -------------
				$('#edit-navbar').delegate('#navbar-edit-item #navbar-edit-save', 'click', function()
				{
					// Validate itemName and itemUrl here
					if ($('#navbar-edit-name').val() == '')
					{
						openAlertDialog({
							'title':vBulletin.phrase.get('edit_navigation_item'),
							'message':vBulletin.phrase.get('input_navigation_item_name'),
							'iconType':'warning',
							'onAfterClose':function(){
								$('#navbar-edit-name').focus();
							}
						});

					}
					else if ($('#navbar-edit-url').val() == '')
					{
						openAlertDialog({
							'title':vBulletin.phrase.get('edit_navigation_item'),
							'message':vBulletin.phrase.get('input_target_url'),
							'iconType':'warning',
							'onAfterClose':function(){
								$('#navbar-edit-url').focus();
							}
						});
					}
					else
					{
						console.log('Saving new/edited navbar item');
						if (!$editNavbarItem)
						{
							insertNavbarItem(
								'',
								$('#navbar-edit-name').val(),
								$('#navbar-edit-url').val(),
								$('#navbar-edit-newwindow').attr('checked'),
								$('#navbar-edit-item').data('edit-usergroups'),
								[] // empty sub-nav (so the UL gets created)
							);
						}
						else
						{
							updateNavbarItem(
								$editNavbarItem,
								$('#navbar-edit-name').val(),
								$('#navbar-edit-url').val(),
								$('#navbar-edit-newwindow').attr('checked'),
								$('#navbar-edit-item').data('edit-usergroups')
							);
						}

						$editNavbarItem = null;
						$editNavbarItemContainer = null;

						$('#navbar-edit-item').addClass('hide');

						console.log('Done saving new/edited navbar item');
					}

					return false;
				});

				// navbar new item cancel -------------
				$('#edit-navbar').delegate('#navbar-edit-item #navbar-edit-cancel', 'click', function()
				{
					$('#navbar-edit-item').addClass('hide');
					return false;
				});

				// navbar new/edit item edit usergroups -------------
				var userGroupDialogCreated = false;
				$('#edit-navbar').delegate('#navbar-edit-item #navbar-edit-usergroups', 'click', function()
				{
					//var $liClicked = $editNavbarItem;

					// prefill currently checked usergroup boxes
					var prefillCurrentSelection = function()
					{
						if (!$editNavbarItem) {
							return false;
						}

						console.log('Prefilling checked usergroups');
						console.log($editNavbarItem.data('item-name'));
						console.log($editNavbarItem.data('item-url'));
						console.log($editNavbarItem.data('item-usergroups'));

						if ($editNavbarItem.data('item-usergroups-temp'))
						{
							var usergroups = $editNavbarItem.data('item-usergroups-temp');
						}
						else
						{
							var usergroups = $editNavbarItem.data('item-usergroups');
						}

						console.log(usergroups);

						$('#navbar-edit-usergroups-dialog .dialog-module-container input[type=checkbox]').attr('checked', false);

						$.each(usergroups, function(index, value)
						{
							$('#navbar-edit-usergroups-dialog .dialog-module-container #navbar-usergroup-checkbox-' + value).attr('checked', true);
						});
					};

					var saveCurrentSelection = function()
					{
						var checkedUsergroupIds = [];
						$('#navbar-edit-usergroups-dialog .dialog-module-container input[type=checkbox]').each(function()
						{
							console.log($(this).attr('checked'));
							if ($(this).attr('checked') == 'checked')
							{
								checkedUsergroupIds.push($(this).val());
							}
						});
						$('#navbar-edit-item').data('edit-usergroups', checkedUsergroupIds);
						if ($editNavbarItem)
						{
							$editNavbarItem.data('item-usergroups-temp', checkedUsergroupIds);
						}
						console.log('Saving checked usergroups');
						//console.log($editNavbarItem.data('item-name'));
						//console.log($editNavbarItem.data('item-url'));
						//console.log($editNavbarItem.data('item-usergroups'));
					};

					if (!userGroupDialogCreated)
					{


						$('#navbar-edit-usergroups-dialog').dialog(
						{
							title: vBulletin.phrase.get('user_group_settings'),
							autoOpen: true,
							modal: true,
							resizable: false,
							closeOnEscape: true,
							showCloseButton: true,
							width: 950,
							dialogClass: 'dialog-container pagemap-dialog-container input-dialog',
							create: function()
							{
								$('#navbar-edit-usergroups-dialog .cancel-button').click(function()
								{
									$('#navbar-edit-usergroups-dialog').dialog('close');
								});
								$('#navbar-edit-usergroups-dialog .save-button').click(function()
								{
									// save the currently checked usergroups
									saveCurrentSelection();
									$('#navbar-edit-usergroups-dialog').dialog('close');
								});

								// populate popup with list of usergroups
								$.ajax({
									url:pageData.baseurl + '/index.php/ajax/api/usergroup/fetchUsergroupList',
									data:({siteId:1}),
									type:'POST',
									dataType: 'json',
									complete:function()
									{
										//window.vBulletin.loadingIndicator.hide();
										$('body').css('cursor', 'auto');
									},
									success:function(result)
									{
										console.log('fetchUsergroupList successful! result:' + JSON.stringify(result));

										if (result)
										{
											console.log('result:');
											console.log(result);

											$(result).each(function()
											{
												console.log(this);
												var $item = $('<div><label><input type="checkbox" id="navbar-usergroup-checkbox-' + this.usergroupid + '" value="' + this.usergroupid + '" />' + this.title + '</label></div>')
												$('#navbar-edit-usergroups-dialog .dialog-module-container').append($item);
											});

											console.log('Done adding usergroups');
										}

										prefillCurrentSelection();
									},
									error:function(xhr, statusText, error)
									{
										console.log('fetchUsergroupList failed! error:' +  error);
										openAlertDialog({
											'title':vBulletin.phrase.get('error'),
											'message':vBulletin.phrase.get('error_retrieving_list_user_groups'),
											'iconType':'error',
											'onAfterClose':function(){
												$('#config-dialog').dialog('close');
											}
										});
										$('#config-dialog .loader').hide();
									}
								});
							},
							close: function()
							{
								//$('#navbar-edit-usergroups-dialog .dialog-module-container').html('');
								//$('#navbar-edit-usergroups-dialog').dialog('destroy');

							},
							open: function()
							{
								prefillCurrentSelection();
							}
						});
						userGroupDialogCreated = true;
					}
					else
					{
						$('#navbar-edit-usergroups-dialog').dialog('open');
					}

					return false;
				});

				// navbar delete item -------------
				$('#edit-navbar').delegate('.navbar-item-delete', 'click', function()
				{
					updateNavbarDisplay($(this).closest('li'), 'remove');
					$(this).closest('li').remove();

					generateNavbarDisplay();
					return false;
				});

				// navbar edit item -------------
				$('#edit-navbar').delegate('.navbar-item-edit', 'click', function()
				{
					var $li = $(this).closest('li');
					console.log('Click to edit item... Name: ' + $li.data('item-name') + ' Url: ' + $li.data('item-url') + ' NewWindow: ' + $li.data('item-newwindow') + ' UserGroups: ' + $li.data('item-usergroups'));

					$editNavbarItem = $li;
					$editNavbarItemContainer = $li.closest('ul');

					$editNavbarItem.data('item-usergroups-temp', null);

					$('#navbar-edit-name').val($li.data('item-name'));
					$('#navbar-edit-url').val($li.data('item-url'));
					$('#navbar-edit-newwindow').attr('checked', $li.data('item-newwindow') == 1 ? true : false);
					// @todo add usergroup info here

					$('#navbar-edit-item').removeClass('hide');
					$('#navbar-edit-name').focus();

					return false;
				});

				// navbar open item subnav edit interface ---------------
				$('#edit-navbar').delegate('.navbar-item-opensubnav', 'click', function()
				{
					var $li = $(this).closest('li');
					console.log('Click to open item subnav ... Name: ' + $li.data('item-name') + ' Url: ' + $li.data('item-url') + ' NewWindow: ' + $li.data('item-newwindow') + ' UserGroups: ' + $li.data('item-usergroups'));

					// select the clicked main menu item
					$('#edit-navbar li').removeClass('disabled selected');
					$li.addClass('selected');

					// show the sub nav UI with the correct list in it
					$('#edit-navbar .subnavbar-ui-wrapper ul').hide();
					$($li.data('subnav-element')).show();
					$('#edit-navbar .subnavbar-ui-wrapper').show();

					generateNavbarDisplay();

					return false;
				});

				// navbar exit w/o saving ---------------
				$('.navbar-navbar #admin-navbar-strip .lnkExitWithoutSaving').live('click', function()
				{
					$('#edit-navbar').slideUp();
					$('#header').add('#header-axd').show();

					// restore previous navbar HTML here
					if (navbarType == 'navbar')
					{
						$('#channel-tabbar ul').html(rollbackNavbarHTML);
						$('#channel-subtabbar ul').html(rollbackSubnavHTML);
					}
					else
					{
						$('#footer-tabbar ul').html(rollbackNavbarHTML);
						$('#footer-subtabbar ul').html(rollbackSubnavHTML);
					}
				});

				// navbar & footer save ---------------
				var saveNavbarData = function()
				{
					var navbarData = [];

					$('#edit-navbar .navbar-ui-wrapper ul li').each(function()
					{
						var $li = $(this);

						var subnavItems = [];
						$li.data('subnav-element').find('li').each(function()
						{
							$subLi = $(this);
							subnavItems.push({
								'phrase': $subLi.data('item-phrase'),
								'title': $subLi.data('item-name'),
								'url': $subLi.data('item-url'),
								'newWindow': $subLi.data('item-newwindow'),
								'usergroups': $subLi.data('item-usergroups')
							});
						});

						navbarData.push({
							'phrase': $li.data('item-phrase'),
							'title': $li.data('item-name'),
							'url': $li.data('item-url'),
							'newWindow': $li.data('item-newwindow'),
							'usergroups': $li.data('item-usergroups'),
							'subnav': subnavItems
						});
					});

					var apiMethod = (navbarType == 'navbar') ? 'saveHeaderNavbar' : 'saveFooterNavbar';

					// save the changes
					$.ajax({
						url:pageData.baseurl + '/index.php/ajax/api/site/' + apiMethod,
						data:({
							siteId: 1,
							data: navbarData
						}),
						type:'POST',
						dataType: 'json',
						complete:function()
						{
							$('body').css('cursor', 'auto');
						},
						success:function(result)
						{
							console.log(apiMethod + ' successful! result:' + JSON.stringify(result));

							$('#edit-navbar').slideUp();
							$('#header').add('#header-axd').show();

							$('#admin-navbar ul.main-nav li').removeClass('disabled').find('a').removeClass('selected');
							$('#admin-navbar-strip-gutter').addClass('hide');
							$(document.body).removeClass('edit-mode lnkEditPage lnkNewPage lnkHeader lnkNavBar lnkFooter').addClass('view-mode');
							$('#main-navbar ul.secondary-nav').removeClass('disabled');

							// restore previously selected navbar tab when possible
							if (navbarType == 'navbar')
							{
								// Try to rollback old navbar
								var rollback = false;
								$('#edit-navbar .navbar-ui-wrapper ul li').each(function() {
									var $newItem = $(this);

									if (normalizeUrl($newItem.data('item-url')) == rollbackNavbarURL) {
										rollback = true;
										$('#edit-navbar .navbar-ui-wrapper ul li').removeClass('selected');
										// Make rollbar item in navbar editor selected so that we can re-generate navbar display
										$newItem.addClass('selected');
										return false;
									}
								});

								if (rollback) {
									generateNavbarDisplay();
								}
								else {
									// Rollback failed, we need to make no item selected
									$('#channel-tabbar ul li').removeClass('current');
									$('#channel-subtabbar ul').html('');
								}

							}
							else
							{
								$('#footer-tabbar ul li').removeClass('current');
								$('#footer-tabbar ul li').filter(function()
								{
									var itemUrl = $(this).find('a').attr('href');
									return (itemUrl == rollbackNavbarURL);

								}).addClass('current');
							}
						},
						error:function(xhr, statusText, error)
						{
							console.log(apiMethod + ' failed! error:' +  error);
							openAlertDialog({
								'title':vBulletin.phrase.get('error'),
								'message':vBulletin.phrase.get('error_saving_navigation_bar_configuration'),
								'iconType':'error',
								'onAfterClose':function(){
									$('#config-dialog').dialog('close');
								}
							});
							$('#config-dialog .loader').hide();
						}
					}); // end ajax save changes
				};

				// navbar save ---------------
				$('.navbar-navbar #admin-navbar-strip .lnkSaveChanges').live('click', function()
				{
					saveNavbarData();
				});

				// footer save ---------------
				$('.navbar-footer #admin-navbar-strip .lnkSaveChanges').live('click', function()
				{
					saveNavbarData();
				});

			})();
			// end navbar & footer edit UI +++++++++++++++++++++++++++++++++++++++++++++++++++++++++




			//end bind click handlers to the top nav bar items

			//the click handler for each of the top nav bar items has been bound,
			//so it's safe to show the top nav bar here
			$('#main-navbar .main-nav').removeClass('hide');

			$('#admin-navbar-strip .lnkSaveChanges').live('click', function(){
				//alert('Not implemented yet.'); //@TODO
			});

			//Save Changes for Header nav
			$('.lnkHeader #admin-navbar-strip .lnkSaveChanges').live('click', function(){
				$('body').css('cursor', 'wait');

				//TODO: Implement saving Header Ad HTML here


				//save Site Logo
				if (Number($('#header .site-logo img').attr('data-fileid')) > 0){
					$.ajax({
						url:pageData.baseurl + '/index.php/uploader/set_logo',
						data:({
							'filedataid': $('#header .site-logo img').attr('data-fileid')
			  			}),
			  			type:'POST',
			  			dataType: 'text',
			  			complete:function(){
							console.log('uploader/set_logo complete.');
							$('body').css('cursor', 'auto');
						},
			  			success:function(result){
							console.log('saving site logo successful! result:' + result);
							if ($.trim(result) === 'true'){
								$('#header .site-logo img').removeAttr('data-fileid').attr('data-orig-src', $('#header .site-logo img').attr('src'));

								$('#main-navbar li').removeClass('disabled').find('a').removeClass('selected');
								$('#admin-navbar-strip-gutter').addClass('hide').find('.prompt-text').text('');
								$(document.body).removeClass('edit-mode lnkHeader').addClass('view-mode');
								$('#header .disable-overlay').hide();
								$('#main-navbar ul.secondary-nav').removeClass('disabled');
							}
							else {
								console.log('saving site logo failed!');
								openAlertDialog({
									'title':vBulletin.phrase.get('error'),
									'message':vBulletin.phrase.get('error_saving_site_logo'),
									'iconType':'error'
								});
							}
						},
						error:function(xhr, statusText, error){
							console.log('saving site logo failed! error:' + error);
							openAlertDialog({
								'title':vBulletin.phrase.get('error'),
								'message':vBulletin.phrase.get('error_saving_site_logo_code', xhr.status),
								'iconType':'error'
							});
						}
					});
				}
				else {
					$('body').css('cursor', 'auto');
					$('#main-navbar li').removeClass('disabled').find('a').removeClass('selected');
					$('#admin-navbar-strip-gutter').addClass('hide').find('.prompt-text').text('');
					$(document.body).removeClass('edit-mode lnkHeader').addClass('view-mode');
					$('#header .disable-overlay').hide();
					$('#main-navbar ul.secondary-nav').removeClass('disabled');
				}
			});

			$('.lnkHeader #admin-navbar-strip .lnkExitWithoutSaving').live('click', function(){
				var $logo = $('#header .site-logo img');
				if ($logo.attr('src') != $logo.attr('data-orig-src')) {
					$logo.attr('src', $logo.attr('data-orig-src')).removeAttr('data-fileid');
				}
				$('#admin-navbar-strip-gutter').find('.prompt-text').text('');
				$('#header .disable-overlay').hide();
			});

			$('#admin-navbar-strip .lnkExitWithoutSaving').live('click', function(){
				$('#main-navbar li').removeClass('disabled').find('a').removeClass('selected');
				$('#admin-navbar-strip-gutter').addClass('hide');
				$(document.body).removeClass('edit-mode lnkEditPage lnkNewPage lnkHeader lnkNavBar lnkFooter').addClass('view-mode');
				$('#header').add('#header-axd').show();
				$('#edit-navbar').hide();
			});

			// Update header Ad number
			$('#header-axd .axdnum').change(function() {
				var self = $(this),
					number = parseInt(self.val());

				window.vBulletin.loadingIndicator.show();

				$.ajax({
					url:pageData.baseurl + '/index.php/ajax/api/ad/saveNumberOfHeaderAds',
					type:'post',
					data:{number:number},
					dataType:'json',
					success:function (response) {
						if (response !== null && typeof response.errors !== 'undefined') {
							openAlertDialog({
								'title':vBulletin.phrase.get('error'),
								'message':vBulletin.phrase.get(response.errors[0]), // TODO: Improve error message
								'iconType':'error'
							});
						}
						else {
							// Change the css class of header ad to hide/show the second Ad
							if (number == 1) {
								$('#header-axd').removeClass('axdnum_2').addClass('axdnum_1');
							}
							else {
								$('#header-axd').removeClass('axdnum_1').addClass('axdnum_2');
							}
						}
					},
					complete:function () {
						window.vBulletin.loadingIndicator.hide();
					}
				});
			});

			$('.axd-edit-button').unbind().live('click', function(){
				var adlocation = $(this).attr('data-location'),
					adcontainer = $(this).closest('.axd-container');

				fetchAds();

				function fetchAds(noconfigdialog) {
					noconfigdialog = noconfigdialog || false;

					$('body').css('cursor', 'wait');
					// Fetch Ads at the location
					$.ajax({
						url:pageData.baseurl + '/index.php/ajax/api/ad/listAdsByLocation',
						type:'post',
						data:{adlocation:adlocation},
						dataType:'json',
						cache:false,
						success:function (response) {
							if (response !== null && typeof response.errors !== 'undefined') {
								openAlertDialog({
									'title':vBulletin.phrase.get('error'),
									'message':vBulletin.phrase.get(response.errors[0]), // TODO: Improve error message
									'iconType':'error'
								});
							}
							else {
								if (response) {
									// If we already have Ad
									openAdListDialog(response);
								}
								else {
									// Else we open "Add new Ad" dialog directly
									// Do not open "Add new Ad" Dialog if fetchAds() is called from an "Add new Ad" Dialog
									if (!noconfigdialog) {
										openAdConfigDialog({adlocation: adlocation});
									}
									else {
										openAdListDialog([]);
									}
								}
							}
						},
						complete:function () {
							$('body').css('cursor', 'default');
						}
					});
				}

				function openAdListDialog(response) {
					$('#axd-list-dialog').dialog({
						title: vBulletin.phrase.get('edit_locationx_ad', adlocation),
						autoOpen:true,
						modal:true,
						resizable:false,
						closeOnEscape:false,
						showCloseButton:false,
						width:720,
						dialogClass:'dialog-container ad-list-dialog-container input-dialog',
						open:function(){
							var self = $(this);
							var aaData = [];
							for (var i in response) {
								aaData.push([
									response[i].title,
									response[i].active,
									response[i].displayorder,
								    response[i].adid
								]);
							}

							$('.title', self).text(vBulletin.phrase.get('ad_list_description', adlocation));
							$('.axdtable', self).dataTable({
								"bPaginate": false,
								"bLengthChange": false,
								"bInfo": false,
								"bAutoWidth": false,
								"bDestroy": true,
								"aaSorting": [[ 2, "asc" ]],
								"aoColumns": [
									{"sTitle": "Title"},
									{
										"sTitle": "Active?",
										"sClass": "center",
										"bSortable": false,
										"sWidth": "20px",
										"bSearchable": false,
										"fnRender": function(obj, sval) {
											var sReturn = '<input type="checkbox" class="isactive"'
											 + ((sval == '1')?' checked="checked"':'') +
											' data-id="' + obj.aData[3] + '" />';
											return sReturn;
										}
									},
									{
										"sTitle": "Display Order",
										"sClass": "center",
										"sWidth": "90px",
										"bSearchable": false,
										"bUseRendered": false,
										"fnRender": function(obj, sval) {
											var sReturn = '<input type="text" class="displayorder" value="'
											 + obj.aData[2] +
											'" data-id="' + obj.aData[3] + '" size="3" />';
											return sReturn;
										}
									},
									{
										"sTitle": "Action",
										"sClass": "center",
										"sWidth": "100px",
										"bSearchable": false,
										"bSortable": false,
										"bUseRendered": false,
										"fnRender": function(obj, sval) {
											var sReturn = '[<a href="#" class="editlink" data-id="' + obj.aData[3] + '">' + vBulletin.phrase.get('edit') + '</a>]' +
												'&nbsp;[<a href="#" class="deletelink" data-id="' + obj.aData[3] + '">' + vBulletin.phrase.get('delete') + '</a>]';
											return sReturn;
										}
									}
								],
								"aaData": aaData
							});
							// Edit link. Open dialog
							$('.axdtable .editlink', self).unbind().click(function() {
								var adid = $(this).attr('data-id');
								self.dialog('close');
								self.dialog('destroy');
								openAdConfigDialog(response[adid]);
								return false;
							});
							$('.axdtable .deletelink', self).unbind().click(function() {
								var adid = $(this).attr('data-id');
								self.dialog('close');
								self.dialog('destroy');
								openConfirmDialog({
									'title': vBulletin.phrase.get('confirm_deletion_x', response[adid].title),
									'message': vBulletin.phrase.get('are_you_sure_want_to_delete_ad_x', response[adid].title, 'adid', adid),
									'iconType':'warning',
									onClickYes: function() {
										$('body').css('cursor', 'wait');
										// Fetch Ads at the location
										$.ajax({
											url:pageData.baseurl + '/index.php/ajax/api/ad/delete',
											type:'post',
											data:{adid:adid},
											dataType:'json',
											success:function (response) {
												if (response.errors) {
													openAlertDialog({
														'title':vBulletin.phrase.get('error'),
														'message':vBulletin.phrase.get(response.errors[0]), // TODO: Improve error message
														'iconType':'error'
													});
												}
												else {
													fetchAds(true);
												}
											}
										});
									},
									onClickNo: function() {
										fetchAds();
									}
								});
								return false;
							});
							$('.axdlist', self).show();

							$('.btnAddAxd', self).unbind().click(function(){
								self.dialog('close');
								self.dialog('destroy');
								openAdConfigDialog({adlocation: adlocation});
								return false;
							});

							$('.btnCancelAxd', self).unbind().click(function(){
								self.dialog('close');
								self.dialog('destroy');
							});

							$('.btnSaveAxd', self).unbind().click(function(){
								if ($('.isactive', self).length == 0) {
									self.dialog('close');
									self.dialog('destroy');
									return false;
								}

								$('body').css('cursor', 'wait');

								// Build post data
								var postdata = {}, firstadid = 0;

								$('.isactive', self).each(function() {
									var adid = $(this).attr('data-id');

									if (!firstadid) {
										firstadid = adid;
									}

									postdata[adid] = {};
									postdata[adid]['active'] = $(this).is(':checked')?1:0;
									postdata[adid]['displayorder'] = $('.displayorder[data-id="' + adid + '"]', self).val();
								});

								$.ajax({
									url:pageData.baseurl + '/index.php/ajax/api/ad/quickSave',
									type:'post',
									data:{data: postdata},
									dataType:'json',
									success:function (saveres) {
										if (saveres.errors) {
											openAlertDialog({
												'title':vBulletin.phrase.get('error'),
												'message':vBulletin.phrase.get(saveres.errors[0]), // TODO: Improve error message
												'iconType':'error'
											});
										}
										else {
											// Fetch the first Ad's HTML. We just need to display the first one
											// without conditionals so that Admin will see what it looks like
											var firstad = response[firstadid];

											$('.axd_' + adlocation, adcontainer).html(firstad.snippet);

											// adcontainer is hidden by default for modules
											// We need to show it
											$('.axd_' + adlocation, adcontainer).show();

											self.dialog('close');
											self.dialog('destroy');
										}
									},
									complete:function () {
										$('body').css('cursor', 'default');
									}
								});
							});
						}
					});
				}

				function openAdConfigDialog(data) {
					var adlocation = data.adlocation;

					$('#axd-config-dialog').dialog({
						title:vBulletin.phrase.get('edit_custom_html_module'),
						autoOpen:true,
						modal:true,
						resizable:false,
						closeOnEscape:false,
						showCloseButton:false,
						width:720,
						dialogClass:'dialog-container axd-dialog-container input-dialog',
						open:function(){
							var self = $(this);

							if (data.adid) {
								$('.title', self).val(data.title);
								$('.axd_html', self).val(data.snippet);

								if (data.active == "1") {
									$('.active', self).prop('checked', true);
								}
								else {
									$('.active', self).prop('checked', false);
								}

								$('.axdid', self).val(data.adid);

								for (var i in data.criterias) {
									$('[name=data\\[criteria\\]\\[' + data.criterias[i].criteriaid + '\\]\\[active\\]]', self).prop('checked', true);
									$('[name=data\\[criteria\\]\\[' + data.criterias[i].criteriaid + '\\]\\[condition1\\]]', self).val(data.criterias[i].condition1);
									$('[name=data\\[criteria\\]\\[' + data.criterias[i].criteriaid + '\\]\\[condition2\\]]', self).val(data.criterias[i].condition2);
									$('[name=data\\[criteria\\]\\[' + data.criterias[i].criteriaid + '\\]\\[condition3\\]]', self).val(data.criterias[i].condition3);
								}
							}
							else {
								$('.axdid', self).val(0);
								$('input[type="text"]', self).val('');
								$('textarea', self).val('');
								$('select', self).find('option:selected').removeAttr("selected");
								$('input[type="checkbox"]', self).prop('checked', false);
							}
							$('.axd_location', self).val(adlocation);

							$('.btnAttachHtmlAxd', self).unbind().click(function(){
								// Call API to save data
								var postdata = $('.configform', self).serialize();
								$('body').css('cursor', 'wait');

								$.ajax({
									url:pageData.baseurl + '/index.php/ajax/api/ad/save',
									type:'post',
									data:postdata,
									dataType:'json',
									success:function (response) {
										if (response) {
											if (response.errors) {
												openAlertDialog({
													'title':vBulletin.phrase.get('error'),
													'message':vBulletin.phrase.get(response.errors[0]), // TODO: Improve error message
													'iconType':'error'
												});
											}
											else {
												closeConfigDialog();
											}
										}
									},
									complete:function () {
										$('body').css('cursor', 'default');
									}
								});

							});

							$('.btnCancelEditHtmlAxd', self).unbind().click(function(){
								closeConfigDialog(true);
							});


							function closeConfigDialog(noconfigdialog) {
								noconfigdialog = noconfigdialog || false;

								$(':checkbox', self).prop('checked', false);
								$('select', self).val('');
								self.dialog('close');
								self.dialog('destory');

								fetchAds(noconfigdialog);
							}
						}
					});
				}


				return false;
			});

			$('#header .header-cell .edit.button').click(function(){
				$('.header-edit-box.selected').removeClass('selected');
				$(this).closest('.header-edit-box').addClass('selected');
				$('#edit-site-logo-dialog').dialog({
					title:vBulletin.phrase.get('edit_site_logo') + '<span class="dialog-subtitle">' + vBulletin.phrase.get('choose_options_site_logo') + '</span>',
					autoOpen:true,
					modal:true,
					resizable:false,
					closeOnEscape:false,
					showCloseButton:false,
					width:520,
					dialogClass:'dialog-container site-logo-dialog-container input-dialog',
					create:function(){
						$('#btnCancelEditSiteLogo').click(function(){
							$('#edit-site-logo-dialog').dialog('close');
						});

						$('#edit-site-logo-dialog').fileupload({
							dropZone:null,
							add: function (e, data) {
								$('body').css('cursor', 'wait');
						    	$(e.target).find('.upload-progress-bar:first').removeClass('hide');
				                data.submit();
				            },
				            done: function (e, data) {
				            	if (data.result && data.result.filedataid) {
					                $('#header .site-logo img').attr({
					                	'src': data.result.imageUrl,
					                	'data-fileid': data.result.filedataid
					                })
					                $('#edit-site-logo-dialog').dialog('close');
				            	}
				            	else {
				            		openAlertDialog({
		    							'title':vBulletin.phrase.get('error'),
		    							'message':vBulletin.phrase.get('error_uploading_logo'),
		    							'iconType':'error'
		    						});
				            	}
				            },
				            fail: function (e, data) {
				            	openAlertDialog({
	    							'title':vBulletin.phrase.get('error'),
	    							'message':vBulletin.phrase.get('error_uploading_logo'),
	    							'iconType':'error'
	    						});
				            },
				            always: function (e, data) {
				            	$('body').css('cursor', 'auto');
				            	$(e.target).find('.upload-progress-bar:first').addClass('hide');
				            }
						});

						$('#edit-site-logo-dialog #btnAttachLogo').click(function(){
							var imageUrl = $.trim($('#edit-site-logo-dialog #imageUrl').val());
							if (imageUrl) {
								$('body').css('cursor', 'wait');
								$(this).closest('.dialog-content').find('.upload-progress-bar:last').removeClass('hide');
								$.ajax({
									url:pageData.baseurl + '/index.php/uploader/uploadLogoUrl',
									data:({
										'urlupload': imageUrl
						  			}),
						  			type:'POST',
						  			dataType: 'json',
						  			complete:function(){
										console.log('uploader/url complete.');
										$('body').css('cursor', 'auto');
										$('#edit-site-logo-dialog .upload-progress-bar:last').addClass('hide');
									},
						  			success:function(result){
										console.log('saving site logo successful! result:' + result);
										if (result && !result.error) {
											$('#header .site-logo img').attr({
												'src': result.imageUrl,
												'data-fileid': result.filedataid
											});

											$('#edit-site-logo-dialog').dialog('close');
						            	}
						            	else if (result.error){
						            		openAlertDialog({
				    							'title':vBulletin.phrase.get('edit_site_logo'),
				    							'message':vBulletin.phrase.get('invalid_image_url'),
				    							'iconType':'warning',
				    							'onAfterClose':function(){
						            				$('#edit-site-logo-dialog #imageUrl').select().focus();
						            			}
				    						});
						            	}
										else {
											openAlertDialog({
												'title':vBulletin.phrase.get('error'),
												'message':vBulletin.phrase.get('error_processing_site_logo'),
												'iconType':'error',
				    							'onAfterClose':function(){
						            				$('#edit-site-logo-dialog #imageUrl').focus();
						            			}
											});
										}
									},
									error:function(xhr, statusText, error){
										console.log('remote url site logo failed! error:' + error);
										openAlertDialog({
											'title':vBulletin.phrase.get('error'),
											'message':vBulletin.phrase.get('error_processing_site_logo_image_hosting', xhr.status),
											'iconType':'error',
				    						'onAfterClose':function(){
					            				$('#edit-site-logo-dialog #imageUrl').focus();
					            			}
										});
									}
								});
							}
							else {
								$('#edit-site-logo-dialog #imageUrl').focus();
							}
						});
					}
				});
			});

			$('.admin-button-flat').disableSelection();

			//initialize tabs
			$pageEditorTabs = $('#edit-content .tabs').tabs({
				show:function(event, ui){
					//resize Modules/Layouts/Templates list
					resizeListWidth(ui.index);

					//resize tab content width
					resizePageEditorTabContentWidth();
				},
				select:function(event, ui){
					$('#save-content').hide();
					if (ui.index == 1){ //Change Layout tab
						if (templateChanged){
							$('#edit-page-dropdown .layout-list .layout-border.selected').removeClass('selected');
							var $selectedRadio = $('#edit-page-dropdown .layout-list input[type=radio][value={0}]'.format($('.canvas-layout:visible').attr('layout-id')));
							$selectedRadio.prev().addClass('selected');
							currentLayout = 'canvas-' + $selectedRadio.attr('id');
						}
					}
				}
			});

			$('#lnkAddModules').click(function(){
				$pageEditorTabs.tabs('select', 0);
				return false;
			});

			attachDefaultWidgetEditButtonHandler();

			//hide/unhide Module checkbox for widgets inside Container widget
			$('.module-buttons .hide-icon input').live('click', function() {
				var $self = $(this);
				$self.closest('.canvas-widget')[this.checked ? 'addClass' : 'removeClass']('hidden-widget');
				var origTitle = $self.attr('title');
				$self.attr('title', $self.data('toggle-title')).data('toggle-title', origTitle);
			});

			//get column counts for each layout
			$('.canvas-layout-container .canvas-layout').each(function(){
				sectionCount[this.id] = $('#' + this.id + ' div[class*="section-"]').length;
			});

			//select associated screen layout
			if (!newPage){
				currentLayout = 'canvas-' + $('#edit-page-dropdown .layout-list input[type=radio][value={0}]'.format(
					$('.canvas-layout:visible').attr('layout-id'))
				).prop('checked', true)
				 .attr('id');
			}

			//transform screen layout radio buttons to thumbnails
			$screenLayoutThumbnails = $('#edit-page-dropdown .layout-list input[type=radio]').thumbnailRadioCheckbox({
				thumbnailClass:'layout-border'
			});

			//set the 'select' event handler after initializing the thumbnailRadioCheckbox plugin object to prevent the 'select' event to fire immediately
			$screenLayoutThumbnails.thumbnailRadioCheckbox('option', 'select', function($thumbnail, $radio){
				$('.canvas-layout').addClass('hide');
				$('#canvas-' + $radio.attr('id')).removeClass('hide');
				selectLayout('canvas-' + $radio.attr('id'));
				setCanvasStaticWidth();
				setCanvasStaticHeight();
				hasCanvasChanged = true;
			});

			// Initialize page map overlay
			(function()
			{
				$('.lnkPageMap').click(function()
				{
					$('#page-map-dialog').dialog(
					{
						title: vBulletin.phrase.get('page_map'),
						autoOpen: false,
						modal: true,
						resizable: false,
						closeOnEscape: false,
						showCloseButton:false,
						width: 500,
						dialogClass: 'dialog-container pagemap-dialog-container input-dialog',
						create: function()
						{
							$('#btnClosePageMapDialog').click(function()
							{
								$('#page-map-dialog').dialog('close');
							});

							$.ajax(
							{
								url:pageData.baseurl + '/index.php/ajax/api/page/fetchPageMapHierarchy',
								data:({
									'pageId': pageData.pageid
								}),
								type:'POST',
								dataType: 'json',
								complete:function()
								{
									console.log('/index.php/ajax/api/page/fetchPageMapHierarchy complete');
									$('body').css('cursor', 'auto');
								},
								success:function(result)
								{
									console.log('/index.php/ajax/api/page/fetchPageMapHierarchy successful');
									if (result && $.isArray(result.pageMap))
									{
										var
											i,
											j,
											output = '',
											page,
											siblings,
											sibling,
											arrowSpan,
											classAttr,
											youAreHere,
											left,
											top;

										for (i = 0; i < result.pageMap.length; ++i)
										{
											page = result.pageMap[i].page;
											siblings = result.pageMap[i].siblings;

											output += '<ul>';
											for (j = 0; j < siblings.length; ++j)
											{
												sibling = siblings[j];
												classAttr = (sibling.pageid == page.pageid) ? ' class="current-path"' : '';
												classAttr = (sibling.pageid == page.pageid && ((i + 1) == result.pageMap.length)) ? ' class="current-path-end"' : classAttr;
												arrowSpan = ((i + 1) == result.pageMap.length) ? '' : '<span>&gt;</span>';
												youAreHere = (sibling.pageid == page.pageid && ((i + 1) == result.pageMap.length)) ? '<div id="you-are-here" class="round-corner7"><div class="arrow"><div class="arrow-inner"></div></div>' + vBulletin.phrase.get('you_are_here') + '</div>' : '';
												output += '<li' + classAttr + '>' + arrowSpan + '<a href="' + pageData.baseurl + sibling.url + '">' + htmlEnities(sibling.title) + '</a>' + youAreHere + '</li>';
											}
											output += '</ul>';
										}

										$('#page-map-content').html(output);

										left = $('#you-are-here').parent().outerWidth() + 10;

										$('#you-are-here').css({left: left, top: -10});
									}
									else
									{
										console.log(result);
										console.log('/index.php/ajax/api/page/fetchPageMapHierarchy successful, but response was not an array');
										openAlertDialog({
											'title':vBulletin.phrase.get('error'),
											'message':vBulletin.phrase.get('invalid_server_response_please_try_again'),
											'iconType':'error'
										});
									}
								},
								error:function(xhr, statusText, error){
									console.log('/index.php/ajax/api/page/fetchPageMapHierarchy failed, error: ' + error);
									openAlertDialog({
										'title':vBulletin.phrase.get('error'),
										'message':vBulletin.phrase.get('error_retrieving_page_map', xhr.status),
										'iconType':'error'
									});
								}
							});
						},
						close: function()
						{
						}
					});
					$('#page-map-dialog').dialog('open');
					return false;
				});

			})(); // end init page map overlay

		} // end of initPage()

		function selectLayout(targetLayout){
			if (!currentLayout) { //initialize current layout

				//only enable target layout's displaysections[] fields
				$('.canvas-layout.hide input[type=hidden]').prop('disabled', true);
				$('#' + targetLayout + ' input[type=hidden]').prop('disabled', false);

				currentLayout = targetLayout;
				return;
			}
			else if (currentLayout == targetLayout) { //do nothing if the same layout is already selected
				return;
			}
			else { //put widgets to the target layout in the same sections as the current layout

				//only enable target layout's displaysections[] fields
				$('.canvas-layout.hide input[type=hidden]').prop('disabled', true);
				$('#' + targetLayout + ' input[type=hidden]').prop('disabled', false);

				var targetLayoutSectionCount = sectionCount[targetLayout];
				var currentLayoutSectionCount = sectionCount[currentLayout];
				if (currentLayoutSectionCount > targetLayoutSectionCount) { //current layout has more sections than the target layout

					//put the widgets to the available target layout sections
					for (var i=0; i<targetLayoutSectionCount; i++) {

						$('#' + currentLayout + ' > .canvas-layout-row > div.section-' + i +' > div.canvas-widget').appendTo('#' + targetLayout + ' > .canvas-layout-row > div.section-' + i);
					}
					//put the widgets from the excess section(s) of the current layout to the bottom of the last section of the target layout
					var targetLayoutLastSection = targetLayoutSectionCount - 1;
					for (i=targetLayoutSectionCount; i<currentLayoutSectionCount; i++) {
						//if ($('#' + currentLayout + ' > div.section-' + i +' > div.canvas-widget').length > 0) {
							//$('#' + currentLayout + ' > div.section-' + i +' > div.canvas-widget').insertBefore($('.unassigned-widget-list div.clear:last'));
							$('#' + currentLayout + ' > .canvas-layout-row > div.section-' + i +' > div.canvas-widget').appendTo('#' + targetLayout + ' > .canvas-layout-row > div.section-' + targetLayoutLastSection);
							//showUnassignedWidgets = true;
						//}
					}
					//if (showUnassignedWidgets) {
					//	$('.unassigned-widget-list').show();
					//}
				}
				else { //number of sections in the current layout is <= to that of the target layout

					for (var i=0; i<currentLayoutSectionCount; i++) {
						$('#' + currentLayout + ' > .canvas-layout-row > div.section-' + i +' > div.canvas-widget').appendTo('#' + targetLayout + ' > .canvas-layout-row > div.section-' + i);
					}

				}
			}
			currentLayout = targetLayout;
		};

		function addWidgets(widgets) {
			//validate widgets array
			if (!$.isArray(widgets) || widgets.length == 0) {
				return;
			}

			window.vBulletin.loadingIndicator.show();
			$('body').css('cursor', 'wait');


			//get widget templates via AJAX
			$.ajax({
				url:pageData.baseurl + '/index.php/ajax/admin-template/widget',
				data:({
					'widgets': widgets,
	  				'pagetemplateid': $('#save-page-form #pagetemplateid-yes').val()
	  			}),
	  			type:'POST',
	  			dataType: 'json',
	  			complete:function(){
					console.log('admin-template/widget complete. moduleLoaded=' + modulesLoaded);
					if (modulesLoaded)
					{
						window.vBulletin.loadingIndicator.hide();
					}
					$('body').css('cursor', 'auto');
				},
	  			success:function(result){
					console.log('admin-template/widget successful! result:' + JSON.stringify(result));
					moduleInstancesLoaded = true;
					if (result && $.isArray(result.widgets)){
						$.each(result.widgets, function(index, widget){
							if (!widget.widgetid || Number(widget.widgetid) < 1 || !$.trim(widget.template)) return true; //skip
							var section = (widget.displaysection && Number(widget.displaysection) > 0) ? widget.displaysection : 0;
							var $addedModule = $(widget.template);

							$addedModule
								.appendTo($('.canvas-layout:not(.hide) .canvas-widget-list.section-' + section).height('auto')) //append widget template to the DOM
								.filter(':not(.container-widget)')
								.find('.toggle-button').trigger('click', [true]); //collapse the added module except the container widget
							$addedModule.find('.tabs').tabs(); //if there are jQuery Tab controls in the widget, initialize them
						});
					}
					else { //widgets in the ajax response is not an array
						openAlertDialog({
							'title':vBulletin.phrase.get('error'),
							'message':vBulletin.phrase.get('invalid_server_response_please_try_again'),
							'iconType':'error'
						});
					}
				},
				error:function(xhr, statusText, error){
					console.log('admin-template/widget failed! error:' + error);
					openAlertDialog({
						'title':vBulletin.phrase.get('error'),
						'message':vBulletin.phrase.get('error_adding_widgets', xhr.status),
						'iconType':'error'
					});
				}
			});

			return false;
		}

		function makeSortableChannels(){
			$('.channel-config-dialog .channel-list').sortable({
				placeholder: "main-channel-container-highlight drag-highlight clear",
				update: function(event, ui){
					ui.item.css('z-index', '0'); //for IE7
					channelsChanged.forum = true;
					hasConfigChanged = true;
				},
				sort:function(event, ui){
					//ui.item.addClass('shadow');
				},
				start:function(event, ui){
					//ui.item.removeClass('shadow');
					if ($.browser.msie && parseInt($.browser.version, 10) == 8){ //IE8 widget height is bigger
						ui.item.height(ui.item.height()-4);
					}
					ui.item.css('z-index', '99999'); //for IE7
					ui.placeholder.height(ui.item.outerHeight());
				},
				over:function(event, ui){
					//console.debug('list over');
				},
				receive:function(event, ui){
					//console.debug('list receive');
				},
				out:function(event, ui){
					//console.debug('list out');
				},
				handle:'.grip-icon-main',
				items:'.main-channel-container'
			});
		}

		function makeSortableMainForum(){
			$mainChannelSortable = $('.main-channel-container').sortable({
				connectWith: ".sub-channel-container",
				placeholder: "channel-item-highlight drag-highlight",
				revert:true,
				update: function(event, ui){//console.debug('main update');
					//ui.item.css('z-index', '0'); //for IE7

					var $mainChannelContainer = ui.item.closest('.main-channel-container');

					//check the main channel container from where the item was dragged from
					if (ui.sender && ui.sender.hasClass('main-channel-container')){
						//remove the main channel container where the channel item came from if it has no sub channel items
						if ($('> .channel-item-container', ui.sender).length == 0){
							ui.sender.slideUp('fast', function(){$(this).remove()});
						}
					}
					channelsChanged.forum = true;
					hasConfigChanged = true;
				},
				sort:function(event, ui){
					//ui.item.addClass('shadow');
				},
				activate:function(event, ui){
					//console.debug('main activate');
				},
				start:function(event, ui){//console.debug('main start');
					/*ui.item.removeClass('shadow');
					if ($.browser.msie && parseInt($.browser.version, 10) == 8){ //IE8 widget height is bigger
						ui.item.height(ui.item.height()-4);
					}*/
					//ui.item.css('z-index', '99999'); //for IE7
					//ui.placeholder.height(ui.item.height());
				},
				stop:function(event, ui){
					$('.main-channel-container, .sub-channel-container').height('auto');
					//$('.sub-channel-container', ui.item).show();
				},
				over:function(event, ui){
					//console.debug('main over');
				},
				receive:function(event, ui){
					//console.debug('main receive');
				},
				out:function(event, ui){
					//console.debug('main out');
				},
				handle:'.channel-item-inner > .grip-icon-item',
				items:'.channel-item-container'
			});
		}

		function makeSortableSubForum(){
			$subChannelSortable = $('.sub-channel-container').sortable({
				connectWith: ".sub-channel-container",
				revert:true,
				placeholder: "channel-item-highlight drag-highlight",
				update: function(event, ui){//console.debug('sub update');
					//ui.item.css('z-index', '0'); //for IE7
					//check the main channel container from where the item was dragged from
					if (ui.sender && ui.sender.hasClass('main-channel-container')){
						//remove the main channel container where the channel item came from if it has no sub channel items
						if ($('> .channel-item-container', ui.sender).length == 0){
							ui.sender.slideUp('fast', function(){$(this).remove()});
						}
					}
					channelsChanged.forum = true;
					hasConfigChanged = true;
				},
				sort:function(event, ui){//console.debug('sub sort');
					//ui.item.addClass('shadow');
				},
				start:function(event, ui){
					/*ui.item.removeClass('shadow');
					if ($.browser.msie && parseInt($.browser.version, 10) == 8){ //IE8 widget height is bigger
						ui.item.height(ui.item.height()-4);
					}*/
					//ui.item.css('z-index', '99999'); //for IE7
					//ui.placeholder.height(ui.item.height());
				},
				stop:function(event, ui){
					$('.main-channel-container, .sub-channel-container').height('auto');
				},
				over:function(event, ui){
					//console.debug('sub over');
				},
				receive:function(event, ui){
					//console.debug('sub receive');
				},
				out:function(event, ui){
					//console.debug('sub out');
				},
				handle:'.channel-item-inner > .grip-icon-item',
				items:'.channel-item-container'
			});
		}

		function addMainForum(channelId, parentId, channelTitle, isCategory, scrollToBottom){
			var categorySwitcher = '<div class="' + (isCategory ? 'category-to-channel' : 'channel-to-category') + '"><a href="#">' + vBulletin.phrase.get((isCategory ? 'make_forum' : 'make_category')) + '</a></div>';

			var $addedChannel =
				$(('<div class="main-channel-container">\
					<div class="grip-icon grip-icon-main {0}"><div>&uml;</div><div>&uml;</div><div>&uml;</div><div>&uml;</div><div>&uml;</div></div>\
					<div class="channel-item-container">\
						<div class="channel-item shadow" data-channel-id="{1}" data-parent-id="{4}">\
							<div class="channel-item-inner">\
								<div class="grip-icon grip-icon-item {0}"><div>&uml;</div><div>&uml;</div><div>&uml;</div><div>&uml;</div><div>&uml;</div></div>\
								<div class="channel-title"><div title="' + vBulletin.phrase.get('click_text_edit_title') + '">{2}</div><input type="text" name="channeltitle" value="{2}" /></div>\
								<div class="close-button" title="' + vBulletin.phrase.get('remove_forum') + '">x</div>\
								<div class="add-subchannel-button {3}" title="' + vBulletin.phrase.get('add_subforum') + '"><a href="#">+</a></div>\
								' + categorySwitcher + '\
								<div class="clear"></div>\
							</div>\
						</div>\
						<div class="sub-channel-container"></div>\
					</div>\
			  </div>').format(pageData.textDirLeft, channelId, channelTitle, pageData.textDirRight, parentId))
			.appendTo($('#top-level-forum .channel-list'));

			//scroll to the bottom
			if (scrollToBottom){
				var channelList = $('#top-level-forum .channel-config-dialog .channel-list').get(0);
				$(channelList).animate({scrollTop: channelList.scrollHeight - channelList.clientHeight}, 'fast');
			}

			//enable drag n drop to the added channel
			makeSortableMainForum();
			makeSortableSubForum();
			channelsChanged.forum = true;
			hasConfigChanged = true;

			return $addedChannel;
		}

		function addSubForum(channelId, parentId, channelTitle, isCategory, $parentChannel){
			var categorySwitcher = '<div class="' + (isCategory ? 'category-to-channel' : 'channel-to-category') + '"><a href="#">' + vBulletin.phrase.get((isCategory ? 'make_forum' : 'make_category')) + '</a></div>';

			var $subChannelContainer = $parentChannel.hasClass('main-channel-container') ? $('> .channel-item-container > .sub-channel-container', $parentChannel) : $('> .sub-channel-container', $parentChannel);
			var $subChannel = $(('<div class="channel-item-container">\
			       <div class="channel-item shadow" data-channel-id="{0}" data-parent-id="{4}">\
					   <div class="channel-item-inner">\
						   <div class="grip-icon grip-icon-item {1}"><div>&uml;</div><div>&uml;</div><div>&uml;</div><div>&uml;</div><div>&uml;</div></div>\
						   <div class="channel-title"><div title="Click text to edit title">{2}</div><input type="text" name="channeltitle" value="{2}" /></div>\
							<div class="close-button" title="' + vBulletin.phrase.get('remove_forum') + '">x</div>\
							<div class="add-subchannel-button {3}" title="' + vBulletin.phrase.get('add_subforum') + '"><a href="#">+</a></div>\
						   ' + categorySwitcher + '\
						   <div class="clear"></div>\
					   </div>\
			      </div>\
			      <div class="sub-channel-container"></div>\
			   </div>').format(channelId, pageData.textDirLeft, channelTitle, pageData.textDirRight, parentId))
			.appendTo($subChannelContainer);

			makeSortableSubForum();
			channelsChanged.forum = true;
			hasConfigChanged = true;
			return $subChannel;
		}

		function loadModules(){
			window.vBulletin.loadingIndicator.show();
			$('body').css('cursor', 'wait');

			//retrieve modules via AJAX
			$.ajax({
				url:pageData.baseurl + '/index.php/ajax/fetch-widget-admin-template-list',
				dataType: 'json',
				complete:function(){
					console.log('fetch-widget-admin-template-list complete. templatesLoaded=' + templatesLoaded);
					if (templatesLoaded) {
						window.vBulletin.loadingIndicator.hide();
						setPanelContentMinHeight();
					}
					$('body').css('cursor', 'auto');
					$(window).resize(resizePageEditorTabContentWidth);
				},
				success:function(result){
					console.log('fetch-widget-admin-template-list successful! result:');
					console.dir({'result':result});
					modulesLoaded = true;
					if ($.isArray(result)){
						if (result.length > 0){
							var categories = {}, moduleCount = 0, customizedCopyWidgetIds = [];

							//add the "my custom modules" category at the beginning of the list
							categories['customized_copy'] = {count:0, title:vBulletin.phrase.get('my_custom_modules')};

							$.each(result, function(index, widget){
								if (!widget.widgetid || Number(widget.widgetid) < 1) return true; //skip
								moduleCount++;

								if (!categories[widget.category]){
									categories[widget.category] = {count:1, title: widget.category_title};
								}
								else {
									categories[widget.category].count++;
								}

								//append widget to the list putting additional info
								var $template = $('#edit-page-dropdown .module-list .module-icon-template').clone();
								$template
									.attr('widget-id', widget.widgetid)
									.attr('data-title', $.trim(widget.title).toLowerCase())
									.removeClass('module-icon-template canvas-widget')
									.addClass(('module-item list-item category-{0}' + (widget.cloneable == '1' ? ' module-cloneable' : '')).format(widget.category));
								$('.module-icon', $template).html($('<img />')
									.attr('src', pageData.baseurl + '/' + pageData.admincpdir + '/img/' + $.trim(widget.icon))
									.attr('height', 60)
									.attr('width', 60)
									.attr('alt', vBulletin.phrase.get('module_icon'))
									);
								$('.module-title .main-title', $template).html($.trim(widget.title));
								$template.appendTo('#edit-page-dropdown .module-list').removeClass('hide');

								if (widget.category == 'customized_copy')
								{
									customizedCopyWidgetIds.push(widget.widgetid);
								}
							});

							// remove 'edit' link for all custom modules already on the page
							$('.canvas-layout-container .canvas-widget').filter(function(){
								var widgetId = $(this).attr('widget-id');
								return ($.inArray(widgetId, customizedCopyWidgetIds) != -1);
							}).find('.module-buttons .edit-button').hide();

							//give all custom modules edit/rename/delete links
							$('<div class="custom-module-manage-links">\
								<a href="#" class="edit">' + vBulletin.phrase.get('edit') + '</a> \
								<a href="#" class="rename">' + vBulletin.phrase.get('rename') + '</a> \
								<a href="#" class="delete">' + vBulletin.phrase.get('delete') + '</a>\
							</div>').appendTo('#add-modules .module-list .category-customized_copy');

							// click handler for custom modules edit/rename/delete links
							$('#add-modules').delegate('.custom-module-manage-links a', 'click', function(e)
							{
								e.preventDefault();
								var clickType = $(this).attr('class');
								var canvas = $(this).closest('.canvas-widget');
								if (clickType == 'edit')
								{
									canvas.find('.module-buttons .admin-only .edit-button').click();
									canvas.find('.module-buttons .admin-only .edit-button').click();
								}
								else if (clickType == 'rename')
								{
									// Disable drag & drop for this module
									canvas.draggable("disable");

                                    var renamelink = $(this);
                                    renamelink.hide();
                                    var maintitle = $('.main-title', canvas);
                                    var currenttitle = maintitle.text();
                                    maintitle.html('<input type="text" class="titleinput textbox" autocomplete="off" style="-moz-user-select:text;width:100%;" value="' + currenttitle + '"> ' +
                                        '<a href="#" class="save">' + vBulletin.phrase.get('save') + '</a> ' +
                                        '<a href="#" class="cancel">' + vBulletin.phrase.get('cancel') + '</a>');
                                    $('a.save', maintitle).click(function(e) {
                                        e.preventDefault();

                                        if ($('.titleinput', maintitle).val() == '')
                                        {
                                            openAlertDialog({
                                                'title':vBulletin.phrase.get('rename_custom_module'),
                                                'message':vBulletin.phrase.get('please_enter_new_module_title'),
                                                'iconType':'warning',
                                                'onAfterClose':function(){
                                                    $('.titleinput', maintitle).focus();
                                                }
                                            });
                                        }
                                        $('body').css('cursor', 'wait');

                                        $.ajax({
                                            url:pageData.baseurl + '/index.php/ajax/api/widget/renameWidget',
                                            type:'POST',
                                            data:{widgetId:canvas.attr('widget-id'),newtitle:$('.titleinput', maintitle).val()},
                                            dataType: 'json',
                                            success:function(result){
                                                $('body').css('cursor', 'auto');

                                                if (result === true){
                                                    currenttitle = $('.titleinput', maintitle).val();
                                                    maintitle.text(currenttitle);
                                                    renamelink.show();
                                                }
                                                else {
                                                    openAlertDialog({
                                                        'title':vBulletin.phrase.get('error'),
                                                        'message':vBulletin.phrase.get('invalid_server_response_please_try_again'),
                                                        'iconType':'error',
                                                        'onAfterClose':function(){
                                                            $('#config-dialog .action-buttons button').prop('disabled', false);
                                                        }
                                                    });
                                                }
                                            },
                                            error:function(xhr, statusText, error){
                                                $('body').css('cursor', 'auto');
                                                openAlertDialog({
                                                    'title':vBulletin.phrase.get('rename_custom_module'),
                                                    'message':vBulletin.phrase.get('error_renaming_module_title'),
                                                    'iconType':'error',
                                                    'onAfterClose':function(){
                                                        $('.titleinput', maintitle).focus();
                                                    }
                                                });
                                            },
                                            complete:function(xhr, statusText){
                                                canvas.draggable("enable");
                                            }
                                        });
                                    })
                                    $('a.cancel', maintitle).click(function(e) {
                                        e.preventDefault();
                                        maintitle.text(currenttitle);
                                        renamelink.show();
                                        canvas.draggable("enable");
                                    })
								}
								else if (clickType == 'delete')
								{
									alert('Deleting is not yet implemented');
								}
							});

							//add "create new custom module" button
							$('<div id="create-custom-module" class="non-module-item canvas-widget module-item list-item category-customized_copy hide">\
								<div class="widget-header">\
									<div class="module-icon"><a href="#" title="' + vBulletin.phrase.get('create_new_custom_module') + '"><img width="60" height="60" alt="Create New Custom Module" src="' + pageData.baseurl + '/admincp/img/module-icon-create-new.png"></a></div>\
									<div class="module-title left"><a href="#" title="' + vBulletin.phrase.get('create_new_custom_module') + '">' + vBulletin.phrase.get('create_new_custom_module') + '</a></div>\
									<div class="clear"></div>\
								</div>\
							</div>').prependTo('#edit-page-dropdown .module-list');

							//create new custom module dialog
							$('#create-custom-module a').click(function()
							{
								$('#create-new-module-dialog').dialog(
								{
									title: vBulletin.phrase.get('choose_base_module'),
									autoOpen: true,
									modal: true,
									resizable: false,
									closeOnEscape: true,
									showCloseButton: true,
									width: 950,
									dialogClass: 'dialog-container pagemap-dialog-container input-dialog',
									create: function()
									{
										$('#create-new-module-dialog .cancel-button').click(function()
										{
											$('#create-new-module-dialog').dialog('close');
										});

										$modulelist = $('.module-list-container').clone();

										$('#create-new-module-dialog .dialog-module-container').append($modulelist);
										$('#create-new-module-dialog #create-custom-module').remove();
										$('#create-new-module-dialog .module-item').not('.module-cloneable').remove();

										// recalculate category counts
										$('#create-new-module-dialog .categories .category').each(function()
										{
											var category = $(this).attr('id').substr('category-'.length);
											var categoryCount = $('#create-new-module-dialog .module-item').filter('.category-' + category).size();
											if (category == 'all')
											{
												$(this).text('All ({0})'.format($('#create-new-module-dialog .module-item').size()));
											}
											else if (categoryCount < 1)
											{
												$(this).hide();
											}
											else
											{
												$(this).text((categories[category].title + ' ({0})').format(categoryCount));
											}
										});

										$('#create-new-module-dialog .module-list').css('width', '800px');
										$('#create-new-module-dialog .module-item').css('cursor', 'pointer');

										$('#create-new-module-dialog .module-item').click(function()
										{
											window.vBulletin.loadingIndicator.show();

											// clone widget, insert it in the parent list, and close dialog
											var widgetId = $(this).attr('widget-id');
											$.ajax(
											{
												url:pageData.baseurl + '/index.php/ajax/api/widget/cloneWidget',
												data:({
													'widgetId': widgetId
												}),
												type:'POST',
												dataType: 'json',
												complete:function()
												{
													console.log('/index.php/ajax/api/widget/cloneWidget complete');
													$('body').css('cursor', 'auto');
												},
												success:function(result)
												{
													if (result && typeof result.widget == 'object')
													{
														console.log('/index.php/ajax/api/widget/cloneWidget successful');
														console.log(result);

														// make ajax call here to get the widget template and insert it into the scroller
														// then "flash" it.
														$.ajax(
														{
															url:pageData.baseurl + '/index.php/ajax/fetch-widget-admin-template-list',
															data:({
																'widgetids': [result.widget.widgetid]
															}),
															type:'POST',
															dataType: 'json',
															success:function(result)
															{
																if ($.isArray(result) && result.length == 1)
																{
																	var widget = result[0];

																	console.log('/index.php/ajax/fetch-widget-admin-template-list successful');
																	console.log(widget);

																	// @todo insert the new widget into the list.
																	++categories[widget.category].count;

																	//append widget to the list putting additional info
																	var $newModule = $('#edit-page-dropdown .module-list .module-icon-template').clone();
																	$newModule
																		.attr('widget-id', widget.widgetid)
																		.attr('data-title', $.trim(widget.title).toLowerCase())
																		.removeClass('module-icon-template')
																		.addClass(('module-item list-item category-{0}' + (widget.cloneable == '1' ? ' module-cloneable' : '')).format(widget.category));
																	$('.module-icon', $newModule).html($('<img />')
																		.attr('src', pageData.baseurl + '/' + pageData.admincpdir + '/img/' + $.trim(widget.icon))
																		.attr('height', 60)
																		.attr('width', 60)
																		.attr('alt', vBulletin.phrase.get('module_icon'))
																		);
																	$('.module-title .main-title', $newModule).html($.trim(widget.title));
																	$newModule.insertAfter('#add-modules #create-custom-module').removeClass('hide');

																	// make draggable (to canvas)
																	$newModule.draggable({
																		connectToSortable: ".canvas-layout-row > .canvas-widget-list:visible",
																		helper: "clone",
																		revert: "invalid",
																		appendTo:'#add-modules .module-list-container',
																		zIndex:2000,
																		start: function(event, ui){
																			moduleDragStart = true;

																		},
																		stop: function(event, ui){
																			moduleDragStart = false;
																		}
																	}).disableSelection();

																	// recalculate category count
																	var categoryCount = $('#add-modules .module-item').filter('.category-customized_copy').not('.non-module-item').size();
																	$('#add-modules #category-customized_copy').text((categories['customized_copy'].title + ' ({0})').format(categoryCount));

																	// update scrollbar
																	$('#add-modules #category-all').click();
																	$('#add-modules #category-customized_copy').click();

																	// give the modules edit/rename/delete links
																	$('<div class="custom-module-manage-links">\
																		<a href="#" class="edit">' + vBulletin.phrase.get('edit') + '</a> \
																		<a href="#" class="rename">' + vBulletin.phrase.get('rename') + '</a> \
																		<a href="#" class="delete">' + vBulletin.phrase.get('delete') + '</a>\
																	</div>').appendTo($newModule);

																	window.vBulletin.loadingIndicator.hide();

																	$newModule.css('background-color', '#2E3741');
																	$newModule.effect('highlight', {'color':'#FFFF00'}, 2000, function()
																	{
																		$(this).css('background-color', 'transparent');
																	});
																}
																else
																{
																	console.log('/index.php/ajax/fetch-widget-admin-template-list successful, but response was not an array');
																	console.log(result);
																	openAlertDialog({
																		'title':vBulletin.phrase.get('error'),
																		'message':vBulletin.phrase.get('invalid_server_response_please_try_again'),
																		'iconType':'error'
																	});
																}
															},
															error:function(xhr, statusText, error){
																console.log('/index.php/ajax/fetch-widget-admin-template-list failed, error: ' + error);
																openAlertDialog({
																	'title':vBulletin.phrase.get('error'),
																	'message':vBulletin.phrase.get('error_retrieving_cloned_widget_template', xhr.status),
																	'iconType':'error'
																});
															}
														}); // end ajax call


														$('#create-new-module-dialog').dialog('close');
													}
													else
													{
														console.log('/index.php/ajax/api/widget/cloneWidget successful, but response was not an array');
														console.log(result);
														openAlertDialog({
															'title':vBulletin.phrase.get('error'),
															'message':vBulletin.phrase.get('invalid_server_response_please_try_again'),
															'iconType':'error'
														});
													}
												},
												error:function(xhr, statusText, error){
													console.log('/index.php/ajax/api/widget/cloneWidget failed, error: ' + error);
													openAlertDialog({
														'title':vBulletin.phrase.get('error'),
														'message':vBulletin.phrase.get('error_cloning_widget', xhr.status),
														'iconType':'error'
													});
												}
											}); // end ajax call
										}); // end module item click handler
									}, // end 'create' handler
									close: function()
									{
										$('#create-new-module-dialog .dialog-module-container').html('');
										$('#create-new-module-dialog').dialog('destroy');
									},
									open: function()
									{
										var resizeCreateNewModuleDialogListWidth = function()
										{
											var $listItems = $('#create-new-module-dialog .list-item');
											var newWidth = Math.max(
												$listItems.outerWidth(true) * $listItems.filter(':visible').length,
												parseFloat($listItems.parent().css('min-width'), 10)
											);
											$listItems.parent().width(newWidth);
											//alert('new width: ' + newWidth);
										};

										// manually resize list width, since inner items float
										//resizeListWidth(x);
										resizeCreateNewModuleDialogListWidth();

										//$('#create-new-module-dialog .module-list-container').width(700);

										//initialize Tiny Scrollbar
										customScrollbars[3] = $('#create-new-module-dialog .module-list-container');
										customScrollbars[3].tinyscrollbar({
											sizethumb: 14,
											axis:'x',
											update:function(){}
										});
										customScrollbars[3].tinyscrollbar_update();

										//category click event handler
										$('#create-new-module-dialog .categories .category').click(function(e){
										//$('body').delegate('.module-list-container .categories .category', 'click', function(e){
											e.stopPropagation();
											//if ($(this).hasClass('selected')) return false;

											var $addModules = $(this).closest('.module-list-container');
											var $moduleItems = $('.module-item', $addModules);

											$('.category.selected', $addModules).removeClass('selected');
											$(this).addClass('selected');

											$moduleItems.hide();
											$('.empty-module', $addModules).hide();

											var categoryId = this.id;
											if (categoryId == 'category-all'){
												$moduleItems.show();
												$('.non-module-item', $addModules).hide();
												resizeCreateNewModuleDialogListWidth();
												customScrollbars[3].tinyscrollbar_update();
											}
											else if (categoryId == 'category-result'){
												$('#search-module-keyword').triggerHandler('keyup', [true]);

											}
											else {
												$('.module-item.{0}'.format(categoryId), $addModules).show();
												resizeCreateNewModuleDialogListWidth();
												customScrollbars[3].tinyscrollbar_update();
											}
											return false;
										}).disableSelection();

										// activate the "all" tab
										$('#create-new-module-dialog #category-all').click();

									} // end 'open' handler
								});
								return false;
							}); // end 'create new custom module' dialog

							//append 'All' and 'Search Result' categories
							$(('<div class="category-arrow-left {0}" title="' + vBulletin.phrase.get('previous') + '">&lsaquo;</div>\
							   <div class="scroller category {0}">\
							       <div class="categories {0}">\
							           <div id="category-all" class="category selected">' + vBulletin.phrase.get('all') + ' ({1})</div>\
							           <div id="category-result" class="category hide">' + vBulletin.phrase.get('search_results') + ' (<span></span>)</div>\
							       </div>\
							   </div>\
							   <div class="category-arrow-right {0}" title="' + vBulletin.phrase.get('next') + '">&rsaquo;</div>\
							   <div class="clear"></div>').format(pageData.textDirLeft, moduleCount)
							  ).insertBefore('#edit-page-dropdown .module-list-container .scroller');

							//append the categories
							var totalWidth = 0;
							$.each(categories, function(index, category){
								var $category = $('<div id="category-{0}" class="category">{1} ({2})</div>'.format(index, category.title, category.count)).insertBefore('#category-result');
								totalWidth += $category.outerWidth(true);
							});

							//resize categories list width
							var categoryWidth = totalWidth + $('#category-all').outerWidth(true);
							$('.categories').width(categoryWidth);
							if ($('.categories').width() <= $('.scroller.category').width()){
								$('.category-arrow-left, .category-arrow-right').css('visibility', 'hidden');
							}
							else {
								$('.category-arrow-right').css('visibility', 'visible');
							}

							//resize module list width
							resizeListWidth(0);

							//initialize Tiny Scrollbar
							customScrollbars[0] = $('#add-modules .module-list-container');
							customScrollbars[0].tinyscrollbar({
								sizethumb: 14,
								axis:'x',
								update:function(){
									if ($('#add-modules .module-list-container').innerHeight() < $('#add-modules .panel-header-text').height()) {
										$('#add-modules .panel-header-text').height($('#add-modules .module-list-container').innerHeight());
									}
								}
							});


							//make each module item draggable to the canvas
							$('#edit-page-dropdown .module-list .module-item').not('.non-module-item').draggable({
								connectToSortable: ".canvas-layout-row > .canvas-widget-list:visible",
								helper: "clone",
								revert: "invalid",
								appendTo:'#add-modules .module-list-container',
								zIndex:2000,
								start: function(event, ui){
									moduleDragStart = true;
								},
								stop: function(event, ui){
									moduleDragStart = false;
								}
							}).disableSelection();

							//search module autocomplete
							var searchStarted = false;
							$('#search-module-keyword').bind('keyup', function(event, manuallyTriggered){
								var $addModules = $('#add-modules');
								var $resultCategory = $('#category-result');
								var $categories = $('.categories', $addModules);
								var $scroller = $('.scroller.category', $addModules);
								var showAll = false;

								$('.module-item', $addModules).hide();
								if (!manuallyTriggered){
									$('.category.selected', $addModules).removeClass('selected');
								}

								//search module title on the data-title attribute
								//if search keyword is blank, all modules should be displayed
								var keyword = $.trim(this.value.toLowerCase());
								if (keyword){
									$('.module-item[data-title*="{0}"]'.format(keyword), $addModules).show();
									$resultCategory.removeClass('hide').addClass('selected');
								}
								else { //show all modules
									$('.module-item', $addModules).show();
									$('#category-all').removeClass('hide').addClass('selected');
									$resultCategory.addClass('hide').removeClass('selected');
									showAll = true;
								}

								var visibleModuleCount = $('.module-item:visible', $addModules).length;
								$('span', $resultCategory).text(visibleModuleCount);

								resizeListWidth(0);
								customScrollbars[0].tinyscrollbar_update();

								//show message when there are no modules in the search result
								if (visibleModuleCount == 0){
									$('.empty-module', $addModules).show();
								}
								else {
									$('.empty-module', $addModules).hide();
								}

								if (showAll) {
									$categories.width(categoryWidth);
								}
								else {
									$categories.width(categoryWidth + $resultCategory.outerWidth(true));
								}
								if ($categories.width() <= $scroller.width()){
									$('.category-arrow-left, .category-arrow-right', $addModules).css('visibility', 'hidden');
									$scroller.scrollLeft(0);
								}
								else {
									if (showAll){ //scroll 'All' category into view
										$('.category-arrow-left', $addModules).css('visibility', 'hidden');
										$('.category-arrow-right', $addModules).css('visibility', 'visible');

										$scroller.scrollLeft(0);
									}
									else { //scroll 'Search Result' category at the end into view
										$('.category-arrow-left', $addModules).css('visibility', 'visible');
										$('.category-arrow-right', $addModules).css('visibility', 'hidden');

										var scrollerDom = $scroller.get(0);
										$scroller.scrollLeft(scrollerDom.scrollWidth - scrollerDom.clientWidth);
									}
								}

								return true;
							});

							//category click event handler
							$('#add-modules .categories .category').click(function(e){
							//$('body').delegate('.module-list-container .categories .category', 'click', function(e){
								e.stopPropagation();
								if ($(this).hasClass('selected')) return false;

								//var $addModules = $('#add-modules');
								var $addModules = $(this).closest('.module-list-container');
								var $moduleItems = $('.module-item', $addModules);

								$('.category.selected', $addModules).removeClass('selected');
								$(this).addClass('selected');

								$moduleItems.hide();
								$('.empty-module', $addModules).hide();

								var categoryId = this.id;
								if (categoryId == 'category-all'){
									$moduleItems.show();
									$('.non-module-item', $addModules).hide();
									resizeListWidth(0);
									customScrollbars[0].tinyscrollbar_update();
								}
								else if (categoryId == 'category-result'){
									$('#search-module-keyword').triggerHandler('keyup', [true]);

								}
								else {
									$('.module-item.{0}'.format(categoryId), $addModules).show();
									resizeListWidth(0);
									customScrollbars[0].tinyscrollbar_update();
								}
								return false;
							}).disableSelection();

							//category left and right arrows click event handler
							var scrollTimer;
							$('.category-arrow-left').bind({
								mousedown: function(){
									$('.category-arrow-right').css('visibility', 'visible');
									scrollTimer = setInterval(function(){
										var $scroller = $('.scroller.category');
										$scroller.scrollLeft($scroller.scrollLeft() - 20);
										if ($scroller.scrollLeft() == 0 ){
											$('.category-arrow-left').css('visibility', 'hidden');
											clearInterval(scrollTimer);
										}
									}, 50);
								},
								mouseup: function(){
									clearInterval(scrollTimer);
								}
							}).disableSelection();

							$('.category-arrow-right').bind({
								mousedown: function(){
									$('.category-arrow-left').css('visibility', 'visible');
									scrollTimer = setInterval(function(){
										var $scroller = $('.scroller.category');
										$scroller.scrollLeft($scroller.scrollLeft() + 20);
										var scrollerDom = $scroller.get(0);
										if ($scroller.scrollLeft() == scrollerDom.scrollWidth - scrollerDom.clientWidth){
											$('.category-arrow-right').css('visibility', 'hidden');
											clearInterval(scrollTimer);
										}
									}, 50);
								},
								mouseup: function(){
									clearInterval(scrollTimer);
								}
							}).disableSelection();
						}
						else { //no modules retrieved
							$('<div class="empty-module">' + vBulletin.phrase.get('no_modules') + '</div>').appendTo('#edit-page-dropdown .module-list');
						}
					}
					else { //widgets in the ajax response is not an array
						openAlertDialog({
							'title':vBulletin.phrase.get('error'),
							'message':vBulletin.phrase.get('invalid_server_response_please_try_again'),
							'iconType':'error'
						});
					}
				},
				error:function(xhr, statusText, error){
					console.log('fetch-widget-admin-template-list failed! error:' + error);
					window.vBulletin.loadingIndicator.hide();
					openAlertDialog({
						'title':vBulletin.phrase.get('error'),
						'message':vBulletin.phrase.get('error_retrieving_modules', xhr.status),
						'iconType':'error'
					});
				}
			});
		}

		function loadTemplates(){

			window.vBulletin.loadingIndicator.show();
			$('body').css('cursor', 'wait');

			//reset template list
			$('#edit-page-dropdown .template-list').empty();

			$.ajax({
				url:pageData.baseurl + '/index.php/ajax/api/pagetemplate/fetchPageTemplateList',
				dataType: 'json',
	  			complete:function(){
					console.log('fetchPageTemplateList complete.');
					if (modulesLoaded) {
						window.vBulletin.loadingIndicator.hide();
						setPanelContentMinHeight();
					}
					$('body').css('cursor', 'auto');
				},
	  			success:function(templates){
					console.log('fetchPageTemplateList successful! result:');
					console.dir({'templates':templates});
					templatesLoaded = true;
					//check results
					if ($.isArray(templates) && templates.length > 0) {
						$.each(templates, function(index, template) {
							$('<div class="template-item list-item {0}">\
									<input type="radio" id="pagetemplateid-{1}" name="pagetemplateid" value="{1}" data-thumbnail="{2}/{3}/img/template-icon-default.png"{4} />\
									<label class="label">{5}</label>\
							   </div>'.format(
									pageData.textDirLeft,
									template.pagetemplateid,
									pageData.baseurl,
									pageData.admincpdir,
									(!newPage && $('#save-page-form #pagetemplateid-yes').val() == template.pagetemplateid) ? ' checked="checked"' : '',
									template.title)
							).appendTo('#edit-page-dropdown .template-list')
							 .data({
								 'screenlayoutid': template.screenlayoutid,
								 'widgetinstances': template.widgetinstances
							 });
						});

						$('.template-item', $('#edit-page-dropdown .template-list')).each(function(index) {
							$(this).attr('data-title', $('.label', $(this)).text().toLowerCase());
						});

						//search template autocomplete
						$('#search-template-keyword').bind('keyup', function (e) {
							if(e.keyCode == 13) {
								e.preventDefault();
								return false;
							}

							var $selectTemplates = $('#select-template');
							var $scroller = $('.scroller', $selectTemplates);
							var showAll = false;

							$('.template-item', $selectTemplates).hide();

							//search template title on the data-title attribute
							//if search keyword is blank, all modules should be displayed
							var keyword = $.trim(this.value.toLowerCase());
							if (keyword) {
								$('.template-item[data-title*="{0}"]'.format(keyword), $selectTemplates).show();
							}
							else {
								$('.template-item', $selectTemplates).show();
								showAll = true;
							}

							var visibleTemplateCount = $('.template-item:visible', $selectTemplates).length;

							resizeListWidth(2);
							customScrollbars[2].tinyscrollbar_update();

							//show message when there are no modules in the search result
							if (visibleTemplateCount == 0) {
								$('.empty-template', $selectTemplates).show();
							}
							else {
								$('.empty-template', $selectTemplates).hide();
							}

							return true;
						});
						// When user presses enter, prevent the form from being submitted
						$('#search-template-keyword').keydown(function(e) {
							if(e.keyCode == 13) {
								e.preventDefault();
								return false;
							}
						});

						//transform template radio buttons as thumbnails
						$templateThumbnails = $('#edit-page-dropdown .template-list .template-item input[type=radio]').thumbnailRadioCheckbox({
							thumbnailClass:'template-border',
							preselect:function($thumbnail, $radio){
								if ($radio.is(':checked')) {
									return false;
								}
								if (hasCanvasChanged || hasConfigChanged){
									openConfirmDialog({
										'title': vBulletin.phrase.get('switch_template'),
										'message': vBulletin.phrase.get('template_changes_will_be_lost'),
										'iconType':'warning',
										'onClickYes':function(){
											hasCanvasChanged = false;
											hasConfigChanged = false;
											templateChanged = true;
											$templateThumbnails.thumbnailRadioCheckbox('check', $radio, true);
										}
									});
									return false;
								}
								templateChanged = true;
								return true;
							},
							select:function($thumbnail, $radio){
							 	$('.canvas-layout').addClass('hide');

								var screenlayoutid = $radio.closest('.template-item').data('screenlayoutid');

								//show associated screen layout
								$('.canvas-layout[layout-id=' + screenlayoutid + ']').removeClass('hide');
								setCanvasStaticWidth();
								setCanvasStaticHeight();

								//update page template id in the page save and module config forms
								$('#save-page-form #pagetemplateid-yes, #config_pagetemplateid').val($radio.val());

								//load associated modules
								if (templateChanged){
									//reset modules
									$('.canvas-widget-list').empty();

									var widgetInstances = $radio.closest('.template-item').data('widgetinstances');
									if ($.isArray(widgetInstances) && widgetInstances.length > 0){
										moduleInstancesLoaded = false;
										var widgets = [];
										$.each(widgetInstances, function(index, widget){
											widgets.push({widgetid: widget.widgetid, widgetinstanceid: widget.widgetinstanceid});
										});
										addWidgets(widgets, true);
										onModuleAddOrRemove();
									}
									else {
										window.vBulletin.loadingIndicator.hide();
									}
								}

								//if you select a template, the overwrite template options in the Save Page form should always be visible even for New Page
								//if we change the body CSS class from 'lnkNewPage' to 'lnkEditPage', it will automatically take care of hiding/showing appropriate fields.
								$('body').removeClass('lnkNewPage').addClass('lnkEditPage');
								$('#save-page-form .new-page-template input').prop('disabled', true);
								$('#save-page-form .edit-page-template input').prop('disabled', false);

								templateChanged = true;
							},
							unselect:function(){
							}
						});

						resizeListWidth(2);

						//initialize Tiny Scrollbar for template list
						customScrollbars[2] = $('#select-template .template-list-container');
						customScrollbars[2].tinyscrollbar({
							sizethumb: 14,
							axis:'x',
							update:function(){
								if ($('#select-template .template-list-container').innerHeight() < $('#select-template .panel-header-text').height()) {
									$('#select-template .panel-header-text').height($('#select-template .template-list-container').innerHeight());
								}
							}
						});
					}
					else {
						window.vBulletin.loadingIndicator.hide();
						openAlertDialog({
							'title':vBulletin.phrase.get('error'),
							'message':vBulletin.phrase.get('error_retrieving_templates'),
							'iconType':'error'
						});
					}
				},
				error:function(xhr, statusText, error){
					console.log('fetchPageTemplateList failed! error:' + error);
					window.vBulletin.loadingIndicator.hide();
					openAlertDialog({
						'title':vBulletin.phrase.get('error'),
						'message':vBulletin.phrase.get('error_retrieving_modules', xhr.status),
						'iconType':'error'
					});
				}
			});
		}

		function displaySubChannels(subchannels, $parentChannel){
			$.each(subchannels, function(j, subChannel){
				//var $parentSubChannel = $('<li data-channel-id="{0}">Sub-Channel: <span>{1}</span><ul class="widget-subchannel-list"></ul></li>'.format(subChannel.nodeid, subChannel.title)).appendTo($('> .widget-subchannel-list', $parentChannel));
				var $parentSubChannel = $(('<div class="sub-channel channel" data-channel-id="{0}" data-parent-id="{7}">\
					<div class="avatar {1}"></div>\
					<div class="title"><a href="{2}{3}">{4}</a></div>\
					<div class="info">\
						<span class="label">' + vBulletin.phrase.get('last_post') + ':</span>\
						<span class="title">{5}</span>\
					</div>\
					<div class="clear"></div>').format(
						subChannel.nodeid,
						pageData.textDirLeft,
						pageData.baseurl,
						subChannel.url,
						subChannel.title,
						(subChannel.lastPostTitle ? subChannel.lastPostTitle : '<em>' + vBulletin.phrase.get('none') + '</em>'),
						pageData.baseurl_core,
						subChannel.parentid
					))
					.appendTo($parentChannel);

					displaySubChannels(subchannels[j].subchannels, $parentSubChannel.eq(0));
			});
		}

		function addSubForums($subchannels, $parentChannel){
			$.each($subchannels, function(index, sub){
				var $parentSubChannel = addSubForum(sub.nodeid, sub.parentid, sub.title, sub.category, $parentChannel);
				addSubForums(sub.subchannels, $parentSubChannel);
		 	});
		}

		function setPanelContentMinHeight(){
			//open the tab to get the height of its tab content
			//this won't be visible in the eye so this should be fine
			//Add Modules tab
			$pageEditorTabs.tabs('select', 0);
			var addModuleHeight = $('#add-modules').height();

			//Change Layout tab
			$pageEditorTabs.tabs('select', 1);
			var changeLayoutHeight = $('#change-layout').height();

			//Select Template tab
			$pageEditorTabs.tabs('select', 2);
			var selectTemplateHeight = $('#select-template').height();

			//Color Style tab
			//$pageEditorTabs.tabs('select', 3);
			//var colorStyleHeight = $('#color-style').height();

			//Save Page form
			$('#edit-page-dropdown .lnkSaveChanges').trigger('click');
			var savePageHeight = $('#save-page-form').height();
			//reset to default tab
			$pageEditorTabs.tabs('select', 0);

			//now get the tallest tab content
			var minHeight = Math.max(
				addModuleHeight,
				changeLayoutHeight,
				selectTemplateHeight,
				//colorStyleHeight,
				savePageHeight
			);

			//then set the min-height of each tab content with the tallest height
			var $panelHeaderText = $('#edit-page-dropdown .panel-header-text');
			$panelHeaderText.each(function(){
				var self = $(this);
				self.css('min-height', minHeight - parseFloat(self.css('margin-top')) - parseFloat(self.css('margin-bottom')) - parseFloat(self.css('padding-top')) - parseFloat(self.css('padding-bottom')));
			});

			var $panelMainContent = $('#edit-page-dropdown .panel-main-content');
			$panelMainContent.each(function(){
				var self = $(this);
				self.css('min-height', minHeight - parseFloat(self.css('margin-top')) - parseFloat(self.css('margin-bottom')) - parseFloat(self.css('padding-top')) - parseFloat(self.css('padding-bottom')));
			});
		}

		function resizeListWidth(tabIndex){
			//resize the width of the templates, layouts or modules list in order for it to be scrolled
			//the contents of these lists are floating elements, so we have to manually resize the width
			var $listItem = $('#edit-page-dropdown #edit-content > .tabs > .tab:eq({0}) .list > .list-item'.format(tabIndex));
			$listItem.parent().width(
				Math.max(
					$listItem.outerWidth(true) * $listItem.filter(':visible').length),
					parseFloat($listItem.parent().css('min-width')
				)
			);
		}

		function toggleAllModuleContentVisibility(show, $exceptSelector){
			var $widgetContents = ($exceptSelector && $exceptSelector.length > 0) ?
				$('.canvas-layout .canvas-widget').not($exceptSelector).find('.widget-content') :
				$('.canvas-layout .canvas-widget .widget-content');
			if (show) {
				$widgetContents.each(function(){
					if ($(this).is(':hidden')){
						$(this).closest('.canvas-widget').find('.widget-header .toggle-button').trigger('click', [true]); //show module without animation
					}
				});
			}
			else {
				$widgetContents.each(function(){
					if (!$(this).is(':hidden')){
						$(this).closest('.canvas-widget').find('.widget-header .toggle-button').trigger('click', [true]); //hide module without animation
					}
				});
			}
		}

		function toggleModuleContentVisibility($module, show){
			if (show) {
				if ($module.find('.widget-content').is(':hidden')){
					$module.find('.toggle-button').trigger('click', [true]); //show module without animation
				}
			}
			else {
				if (!$module.find('.widget-content').is(':hidden')){
					$module.find('.toggle-button').trigger('click', [true]); //hide module without animation
				}
			}
		}

		function onModuleAddOrRemove(){ //there must be at least one Channel module for existing page
			// todo: this behavior needs to be implemented in a different way (e.g. when editing a new page).
			// Alan will send new specs related to "fixed" modules in a page
			if (!newPage){
				var $channelModules = $('.canvas-layout:visible .canvas-widget.channel-widget');
				if ($channelModules.length == 1){ //hide Remove button
					$channelModules.find('.close-button').hide();
				}
				else {
					$channelModules.find('.close-button').show();
				}
			}
		}

		function fetchModuleTemplate(item, onAfterFetch)
		{
			var widgetId = item.attr('widget-id');
			if (moduleTemplates[widgetId] == null)
			{
				window.vBulletin.loadingIndicator.show();
				$('body').css('cursor', 'wait');

				// fetch module template
				$.ajax(
				{
					url:pageData.baseurl + '/index.php/ajax/fetch-widget-template',
					data:({
						'widgetid': widgetId
					}),
					type:'POST',
					dataType: 'json',
					complete: function()
					{
						window.vBulletin.loadingIndicator.hide();
						$('body').css('cursor', 'auto');
					},
					success:function(result)
					{
						console.log('Fetching module template successful');

						var template = $.trim(result);
						if (template)
						{
							var $template = $(template.replace(/\<\s*script[^\>]*\>(.*?)\<\s*\/\s*script\>/g, '')); //we don't need the js in widget template for Add Modules tab
							$template
								.attr('data-title', function(){
										var $title = $('.module-title', $template).clone();
										$title.find('.hide-on-viewmode').children().unwrap();
										$title.find('*:hidden').remove();
										return $.trim($title.text()).toLowerCase();
									})

							moduleTemplates[widgetId] = $template;
							if (typeof onAfterFetch == 'function') {
								onAfterFetch($template.clone(true));
							}
						}
					},
					error:function(xhr, statusText, error){
						console.log('Fetching module template failed, error: ' + error);
						openAlertDialog({
							'title':vBulletin.phrase.get('error'),
							'message':vBulletin.phrase.get('error_retrieving_cloned_widget_template', xhr.status),
							'iconType':'error'
						});
					}
				}); // end ajax call
			}
			else
			{
				if (typeof onAfterFetch == 'function') {
					onAfterFetch(moduleTemplates[widgetId].clone(true));
				}
			}
		}

		function toggleModuleFlashContentVisibility(visibility, except){
			//show/hide youtube modules
			//we need to do this as flash WITHIN iframe (as what youtube embed does) "obscures" the module being dragged when it hovers over the flash object
			//this happens in all browsers and apparently this cannot be solved using the "iframe shim" technique
			$('.edit-mode .canvas-widget.youtube-widget .widget-content').css('visibility', visibility);
			if (except) {
				except.find('.widget-content').css('visibility', (visibility == 'hidden' ? 'visible':'hidden'));
			}
		}

		function attachDefaultWidgetEditButtonHandler(){
			//edit button handler for default widgets
			$('.canvas-widget.default-widget .edit-button').unbind('click').die('click').live('click', function(){
		  		$('body').css('cursor', 'wait');
		  		var $widgetContainer = $(this).closest('.canvas-widget');
		  		var widgetId = $widgetContainer.attr('widget-id');
		  		var $widgetNameContainer = $('> .widget-header .module-title', $widgetContainer);
		  		var widgetName = $('.hide-on-viewmode', $widgetNameContainer).length > 0 ? $('.hide-on-viewmode', $widgetNameContainer).text() : $widgetNameContainer.text();
		  		var widgetType = $widgetContainer.data('widget-type');

		  		$('#config-dialog .loader').show();
		  		$('#config-dialog .widget-name h1').html(widgetName);
		  		$('#config-dialog .dialog-content .widget-config-container').hide().empty().removeClass('error');
		  		$('#config-dialog').data('selected-module', $widgetContainer);
		  		toggleModuleFlashContentVisibility('hidden');
		  		$('#config-dialog').dialog('open');

		  		//get config items of the selected widget
		  		$.ajax({
		  			url:pageData.baseurl + '/index.php/ajax/api/widget/fetchConfigSchema',
		  			data:({
		  				widgetid: widgetId,
		  				widgetinstanceid: $widgetContainer.attr('widget-instance-id')||'', //if this widget instance has been configured before, its widget instance id exists, so use it
		  				pagetemplateid: $('#config_pagetemplateid').val() || $('#select-template input[type=radio]:checked').val() || '', //if New Page, no template is checked by default
		  				configtype: 'admin'
		  			}),
		  			type:'POST',
		  			dataType: 'json',
		  			complete:function(){
		  				$('body').css('cursor', 'auto');
		  			},
		  			success:function(result){
		  				console.log('fetchConfigSchema successful! result:' + JSON.stringify(result));
		  				if (result) {
		  					//set hidden fields
		  					$('#config_widgetid').val(result.widgetid);
		  					$('#config_widgetinstanceid').val(result.widgetinstanceid);
		  					$('#config_pagetemplateid, #save-page-form #pagetemplateid-yes, #save-page-form #pagetemplateid-new').val(result.pagetemplateid);

		  					//remember id of this widget instance for subsequent requests
		  					$widgetContainer.attr('widget-instance-id', result.widgetinstanceid);
							if (!result.configs || result.configs.length == 0) {
								$('.widget-config-container').html(vBulletin.phrase.get('no_configurations_found')).addClass('notice');
								$('#btnSaveConfig').prop('disabled', true);
								$('#btnCloseConfig').focus();
							}
							else {
			  					//loop through all the config items
			  					var idx = 0; //result.configs is an object literal and not an indexed array so we cannot use $.each index for math operations.
			  					var $widgetConfigContainer = $('#config-dialog .dialog-content .widget-config-container');

			  					//we need a way to know what type of default widget we are configuring to know how to display it right after saving
			  					$('<input type="hidden" name="data[widget_type]" />').addClass('widget-type').val(widgetType).appendTo($widgetConfigContainer);

								var hasdefaulttabconfig = false, hasdisplaytabsconfig = false, hastaborderconfig = false, tabs;
			  					$.each(result.configs, function(index, config){

			  						var $configValue;
			  						//convert config item to corresponding UI control
			  						switch(config.type){
										case 'ChannelSetup':
											// show channel setup and go to next iteration
											$('#config-dialog .dialog-content .channel-config-dialog').css('display', 'block');
											return true;
											break;
			  							//IE 7 and below need the 'type' and 'name' attributes already defined when creating form elements,
			  							//so might as well define all the attributes instead of using .attr()
			  							case 'Text':
			  								$configValue = $('<input type="text" name="data[{0}]" id="data[{0}]" />'.format(config.name))
				  												.addClass('textbox config-textbox')
				  												.val(config['defaultvalue'] || '');
			  								break;
			  							case 'LongText':
			  								$configValue = $('<textarea name="data[{0}]" id="data[{0}]" rows="3" />'.format(config.name))
				  												.addClass('textbox config-textbox')
				  												.val(config['defaultvalue'] || '');
			  								break;
			  							case 'YesNo':
			  								var $options = {
			  									'option_1' : $('<input type="radio" value="1" name="data[{0}]" id="data[{0}_1]" />'.format(config.name)),
		  										'label_1': $('<label />').attr({'for': config.name + '_1'}).text('Yes'),
			  									'option_0' : $('<input type="radio" value="0" name="data[{0}]" id="data[{0}_0]" />'.format(config.name)),
		  										'label_0': $('<label />').attr({'for': config.name + '_0'}).text('No')
			  								}

			  								var $defaultSelectedOption = $options['option_'+config['defaultvalue']];
			  								if ($defaultSelectedOption) {
			  									$defaultSelectedOption.prop('checked', true);
			  								}
			  								$configValue = $('<div />')
			  									.append(
			  										$options['option_1'], $options['label_1'],
			  										$options['option_0'], $options['label_0']
			  									);
			  								break;
			  							case 'Select':
			  								$configValue = $('<select name="data[{0}]" />'.format(config.name));
			  								var i;
											if(config.data != "")
											{
												for (i in config.data)
												{
													if (config['default'] == i)
													{
														$('<option />').attr('value', i).attr('selected', 'selected').text(config.data[i]).appendTo($configValue);
													}
													else
													{
														$('<option />').attr('value', i).text(config.data[i]).appendTo($configValue);
													}
												}
											}
			  								break;
			  						}

			  						//put * if field is required
			  						$requiredMark = $('<div />')
			  										.addClass('config-required-mark ' + pageData.textDirLeft)
			  										.append(function(){
			  											return (config.isRequired==1) ? '*':'&nbsp;'
			  										});

			  						//disable field if config is not editable
			  						if (config.isEditable==0) {
			  							if (config.type=='YesNo') {
			  								$configValue.find('input').prop('disabled', false);
			  							}
			  							else {
			  								$configValue.prop('disabled', false);
			  							}
			  						}

									//append the config row
			  						$widgetConfigContainer.append(
			  							$('<div></div>')
			  								.addClass(function(){
			  									return "clearfix config-row" + (((++idx) % 2 != 0) ? ' odd':'');
			  								})
			  								.append(
				  								$('<div></div>').addClass('config-label ' + pageData.textDirLeft).addClass(config.name).html(config.label),
				  								$requiredMark,
				  								$('<div></div>').addClass('config-value ' + pageData.textDirLeft).addClass(config.name).append($configValue)
			  								)
			  						);

									if (config.name == 'default_tab') {
										hasdefaulttabconfig = true;
									}
									if (config.name == 'display_tabs') {
										hasdisplaytabsconfig = true;
									}
									if (config.name == 'tab_order') {
										hastaborderconfig = true;
									}
								});


								var rebuildDefaultTabOptions = function() {
									tabs = loadTabs($widgetContainer);
									var defaulttab = $widgetContainer.attr('widget-default-tab'),
										defaulttabselect = $('select[name="data[default_tab]"]', $widgetConfigContainer),
										newoption;

									defaulttabselect.empty();

									for (var i in tabs) {
										if (hasdisplaytabsconfig) {
											if (!$('input:checkbox[value="' + tabs[i].selector + '"]', displaytabsconfigvaluecontainer).is(':checked')) continue;
										}
										else {
											if (!tabs[i].displayed) continue;
										}
										newoption = $('<option value="' + tabs[i].selector + '">' + tabs[i].label + '</option>');
										if (defaulttab == tabs[i].selector) {
											newoption.attr('selected', 'selected');
										}
										defaulttabselect.append(newoption);
									}
								}

								var rebuildTabOrderConfig = function() {
									tabs = loadTabs($widgetContainer);
									var configvaluecontainer = $('.config-value.tab_order', $widgetConfigContainer), newitem, newhidden;

									configvaluecontainer.empty().append('<ul>');

									for (var i in tabs) {
										if (hasdisplaytabsconfig) {
											if (!$('input:checkbox[value="' + tabs[i].selector + '"]', displaytabsconfigvaluecontainer).is(':checked')) continue;
										}
										else {
											if (!tabs[i].displayed) continue;
										}
										newitem = $('<li id="' + tabs[i].selector + '">' + tabs[i].label + '</li>');
										$('ul', configvaluecontainer).append(newitem);
										newhidden = $('<input name="data[tab_order][' + tabs[i].selector.substring(1) + ']" value="' + i + '" type="hidden">');
										configvaluecontainer.append(newhidden);
									}
									$('ul', configvaluecontainer).sortable({
										stop: function() {
											var result = $(this).sortable('toArray');
											configvaluecontainer.find('input:hidden').remove();
											for (i in result) {
												newhidden = $('<input name="data[tab_order][' + result[i].substring(1) + ']" value="' + i + '" type="hidden">');
												configvaluecontainer.append(newhidden);
											}
										}
									});
									$('ul', configvaluecontainer).disableSelection();
								}

								if (hasdisplaytabsconfig) {
									tabs = loadTabs($widgetContainer);
									var displaytabsconfigvaluecontainer = $('.config-value.display_tabs', $widgetConfigContainer), newcheckbox;

									for (var i in tabs) {
										newcheckbox = $('<label><input type="checkbox" name="data[display_tabs][]" value="' + tabs[i].selector + '">' + tabs[i].label + '</label>');
										if (tabs[i].displayed) {
											newcheckbox.find('input:checkbox').attr('checked', 'checked');
										}
										displaytabsconfigvaluecontainer.append(newcheckbox);
									}

									if (hasdefaulttabconfig) {
										$('input:checkbox', displaytabsconfigvaluecontainer).click(function() {
											// Rebuild default tab options if any checkboxes change
											rebuildDefaultTabOptions();
											rebuildTabOrderConfig();
										});
									}
								}
								if (hastaborderconfig) {
									rebuildTabOrderConfig();
								}
								if (hasdefaulttabconfig) {
									rebuildDefaultTabOptions();
								}

			  				}
			  			}
		  				$('#config-dialog .dialog-content .widget-config-container').show();
						$('#config-dialog .loader').hide();
		  			},
		  			error:function(xhr, statusText, error){
		  				console.log('fetchConfigSchema failed! error:' +  error);
		  				openAlertDialog({
							'title':vBulletin.phrase.get('error'),
							'message':vBulletin.phrase.get('error_retrieving_configuration', widgetName),
							'iconType':'error',
							'onAfterClose':function(){
			  					$('#config-dialog').dialog('close');
							}
						});
						$('#config-dialog .loader').hide();
		  			}
				});
		  		return false;
			});

			function loadTabs(widgetcontainer) {
				var tabs = [];
				$('ul.widget-tabs-nav li a, .widget-header ul.ui-tabs-nav li a, .widget-tabs-nav ul.ui-tabs-nav li a', widgetcontainer).each(function() {
					var self = $(this), displayed;
					if ($(this).closest('li').hasClass('hide'))
					{
						displayed = false;
					}
					else
					{
						displayed = true;
					}
					tabs.push({
						'selector': self.attr('href'),
						'label': self.text(),
						'displayed': displayed
					});
				});

				return tabs;
			}

		}

		function setCanvasStaticWidth(){
			$('.edit-mode .canvas-layout:visible > .canvas-widget-list')
				.width('')
				.each(function(){
					$(this).width($(this).width());
				});
		}

		function setCanvasStaticHeight(){
			//Only IE 8 needs this
			if ($.browser.msie && parseInt($.browser.version, 10) == 8) {
				var $canvasWidgetList = $('.edit-mode .canvas-layout:visible > .canvas-widget-list');
				$canvasWidgetList.each(function(){
					var $widgets = $('.canvas-widget', this), $self = $(this);
					var bottomOffset = $widgets.outerHeight(true) || 50;
					var contentHeight = $widgets.length * $widgets.outerHeight(true);
					var offset = $self.height() - contentHeight;console.log('offset:', offset);
					if (offset >= 0 && offset < bottomOffset){
						var $window = $(window);
						var top = $window.scrollTop();
						$self.height($self.height() + (bottomOffset - offset));
						$window.scrollTop(top);
						return false;
					}
					else if ((offset > bottomOffset && $self.height() > parseInt($self.css('min-height'), 10)) || offset < 0) {
						var $window = $(window);
						var top = $window.scrollTop();
						$self.height(contentHeight + bottomOffset);
						$window.scrollTop(top);
						return false;
					}
				});
			}
		}

		function initializeForumEditor()
		{
			window.console.log('Fetching page manager forums');
			vBulletin.AJAX({
				url:pageData.baseurl + '/index.php/ajax/api/widget/fetchPageManagerForums',
				data:{},
				complete:function(){
					$('#config-dialog .loader').hide();
					$('body').css('cursor', 'auto');
				},
				success:function(result){
					forumsLoaded = true;
					$.each(result, function(indexSub, sub){
						var $channel = addMainForum(sub.nodeid, sub.parentid, sub.title, sub.category, false);
						addSubForums(sub.subchannels, $channel);
					});

					$('.main-channel-container > .channel-item-container > .channel-item .grip-icon').live('mousedown', function(){
						$(this).closest('.main-channel-container').height($(this).closest('.main-channel-container').height());
					});
					$('.sub-channel-container > .channel-item-container > .channel-item .grip-icon').live('mousedown', function(){
						$(this).closest('.sub-channel-container').height($(this).closest('.sub-channel-container').height());
					});
					hasConfigChanged = false;

					// channel setup is included in the widget, initialize it
//						if ($('.config-dialog-container .channel-config-dialog').length > 0)
//						{
						//make channel-list draggable-n-droppable
						makeSortableChannels();
//						}

				},
				error_phrase:'error_fetching_channels'
			});

			//add main channel button event handlers
			$('.channel-config-dialog .add-channel-fieldset .add-button, .channel-config-dialog .add-channel-fieldset input').live('click keydown', function(event)
			{
				if (((event.type == 'click' || event.which != 13) && this.type == 'text') || (event.type == 'keydown' && this.type == 'button' && event.which != 13))
				{
					return true;
				}
				var $channelTitleField = (this.type == 'text') ? $(this):$(this).prev();
				var channelTitle = $.trim($channelTitleField.val());
				if (channelTitle && channelTitle != $channelTitleField.prop('defaultValue'))
				{
					//var topLevel = $(this).parents('.channel-config-dialog').data('top-level');
					addMainForum('', '', channelTitle, 0, true);

					//reset channel title field
					$channelTitleField.val('');

					if (this.type == 'button') $channelTitleField.focus();
				}
				else
				{
					openAlertDialog({
						'title':vBulletin.phrase.get('warning_gcpuser'),
						'message':vBulletin.phrase.get('please_enter_channel_title'),
						'iconType':'warning',
						'onAfterClose':function(){
							$channelTitleField.focus();
						}
					});
				}

			});

			//channel title click handler
			$('.channel-config-dialog .main-channel-container .channel-item .channel-title div').live('click', function(){
				$(this).hide();
				var $channelTitle = $(this).next();
				$channelTitle.show();
				$channelTitle.select();
				$channelTitle.focus();
			});

			//channel title textbox event handlers
			$('.channel-config-dialog .main-channel-container .channel-item .channel-title input').live('keydown blur', function(event){
				if (event.type == 'focusout' || (event.type == 'keydown' && event.which == 13)){
					if (!$.trim(this.value) && event.type == 'focusout'){
						this.value = this.defaultValue;
					}
					if ($.trim(this.value)) {
						$(this).hide();
						$(this).prev().html(this.value);
						$(this).prev().show();
					}
				}
			});

			// make category button click
			$('.channel-config-dialog .channel-item .category-to-channel a').live('click', function(){
				var $channelItem = $(this).closest('.channel-item');

				$channelItem.attr('data-switch-category', 0);

				$(this).parent()
					.removeClass('category-to-channel')
					.addClass('channel-to-category')
				$(this).html(vBulletin.phrase.get('make_category'));

				return false;
			});
			$('.channel-config-dialog .channel-item .channel-to-category a').live('click', function(){
				var $channelItem = $(this).closest('.channel-item');

				$channelItem.attr('data-switch-category', 1);

				$(this).parent()
					.removeClass('channel-to-category')
					.addClass('category-to-channel');
				$(this).html(vBulletin.phrase.get('make_forum'));

				return false;
			});

			//add subchannel button click
			$('.channel-config-dialog .channel-item .add-subchannel-button a').live('click', function(){
				var $addedChannel = addSubForum('', '', 'New Channel', 0, $(this).closest('.channel-item-container'));
				$('.channel-title div', $addedChannel).click();
				$('.channel-title input', $addedChannel).get(0).scrollIntoView(false);
				return false;

			});

			//channel widget close button click
			$('.channel-config-dialog .channel-list .channel-item .close-button').live('click', function(){
				var $this = $(this);
				var hasSubChannels = $('> .sub-channel-container > .channel-item-container', $this.closest('.channel-item-container')).length > 0;
				openConfirmDialog({
					'title': vBulletin.phrase.get('remove_forum_q'),
					'message': vBulletin.phrase.get('do_you_want_to_remove_forum',
							$(this).prev().text(),
							(hasSubChannels) ? ' ' + vBulletin.phrase.get('subchannels_will_be_deleted') : ''),
					'iconType':'warning',
					'onClickYes':function(){
						var $channelItemContainer = $this.closest('.channel-item-container');
						var $channelContainer = $channelItemContainer.parent();
						var $nodeId = $this.closest('.channel-item').attr('data-channel-id');
						$('body').css('cursor', 'wait');

						$.ajax({
							url:pageData.baseurl + '/index.php/ajax/api/content_channel/delete',
							data: {nodeid:$nodeId},
							type:'POST',
							dataType: 'json',
							complete:function(){
								$('body').css('cursor', 'auto');
							},
							success:function(result){
								console.log('Delete channel successful! result:' + JSON.stringify(result));
								//check results
								if (result){
									//delete channel/subchannel item container which also includes all its subchannels, if any
									$channelItemContainer.remove();

									//if we are deleting the main channel, we should remove the whole thing
									if ($channelContainer.hasClass('main-channel-container')){
										$channelContainer.slideUp('fast', function(){
											$(this).remove();
										});
									}
								}
								else {
									openAlertDialog({
										'title':vBulletin.phrase.get('error'),
										'message':vBulletin.phrase.get(result.errors[0][0]),
										'iconType':'error'
									});
								}
							},
							error:function(xhr, statusText, error){
								console.log('Delete channel failed! result:' + error);
								openAlertDialog({
									'title':vBulletin.phrase.get('error'),
									'message':vBulletin.phrase.get('error_deleting_page', xhr.status),
									'iconType':'error'
								});
							}
						});
					}
				});
			});
		}

		function initializeBlogsGroupsList(channel)
		{
			function loadChannels(channel, page, initPagination)
			{
				vBulletin.AJAX({
					url:pageData.baseurl + ('/ajax/render/sb_{0}_list').format(channel),
					data:{page:page},
					complete:function(){
						$('#config-dialog .loader').hide();
						$('body').css('cursor', 'auto');
					},
					success:function(result){
						$(('#top-level-{0} .channel-config-dialog').format(channel)).html(result);
						if (initPagination)
						{
							vBulletin.pagination({
								'context': ('#top-level-{0} .channel-config-dialog').format(channel),
								'onPageChanged' : function(pageNumber, bypassFilter){
									loadChannels(channel, pageNumber);
								}
							});
						}
					},
					error_phrase:'error_fetching_channels'
				});

			}

			loadChannels(channel, 1, true);
			//channel title click handler
			$('.page_manager_table .channel_name div').live('click', function(){
				$(this).hide();
				var $channelTitle = $(this).next();
				$channelTitle.show();
				$channelTitle.select();
				$channelTitle.focus();
			});

			//channel title textbox event handlers
			$('.page_manager_table .channel_name input').live('keydown blur', function(event){
				if (event.type == 'focusout' || (event.type == 'keydown' && event.which == 13)){
					if (!$.trim(this.value) && event.type == 'focusout'){
						this.value = this.defaultValue;
					}
					var new_title = $.trim(this.value);
					var that = $(this);
					if (new_title && that.prev().html() != new_title) {
						$('body').css('cursor', 'wait');

						vBulletin.AJAX({
							url:pageData.baseurl + '/index.php/ajax/api/Content_Channel/update',
							data:{
									nodeid:that.parents('.channel_row').data('nodeid'),
									data:{title:new_title}
								},
							complete:function(){
								$('#config-dialog .loader').hide();
								$('body').css('cursor', 'auto');
							},
							success:function(result){
								that.hide();
								that.prev().html(new_title);
								that.prev().show();
							},
							error_phrase:'error_saving_page'
						});
					}
				}
			});
			//blog/group delete button click
			$('.page_manager_table .delete').live('click', function(){
				var $this = $(this);
				openConfirmDialog({
					'title': vBulletin.phrase.get('remove_channel_q'),
					'message': vBulletin.phrase.get('do_you_want_to_remove_channel', $this.parents('.channel_row').find('.channel_name_val').text()),
					'iconType':'warning',
					'onClickYes':function(){
						$('body').css('cursor', 'wait');
						vBulletin.AJAX({
							url:pageData.baseurl + '/index.php/ajax/api/content_channel/delete',
							data: {nodeid:$this.parents('.channel_row').data('nodeid')},
							complete:function(){
								$('body').css('cursor', 'auto');
							},
							success:function(result){
								$this.parents('.channel_row').remove();
							}
						});
					}
				});
			});
		}

		var forumsLoaded = false;
		//var groupsLoaded = false;

		function initializePageManager(){
			// Channel config dialog
			//$('#config-dialog .loader').show();
			$('body').css('cursor', 'wait');
			//initialize tabs
			$pageManagerTabs = $('#manage-page .tabs').tabs({
				show:function(event, ui){
					if (ui.index == 0 && !forumsLoaded)
					{
						initializeForumEditor();
					}

					if (ui.index != 0 && hasConfigChanged)
					{
						openConfirmDialog({
							'title': vBulletin.phrase.get('exit_without_saving_page'),
							'message': vBulletin.phrase.get('forum_changes_will_be_lost'),
							'iconType':'warning',
							'onClickYes':function(){
								//hasCanvasChanged = false;
								hasConfigChanged = false;
								//templateChanged = true;
								//$templateThumbnails.thumbnailRadioCheckbox('check', $radio, true);
							}
						});
						return false;

					}
					//resize Modules/Layouts/Templates list
					//resizeListWidth(ui.index);

					//resize tab content width
					//resizePageEditorTabContentWidth();
				},
				select:function(event, ui){
				}
			});

			$pageManagerTabs.tabs('select', 0);

			$managePagesTabs = $('#manage-pages').tabs({
				show:function(event, ui){
					if ((ui.index == 1 || ui.index == 2))// && !groupsLoaded
					{
						initializeBlogsGroupsList($(ui.tab).data('top-level'));
					}
				}
			});

			$managePagesTabs.tabs('select', 0);

			// save the channels/forums
			$('#manage-page-dropdown .lnkSaveChanges').click(function()
			{
				console.log('Saving forum/channel data');

				vBulletin.loadingIndicator.show();
				$('body').css('cursor', 'wait');

				var forumData = [];

				function populateSubChannelData($subChannelContainer, channelObj, parentChannelId)
				{
					var $subChannelItemContainers = $('> .channel-item-container', $subChannelContainer);

					if ($subChannelItemContainers.length > 0)
					{
						$subChannelItemContainers.each(function(index)
						{
							var $subChannelItem = $('> .channel-item', this);
							var subChannelId = $subChannelItem.attr('data-channel-id');
							var subChannelPreviousParentId = $subChannelItem.attr('data-parent-id');

							//add sub channel data
							subchannelObj = {
								nodeid: subChannelId || '0',
								previousParentId: subChannelPreviousParentId,
								title: $('.channel-title div', $subChannelItem).text(),
								displayorder: index + 1, // index starts with 0, displayorder must start with 1, as 0 displayorder hides a forum
								parentid: parentChannelId || '0',
								subchannels : []
							};

							if ($subChannelItem.attr('data-switch-category') != null)
							{
								subchannelObj['switchCategory'] = $subChannelItem.attr('data-switch-category');
							}

							channelObj.subchannels.push(subchannelObj);

							populateSubChannelData($subChannelItem.next('.sub-channel-container'), channelObj.subchannels[index], subChannelId);
						});
					}
				}

				if (channelsChanged.forum)
				{
					// populate 'channels' property
					$('.channel-config-dialog .channel-list .main-channel-container').each(function(index)
					{
						var $channel = $('> .channel-item-container > .channel-item', this);
						var mainChannelId = $channel.attr('data-channel-id');
						var mainChannelPreviousParentId = $channel.attr('data-parent-id');

						var channelObj = {
							nodeid: mainChannelId,
							previousParentId: mainChannelPreviousParentId,
							title: $('.channel-title div', $channel).text(),
							displayorder: index + 1, // index starts with 0, displayorder must start with 1, as 0 displayorder hides a forum
							subchannels : []
						}

						if ($channel.attr('data-switch-category') != null)
						{
							channelObj['switchCategory'] = $channel.attr('data-switch-category');
						}

						//populate 'subchannels' property recursively
						populateSubChannelData($channel.next('.sub-channel-container'), channelObj, mainChannelId);

						//add main channel data
						forumData.push(channelObj);
					});

					//submit the channel data
					vBulletin.AJAX({
						url:pageData.baseurl + '/index.php/ajax/api/widget/saveForums',
						data: {data: JSON.stringify(forumData)},
						complete:function(){
							$('body').css('cursor', 'auto');
							vBulletin.loadingIndicator.hide();
						},
						success:function(result)
						{
							console.log('Forum/channel changes successfully saved');

							//check results
							if (result && result.forums && result.forums.length > 0)
							{
								//empty the channel list
								//$('.channel-config-dialog .channel-list').empty();

								hasConfigChanged = false;
								channelsChanged.forum = false;
								//saveDefaultConfig($form);

								location.reload();
							}
							else
							{
								openAlertDialog({
									'title':vBulletin.phrase.get('error'),
									'message':vBulletin.phrase.get('error_saving_forums'),
									'iconType':'error'
								});
								return false;
							}
						},
						error_phrase:'error_saving_channels_code'
					});
				}
				else
				{
					console.log('No forum/channel changes to save');
					vBulletin.loadingIndicator.hide();
					$('body').css('cursor', 'auto');
				}
			});
			$('#manage-page-dropdown .lnkExitWithoutSaving').live('click', function(){
			//$mainChannelSortable.sortable('destroy');
			//$subChannelSortable.sortable('destroy');
				if (hasConfigChanged) {
					openConfirmDialog({
						'title': vBulletin.phrase.get('exit_without_saving_page'),
						'message': vBulletin.phrase.get('do_you_want_to_exit_without_saving_page'),
						'iconType':'warning',
						'onClickYes':function(){
							location.reload();
						}
					});
				}
				else {
					location.reload();
				}
			});
		}

		function initializePageEditor(){
			//disable all content links and fields
			$('.edit-mode .widget-content a, .edit-mode #channel-tabbar a, .edit-mode #btnSearch, .edit-mode #q').live('focus click', function(e){
				this.blur();
				return false;
			});

			//load modules and templates only once
			if (!modulesLoaded){
				loadModules();
			}
			if (!templatesLoaded){
				loadTemplates();
			}
			//templates have already been loaded; this occurs if Edit Page dropdown has been opened previously
			//now just unselect/select a template accordingly
			else {
				//unselect previously selected page template
				$templateThumbnails.thumbnailRadioCheckbox('check', $('#select-template .template-border.selected').next('input') , false);

				if (!newPage) { //Edit Page; select associated page template
					$('#select-template .template-item input[value={0}]'.format($('#pagetemplateid-yes').val()))
						.prev()
						.trigger('click');
				}
			}

			//initialize Tiny Scrollbar for layout list
			customScrollbars[1] = $('#change-layout .layout-list-container');
			customScrollbars[1].tinyscrollbar({
				sizethumb: 14,
				axis:'x',
				update:function(){
					if ($('#change-layout .layout-list-container').innerHeight() < $('#change-layout .panel-header-text').height()) {
						$('#change-layout .panel-header-text').height($('#change-layout .layout-list-container').innerHeight());
					}
				}
			});
//			//initialize Tiny Scrollbar for color style
//			customScrollbars[3] = $('#change-layout .layout-list-container');
//			customScrollbars[3].tinyscrollbar({
//				sizethumb: 14,
//				axis:'x',
//				update:function(){
//					if ($('#change-layout .layout-list-container').innerHeight() < $('#change-layout .panel-header-text').height()) {
//						$('#change-layout .panel-header-text').height($('#change-layout .layout-list-container').innerHeight());
//					}
//				}
//			});

			//reset pagetemplateid in the module config form
			$('#config_pagetemplateid').val('');

			if (newPage){
				$('#save-page-form #pagetitle').val('');
				$('#save-page-form #pageurl').val('');
				$('#save-page-form #pagetemplateid').val('0');
				$('#save-page-form #pageid').val('0');
			}

			$('#edit-page-dropdown .lnkSaveChanges').click(function(){
				$('#edit-page-dropdown .tabs li').removeClass('ui-tabs-selected ui-state-active'); //deselect all tabs
				$('#edit-page-dropdown .tabs .tab').addClass('ui-tabs-hide'); //hide panels
				$('#save-content').show(); //show save form

				// these are set to display none in some cases below; show them again
				$('#save-page-form .edit-page-template').css('display', '');
				$('#save-page-form .edit-page-template').prev('label').css('display', '');

				//if New Page without a template, enable template title field and disable options to overwrite template
				if ($('body').hasClass('lnkNewPage')) {
					$('#save-page-form .new-page-template input').prop('disabled', false);
					$('#save-page-form .edit-page-template input').prop('disabled', true);

				}
				else {
					// If neither Overwrite Template Yes or No is checked, we check Yes by default
					if (!$('#pagetemplateid-yes').prop('checked') && !$('#pagetemplateid-no').prop('checked')) {
						$('#pagetemplateid-yes').prop('checked', true);
					}

					//if Edit Page or New Page with a template, enable fields for overwriting template and disable template title field for new template
					$('#save-page-form .edit-page-template input').prop('disabled', false);
					$('#save-page-form .new-page-template input').prop('disabled', true);

					//if New Page with a template, but the template has not been changed, bypass template overwrite confirmation
					if (newPage && (!hasCanvasChanged && !hasConfigChanged))
					{
						$('#save-page-form .edit-page-template').css('display', 'none');
						$('#save-page-form .edit-page-template').prev('label').css('display', 'none');
					}

					if ($('#pagetemplateid-yes').prop('checked')) { //overwrite template
						$('#save-page-form #templatetitle').prop('disabled', false);
						$('#save-page-form #templatetitle-edit').prop('disabled', true);
					}
					else { //do not overwrite template
						$('#save-page-form #templatetitle').prop('disabled', true);
						$('#save-page-form #templatetitle-edit').prop('disabled', false);
					}
				}

			});

			$('#edit-page-dropdown .lnkExitWithoutSaving').click(function(){
				if (hasCanvasChanged || hasConfigChanged || templateChanged ||
						(!newPage &&
							($('#pagetitle').val() != $('#pagetitle').prop('defaultValue')
							|| $('#pageurl').val() != $('#pageurl').prop('defaultValue')))
						|| (newPage && ($('#pagetitle').val() != '' || $('#pageurl').val() !=''))) {
					openConfirmDialog({
						'title': vBulletin.phrase.get('exit_without_saving_page'),
						'message': vBulletin.phrase.get('do_you_want_to_exit_without_saving_page'),
						'iconType':'warning',
						'onClickYes':function(){
							location.reload();
						}
					});
				}
				else {
					location.reload();
				}
			});

			var resizeTimer = 0;
			$(window).bind('resize.canvas', function(){
				clearTimeout(resizeTimer);
				resizeTimer = setTimeout(setCanvasStaticWidth, 200);
			});

			var getHideContainedWidgetControl = function(checked) {
				return '<label class="hide-icon module-button-item"><input type="checkbox" title="{0}" data-toggle-title="{1}"{2} /></label>'.format(
					vBulletin.phrase.get('check_to_hide_module'),
					vBulletin.phrase.get('uncheck_to_unhide_module'),
					checked ? ' checked="checked"' : ''
				);
			}

			//add Hide module checkboxes for existing contained widgets
			$('.canvas-widget.container-widget .canvas-widget:not(.dummy-widget)').each(function() {
				var checked = $(this).hasClass('hidden-widget');
				$('.module-buttons .admin-only', this).prepend(getHideContainedWidgetControl(checked));

				if (checked) {
					//doing .trigger('click') unchecks the checkbox, so we have to check it again
					$('.module-buttons .admin-only .hide-icon input', this).trigger('click').prop('checked', true);
				}
			});

			var checkNestedContainerWidgets = function(event, sortableUI, fromModuleTab) {
				var $widget = sortableUI.item,
					fromModuleTab = sortableUI.item.hasClass('module-item');

				//cancel move if container widget is being moved to another container widget
				var $innerContainerWidget = $('> .canvas-widget.container-widget {0}'.format(
					fromModuleTab ? '.module-item' : '.canvas-widget.container-widget'
				), this);
				if ($innerContainerWidget.length > 0) {
					var $outerContainerWidget = $innerContainerWidget.closest('.canvas-widget.container-widget');
					if ($outerContainerWidget.attr('widget-id') == $innerContainerWidget.attr('widget-id')) { //if widget id's of outer and its inner widgets are the same, then they are nested
						if (fromModuleTab) {
							$innerContainerWidget.remove();
						}
						else if (sortableUI.sender) {
							sortableUI.sender.sortable('cancel');
						}
						else {
							$(this).sortable('cancel');
						}

						cancelWidgetMove = true;
						openAlertDialog({
							'title':vBulletin.phrase.get('move_not_allowed'),
							'message':vBulletin.phrase.get('dropping_container_module_into_container_module_not_allowed'),
							'iconType':'warning'
						});
						return true;
					}
					return false;
				}
				return false;
			}

			//adds Hide Module checkbox if the widget is inside a Container widget and removes it if not
			var toggleHideWidgetButton = function($widget) {
				if ($widget.parents('.canvas-widget.container-widget').length > 0) {
					if ($('.module-buttons .admin-only .hide-icon', $widget).length == 0) {
						$('.module-buttons .admin-only', $widget).prepend(getHideContainedWidgetControl());
					}
				}
				else {
					$widget.removeClass('hidden-widget').find('> .widget-header .module-buttons .admin-only .hide-icon').remove();
				}
			}

			//make page canvas widget items draggable-n-droppable
			var cancelWidgetMove = false;
			$('.edit-mode .canvas-layout .canvas-widget-list').sortable({
				revert:true,
				tolerance:'pointer',
				/*snap:'.edit-mode .canvas-layout:visible .canvas-widget-list',
				snapMode:'inner',
				snapTolerance:5,*/
				connectWith: ".edit-mode .canvas-layout:visible .canvas-widget-list",
				placeholder: "canvas-widget canvas-widget-highlight drag-highlight clear",
				create:function(){
					setCanvasStaticWidth();
					setCanvasStaticHeight();
				},
				update: function(event, ui){
					//console.log('sortable update', $(this), ui.item, ui.sender);
					var sortable = this;
					if (moduleOverCanvas){ //means the item was dragged from the Module list
						if (!cancelWidgetMove) {
							// replace module list item with module template
							fetchModuleTemplate(ui.item, function($moduleTemplate){
								ui.item.replaceWith($moduleTemplate);

								//Collapse the added widget by default for easier drag and drop
								//except Container widget which needs to be expanded by default because it is also a drag and drop zone
								$moduleTemplate.filter(':not(.container-widget)').find('.toggle-button').trigger('click', [true]);

								//check for nested container widgets
								if (!checkNestedContainerWidgets.apply(sortable, [event, ui])) {

									toggleHideWidgetButton($moduleTemplate);

									//initialize tabs (if any) when module is dropped from the Module list to the canvas
									$moduleTemplate.addClass('shadow').find('.widget-tabs').andSelf().filter('.widget-tabs').tabs();
									onModuleAddOrRemove();

									//remove dummy widget inside container widget if we are in a container widget
									$moduleTemplate.parents('.canvas-widget.container-widget').find('.canvas-widget.dummy-widget').remove();

									//when widget is dropped from Add Modules tab into a widget container,
									//for some reason jquery sortable leaves extra module item and placeholder
									//and doesn't remove both, so...
									var $widgetContainer = $moduleTemplate.parents('.canvas-widget.container-widget');
									if ($widgetContainer.length == 1) {
										$widgetContainer.find('.canvas-widget-highlight').remove();
										$widgetContainer.find('.module-item').remove();
									}
								}
							});
						}
					}
					else {
						//when moving widgets from another canvas-widget-list, 'receive' callback is triggered
						//but not when moving widgets from the same canvas-widget-list,
						//so we'll just check for nested container widgets here in the 'update' callback
						if (!checkNestedContainerWidgets.apply(sortable, [event, ui])) {
							toggleHideWidgetButton(ui.item);
							onModuleAddOrRemove();
						}
					}

					hasCanvasChanged = true;
				},
				out:function(event, ui){
					//console.log('out');
				},
				sort:function(event, ui){
					//console.log('sortable sort');
					if (moduleDragStart){
						moduleOverCanvas = true;
					}
					var $widgetContainer = ui.placeholder.closest('.canvas-widget.container-widget');
					if ($widgetContainer.length == 1 && $widgetContainer.find('.canvas-widget:last-child').hasClass('canvas-widget-highlight')) {
						ui.placeholder.css({'margin-bottom': 0, 'margin-top':-3});
					}
					else {
						ui.placeholder.css({'margin-bottom': '', 'margin-top':''});
					}
				},
				start:function(event, ui){
					//console.log('start:', ui.placeholder);
					toggleModuleFlashContentVisibility('hidden', ui.item);
				},
				over:function(event, ui){
					//console.log('sortable over');
					/*$.each(ui.placeholder.parent().prop('className').split(' '), function(index, className){console.debug(className);
						if (className.indexOf('section-') == 0){console.debug('found!');
							ui.item.addClass(className);
							return false;
						}
					});	*/
				},
				stop:function(event, ui){
					//console.log('sortable stop', $(this), ui.item, ui.sender);
					cancelWidgetMove = false;
					setCanvasStaticHeight();
					moduleOverCanvas = false;
					ui.item.height('auto');
					toggleModuleFlashContentVisibility('visible');
					//ui.item.get(0).className = ui.item.get(0).className.replace(/\bsection-\d?\b/g, '');

					//make 'container widget'-related adjustments
					$('.canvas-layout .canvas-widget-list .canvas-widget-highlight').remove();
					var $containerWidgets = $('.canvas-layout > .canvas-layout-row .canvas-widget-list > .canvas-widget.container-widget');
					$('.canvas-layout > .canvas-layout-row .canvas-widget-list > .canvas-widget.container-widget').each(function() {
						var $canvasWidgetList = $('.canvas-widget-list', this);
						if ($canvasWidgetList.children().length == 0) { //container widget is empty, so add dummy widget back
							$canvasWidgetList.append('<div class="canvas-widget dummy-widget"><span>{0}</span></div>'.format(vBulletin.phrase.get('you_can_also_drag_and_drop_modules_here')));
						}
						else if ($canvasWidgetList.find('.canvas-widget.dummy-widget').length > 0 && $canvasWidgetList.find('.canvas-widget:not(.dummy-widget,.canvas-widget-highlight)').length > 0){ //container widget is not empty, so remove dummy widget
							$canvasWidgetList.find('.canvas-widget.dummy-widget').remove();
						}
					});
				},
				receive:function(event, ui) {
					//console.log('sortable receive', $(this), ui.item, ui.sender);
					if (ui.item.hasClass('module-item')) {
						checkNestedContainerWidgets.apply(this, [event, ui, true]);
					}
				},
				handle:'.move-icon',
				items:'.canvas-widget'
			})
			.find('.canvas-widget .widget-header').disableSelection();

			//module Remove button click
			$('.edit-mode .canvas-widget .close-button').live('click', function(){
				var $this = $(this);
				openConfirmDialog({
					'title': vBulletin.phrase.get('remove_module_q'),
					'message': vBulletin.phrase.get('do_you_want_to_remove_module', $this.closest('.widget-header').find('.module-title').text()),
					'iconType': 'warning',
					'onClickYes':function(){
						var $canvasWidget = $this.closest('.canvas-widget'),
							$containerWidget = $canvasWidget.parents('.canvas-widget.container-widget');

						$canvasWidget.remove();
						setCanvasStaticHeight();
						onModuleAddOrRemove();
						hasCanvasChanged = true;

						if ($containerWidget.find('.canvas-widget').length == 0) { //no widgets inside the Container widget, so put the dummy widget back
							$containerWidget.find('.canvas-widget-list').append('<div class="canvas-widget dummy-widget"><span>{0}</span></div>'.format(vBulletin.phrase.get('you_can_also_drag_and_drop_modules_here')));
						}
					}
				});
			});

			//search widget Edit button click
			$('.edit-mode .search-widget .edit-button').live('click', function(){
				$('#search-config-dialog').data('search-widget', $(this).closest('.search-widget')); //remember corresponding search widget
				toggleModuleFlashContentVisibility('hidden');
				$('#search-config-dialog').dialog('open');
				return false;
			});

// End of Channel config dialog

			//Save page onsubmit handler
			$('#save-page-form #btnOK').live('click', function(e, bypassValidation){
				var dialogTitle = $('#edit-page-dropdown .lnkSaveChanges .label').text();
				if (!bypassValidation) {
					//validate inputs
					if (!$.trim($('#save-page-form #pagetitle').val())){
						openAlertDialog({
							'title':dialogTitle,
							'message':vBulletin.phrase.get('please_enter_page_name'),
							'iconType':'warning',
							'onAfterClose':function(){
								$('#save-page-form #pagetitle').focus();
							}
						});
						return false;
					}
					if ($('body').hasClass('lnkEditPage')) { //validate template fields for Edit Page or New Page that has selected template

						var $templateOptionYes = $('#save-page-form #pagetemplateid-yes');
						var $templateOptionNo = $('#save-page-form #pagetemplateid-no');
						if (!$templateOptionYes.prop('checked') && !$templateOptionNo.prop('checked')) {
							openAlertDialog({
								'title':dialogTitle,
								'message':vBulletin.phrase.get('please_choose_overwrite_template_options'),
								'iconType':'warning',
								'onAfterClose':function(){
									$('#save-page-form #pagetemplateid-yes').focus();
								}
							});
							return false;
						}
						else if ($templateOptionNo.prop('checked')) { //No  (do not overwrite template - new template)
							var $templateTitleField = $('#save-page-form #templatetitle-edit');
							var templateTitle = $.trim($templateTitleField.val());
							if (!templateTitle || templateTitle == $templateTitleField.prop('defaultValue')){
								openAlertDialog({
									'title':dialogTitle,
									'message':vBulletin.phrase.get('please_enter_new_template_name'),
									'iconType':'warning',
									'onAfterClose':function(){
										$('#save-page-form #templatetitle-edit').focus();
									}
								});
								return false;
							}
							openConfirmDialog({
								'title':dialogTitle,
								'message':vBulletin.phrase.get('applying_new_template', $('#save-page-form #templatetitle-edit').val()),
								'buttonLabel': {yesLabel:vBulletin.phrase.get('save_page'), noLabel:vBulletin.phrase.get('cancel')},
								'iconType':'warning',
								'onClickYes':function(){
									$('#save-page-form #btnOK').trigger('click', true); //submit the form again bypassing validation
								}
							});
							return false;
						}
						else if ($templateOptionYes.prop('checked')) { //Yes (overwrite template)

							//if New Page with a template, but the template has not been changed, bypass template overwrite confirmation
							if (newPage && (!hasCanvasChanged && !hasConfigChanged))
							{
								$('#save-page-form #btnOK').trigger('click', true); //submit the form again bypassing validation
							}
							else
							{
								openConfirmDialog({
									'title':dialogTitle,
									'message':vBulletin.phrase.get('overwrite_template_continue'),
									'buttonLabel': {yesLabel:vBulletin.phrase.get('save_page'), noLabel:vBulletin.phrase.get('cancel')},
									'iconType':'warning',
									'onClickYes':function(){
										$('#save-page-form #btnOK').trigger('click', true); //submit the form again bypassing validation
									}
								});
							}
							return false;
						}
					}
					else { //validate template fields for New Page that has no selected template
						var $templateTitleField = $('#save-page-form #templatetitle-new');
						var templateTitle = $.trim($templateTitleField.val());
						if (!templateTitle || templateTitle == $templateTitleField.prop('defaultValue')){
							openAlertDialog({
								'title':dialogTitle,
								'message':vBulletin.phrase.get('please_enter_new_template_name'),
								'iconType':'warning',
								'onAfterClose':function(){
									$('#save-page-form #templatetitle-new').focus();
								}
							});
							return false;
						}
					}
				}

				var $currentLayout = $('.canvas-layout:visible');
				currentLayout = $currentLayout.attr('id');
				//console.log('currentLayout: ' + currentLayout);

				//update screenlayoutid with selected layout
				$('#save-page-form #screenlayoutid').val($currentLayout.attr('layout-id'));
				//console.log('layout id: ' + $currentLayout.attr('layout-id'));
				//console.log('section count: ' + sectionCount[currentLayout]);

				function prepareModuleInstance($module) {
					var moduleInfo = {
						widgetId: $module.attr('widget-id'),
						widgetInstanceId: ($module.attr('widget-instance-id')||'0')
					};
					if ($module.hasClass('container-widget'))
					{
						var arr = [];
						var displaySubModules = [];
						$('div.canvas-widget-list > div.canvas-widget', $module).each(function(index){
							if (!$(this).hasClass('hidden-widget'))
							{
								displaySubModules.push($(this).attr('widget-instance-id'));
							}
							arr.push(prepareModuleInstance($(this)));
						});
						moduleInfo['subModules'] = arr;
						moduleInfo['displaySubModules'] = displaySubModules;
					}

					return moduleInfo;
				}

				//prepare module instances data
				$('input[type=hidden][name*="displaysections"]', $currentLayout).clone().appendTo($('#moduleData').empty());
				for (var i=0; i<sectionCount[currentLayout]; i++) {
					var arr = [];
					$(' > .canvas-layout-row > div.section-' + i + ' > div.canvas-widget', $currentLayout).each(function(index){
						arr.push(prepareModuleInstance($(this)));
					});

					//populate the corresponding displaysections[] hidden textbox with the added widgets
					$('#save-page-form input[name="displaysections[' + i + ']"]').val(JSON.stringify(arr));
				}

				// fetch form data
				var $formData = {};
				var $serializedForm = $('#save-page-form').serializeArray();
				$.each($serializedForm, function(index, el){
					$formData[el.name] = el.value;
				});

				// we can now send the data
				$.ajax({
					url:pageData.baseurl + '/index.php/ajax/api/page/pageSave',
					data: {input:$formData},
					type:'POST',
					dataType: 'json',
					complete:function(){
						$('body').css('cursor', 'auto');
					},
					success:function(result){
						console.log('savePage successful! result:' + JSON.stringify(result));
						//check results
						if (result && result.url != null){
							window.location.href = pageData.baseurl + result.url;
						}
						else {
							openAlertDialog({
								'title':vBulletin.phrase.get('error'),
								'message':vBulletin.phrase.get(result.errors[0][0]),
								'iconType':'error'
							});
						}
					},
					error:function(xhr, statusText, error){
						console.log('saveChannelWidgetConfig failed! result:' + error);
						openAlertDialog({
							'title':vBulletin.phrase.get('error'),
							'message':vBulletin.phrase.get('error_saving_page', xhr.status),
							'iconType':'error'
						});
					}
				});
				});

			//initialize widget config dialog
			$('#config-dialog').dialog({
				title:'Module Configuration',
				autoOpen:false,
				modal:true,
				resizable:false,
				closeOnEscape:false,
				showCloseButton:false,
				height:500,
				width:800,
				dialogClass:'dialog-container config-dialog-container input-dialog',
				open:function(){
					$('#config-dialog .loader').show();
					$('body').css('cursor', 'wait');
						},
				create:function(){


					//submit form handler to save config
					$('#sitebuilder-widget-form').submit(function() {

						function saveDefaultConfig(form) {
							$('body').css('cursor', 'wait');
							$('#config-dialog .action-buttons button').prop('disabled', true);

							var $currentModule = $('#config-dialog').data('selected-module');
							var xxxxwidgetId = $(form).find('#config_widgetid');

							var saveCustomizedCopy = $currentModule.hasClass('category-customized_copy');

							var saveUrl = saveCustomizedCopy ? form.action.replace(/saveAdminConfig/, 'saveDefaultConfig') : form.action;

							$.ajax({
								url:saveUrl,
								type:form.method,
								data:($(form).serializeArray()),
								dataType: 'json',
								success:function(result){
									console.log('saveAdminConfig successful!');
									$('body').css('cursor', 'auto');

									if (result && result.data){
										var $module = $('#config-dialog').data('selected-module');

										// update title if available
										var widgetTitle = result.data.title || result.data.tagCloudTitle || result.data.searchResultTitle;
										if (widgetTitle) {
											$module.find('.main-title').text(widgetTitle);
										}

										switch (result.data['widget_type']){
											case 'custom-html-widget': //HTML Module
												$module.find('.widget-content').html(result.data.html);
												toggleModuleContentVisibility($module, true);
												break;
											case 'video-widget': //Video Module
												var embedData = result.data.embed_data;
												if (embedData) {
													var $videoContainer = $module.find('.widget-content .videocontainer');
													if ($videoContainer.length == 0) {
														$videoContainer = $('<div />').addClass('videocontainer').appendTo($module.find('.widget-content'));
													}
													var data = {
														code: embedData.code,
														provider: embedData.provider,
														width: '100%',
														height: 260
													};
													//fetch object tag based on video provider and code
													$.get(pageData.baseurl + '/ajax/render/bbcode_video', data, function(template){
														if (template) {
															$videoContainer.empty().append(template);
															toggleModuleContentVisibility($module, true);
														}
													}, 'json');
													$module.find('.widget-content').find('.note').addClass('hide');
												}
												break;
										}

										// Update widget-default-tab attr for the widget
										var defaulttabselect = $('select[name="data[default_tab]"]', $(form));
										if (defaulttabselect.length > 0) {
											$module.attr('widget-default-tab', defaulttabselect.val());
										}
									}
									else {
										openAlertDialog({
											'title':vBulletin.phrase.get('error'),
											'message':vBulletin.phrase.get('invalid_server_response_please_try_again'),
											'iconType':'error',
											'onAfterClose':function(){
												$('#config-dialog .action-buttons button').prop('disabled', false);
											}
										});
										$('#config-dialog .loader').hide();
									}

									$('#config-dialog').dialog('close');
								},
								error:function(xhr, statusText, error){
									console.log('saveAdminConfig failed! error:' + error);
									$('body').css('cursor', 'auto');
									openAlertDialog({
										'title':vBulletin.phrase.get('error'),
										'message':vBulletin.phrase.get('error_saving_configuration_module', $('#config-dialog .widget-name h1').text()),
										'iconType':'error',
										'onAfterClose':function(){
											$('#config-dialog .action-buttons button').prop('disabled', false);
										}
									});
									$('#config-dialog .loader').hide();
								}
							});
						}

						var $form = this;

//						if ($('.config-dialog-container .channel-config-dialog:visible').length > 0)
//						{

//						}
//						else
//						{
										saveDefaultConfig($form);
//						}

						return false;
					});
					$('#btnCloseConfig').click(function(){
						$('.channel-config-dialog .channel-list').empty();
						$('#config-dialog').dialog('close');
					});
				},
				close:function(){
					toggleModuleFlashContentVisibility('visible');
					$('#config-dialog .dialog-content .channel-config-dialog').css('display', 'none')
					$('#config-dialog .action-buttons button').prop('disabled', false);
				}
			});

			//autofill for page url
			$('#pagetitle').bind('keyup blur', function(e){
				if (newPage){
					$('#pageurl').val(this.value.latinise().replace(/[^\w-]+/g,''));
				}
				return true;
			});

			//template option to show/hide template field (Save Page)
			$('#save-page-form #pagetemplateid-yes').click(function(){
				$('#save-page-form .template-name').addClass('hide');
				$('#save-page-form #templatetitle').prop('disabled', false);
				$('#save-page-form #templatetitle-edit').prop('disabled', true);
			});
			$('#save-page-form #pagetemplateid-no').click(function(){
				$('#save-page-form .template-name').removeClass('hide');
				$('#save-page-form #templatetitle').prop('disabled', true);
				$('#save-page-form #templatetitle-edit').prop('disabled', false);
			});

			//initialize search widget config dialog
			$('#search-config-dialog').dialog({
				title:vBulletin.phrase.get('edit_search_module'),
				autoOpen:false,
				modal:true,
				resizable:false,
				closeOnEscape:false,
				showCloseButton:false,
				width:800,
				dialogClass:'dialog-container search-config-dialog-container input-dialog',
				close:function(){
					toggleModuleFlashContentVisibility('visible');
				},
				open:function(){
					$('#search-config-dialog .loader').show();
					$('body').css('cursor', 'wait');
					//delay a bit to allow the 'wait' cursor to be visible
					setTimeout(function(){
						var initSearchConfig = function()
						{
							searchForm = new vBulletin_Search_Control("#customSearchDialog");
							loadConfig(searchForm);
							$('#search-config-dialog .loader').hide();
							$('body').css('cursor', 'auto');
						}
						var $searchWidgetInstance = $('#search-config-dialog').data('search-widget');
						var widgetData = {id: $searchWidgetInstance.attr('widget-id'), instanceid: $searchWidgetInstance.attr('widget-instance-id')};
						if(typeof vBulletin_Search_Control == 'undefined')
						{
							$.getScript(pageData.baseurl + '/js/sb_search.js?' + pageData.simpleversion, initSearchConfig);
						}
						else
						{
							initSearchConfig();
						}
					}, 1);

					hasConfigChanged = false;
				},

				create:function(){
					//init the search fields

					$('#btnSaveSearchConfig').click(function(){
						$('body').css('cursor', 'wait');
						//$('#loadingIcon').show();

						var $searchWidgetInstance = $('#search-config-dialog').data('search-widget');
						var widgetData = {id: $searchWidgetInstance.attr('widget-id'), instanceid: $searchWidgetInstance.attr('widget-instance-id')};

						var searchData = {
								pageid: pageData.pageid,
								widgetid: widgetData.id,
								widgetinstanceid: widgetData.instanceid,
								pagetemplateid: $('#select-template input[type=radio]:checked').val(),
								searchJSON: {}
						};

						var searchTitle = $('#searchTitle');
						if(searchTitle.length > 0 && $.trim(searchTitle.val()).length > 0)
						{
							searchData.searchTitle = $.trim(searchTitle.val());
							searchTitle.data('defaultValue', searchData.searchTitle);
						}

						var resultsPerPage = $('#resultsPerPage');
						if(resultsPerPage.length > 0 && $.trim(resultsPerPage.val()).length > 0)
						{
							searchData.resultsPerPage = $.trim(resultsPerPage.val());
							resultsPerPage.data('defaultValue', searchData.resultsPerPage);
						}

						// building search JSON
						searchData.searchJSON = searchForm.load();

						//submit the search data
						$.ajax({
							url:pageData.baseurl + '/index.php/ajax/api/widget/saveSearchWidgetConfig',
							data: {data: JSON.stringify(searchData)},
							type:'POST',
							dataType: 'json',
							complete:function(){
								$('body').css('cursor', 'auto');
								//$('#loadingIcon').hide();
							},
							success:function(result){
								console.log('savesearchWidgetConfig successful! result:' + JSON.stringify(result));
								//check results
								if (result && result.widgetinstanceid > 0 && result.searchJSON){
									//update the search widget instance on the main page

									$searchWidgetInstance.attr('widget-instance-id', result.widgetinstanceid);
									$searchWidgetInstance.find('.main-title').text(searchData.searchTitle);

									//close search config overlay
									$('#search-config-dialog').dialog('close');

									toggleModuleContentVisibility($searchWidgetInstance, true);

									hasConfigChanged = true;
								}
								else {
									openAlertDialog({
										'title':vBulletin.phrase.get('error'),
										'message':vBulletin.phrase.get('error_saving_search_config'),
										'iconType':'error'
									});
								}
							},
							error:function(xhr, statusText, error){
								console.log('saveSearchWidgetConfig failed! result:' + error);
								openAlertDialog({
									'title':vBulletin.phrase.get('error'),
									'message':vBulletin.phrase.get('error_saving_search_config_code', xhr.status),
									'iconType':'error'
								});
							}
						});
					});

					$('#btnCancelSearchConfig').click(function(){
						function closeSearchConfigDialog(){
							$('#search-config-dialog').dialog('close');

							//reset search criteria fields
							searchForm.set("{}");

							//reset search widget fields
							var searchTitle = $('#search-config-dialog #searchTitle');
							searchTitle.val(searchTitle.data('defaultValue'));

							var resultsPerPage = $('#search-config-dialog #resultsPerPage');
							resultsPerPage.val(resultsPerPage.data('defaultValue'));
						}
						if (hasConfigChanged){
							var $this = $(this);
							openConfirmDialog({
								'title': vBulletin.phrase.get('cancel_edit'),
								'message': vBulletin.phrase.get('do_you_want_to_cancel_editing_search_module'),
								'iconType':'warning',
								'onClickYes':closeSearchConfigDialog
							});
						}
						else {
							closeSearchConfigDialog();
						}
					});
				}
			});
		}  // end initializePageEditor()

		function loadConfig(container){
			var $widgetContainer = $(this).closest('.canvas-widget');
			var $searchWidgetInstance = $('#search-config-dialog').data('search-widget');
			var widgetData = {id: $searchWidgetInstance.attr('widget-id'), instanceid: $searchWidgetInstance.attr('widget-instance-id')};
			//get config items of the selected widget
			$.ajax({
				url:pageData.baseurl + '/index.php/ajax/api/widget/fetchSearchConfig',
				data:({
					widgetid: widgetData.id,
					widgetinstanceid: widgetData.instanceid||'', //if this widget instance has been configured before, its widget instance id exists, so use it
					pagetemplateid: $('#config_pagetemplateid').val() || $('#select-template input[type=radio]:checked').val() || '', //if New Page, no template is checked by default
					configtype: 'admin'
				}),
				type:'POST',
				dataType: 'json',
				complete:function(){
					$('body').css('cursor', 'auto');
				},
				success:function(result){
					console.log('fetchConfig successful! result:' + JSON.stringify(result));
					if(result.searchTitle){
						var searchTitle = $('#searchTitle');
						if(searchTitle.length > 0)
						{
							searchTitle.val(result.searchTitle);
						}
					}
					if(result.resultsPerPage){
						var resultsPerPage = $('#resultsPerPage');
						if(resultsPerPage.length > 0)
						{
							resultsPerPage.val(result.resultsPerPage);
						}
					}
					container.set(result.searchJSON || {}, result.contentTypes || {}, result.channels || {});
					$('#config-dialog .dialog-content .widget-config-container').show();
					$('#search-config-dialog .form_layout .form_row .field_column select').selectBox();
					$('#config-dialog .loader').hide();
				},
				error:function(xhr, statusText, error){
					console.log('fetchConfigSchema failed! error:' +  error);
					openAlertDialog({
						'title':vBulletin.phrase.get('error'),
						'message':vBulletin.phrase.get('error_retrieving_configuration', widgetName),
						'iconType':'error',
					'onAfterClose':function(){
							$('#config-dialog').dialog('close');
						}
					});
					$('#config-dialog .loader').hide();
				}
			});
		}
		initPage();
	});
})(jQuery);
