(function($){
	$(document).ready(function(){

		function initPage(){

			//reset form
			$('#sitebuilder-editpage-form').trigger('reset');

			//auto-fill for permalink field for creating new page only
			if ($('#editmode').val() == '0'){
				$('#pagetitle').bind('keyup blur', function(e){
					var link = this.value.replace(/[^\w-]+/g,'');

					if ($('#pagelink-container').is(':hidden')) {
						if ($('#subdomain-radio').is(':checked')){
							$('#displaylink').text($('#urlscheme').text() + link + $('#urlhostname').text());
						}
						else {
							$('#displaylink').text($('#baseurl').text() + link);
						}
					}
					$('#resturl, #subdomain').val(link);

				});
			}

			$('#btnEditLink').toggle(
				function(){
					$(this).text('OK');
					selectPermalinkOption();

					//remember original values in case user clicks Cancel
					$('#displaylink').data('orig-url', $('#displaylink').text());
					$('#resturl').data('orig-value', $('#resturl').val());
					$('#subdomain').data('orig-value', $('#subdomain').val());

					$('#displaylink').removeClass('url-style').text('Choose one of the following options for the permalink.');
					$('#pagelink-container').slideDown('slow');
					$('#lnkCancel').removeClass('hide');
				},
				function(e, isCancel){
					$(this).text('Edit');

					$('#pagelink-container').slideUp('slow', function(){
						if (isCancel){
							//reset Permalink fields to original values
							$('#resturl').val($('#resturl').data('orig-value'));
							$('#subdomain').val($('#subdomain').data('orig-value'));
						}
						else {
							//reset value of unselected permalink field to original value
							var $pagelinkTextbox = $('input[name=pagelink]:not(:checked)').next().next();
							$pagelinkTextbox.val($pagelinkTextbox.data('orig-value'));
						}
					});

					if (!isCancel){	//set selected permalink style display
						if ($('#subdomain-radio').is(':checked')){
							$('#displaylink').addClass('url-style').text($('#urlscheme').text() + $('#subdomain').val() + $('#urlhostname').text());
						}
						else if ($('#resturl-radio').is(':checked')){
							$('#displaylink').addClass('url-style').text($('#baseurl').text() + $('#resturl').val());
						}
						else {
							$('#displaylink').removeClass('url-style').text('Choose one of the following options for the permalink.');
						}

						//update original values of the selected permalink style
						$('#displaylink').data('orig-url', $('#displaylink').text());
						var $pagelinkTextbox = $('input[name=pagelink]:checked').next().next();
						$pagelinkTextbox.data('orig-value', $pagelinkTextbox.val());
					}
					else {
						$('#displaylink').addClass('url-style').text($('#displaylink').data('orig-url'));
					}
					$('#lnkCancel').addClass('hide');
				}
			);

			$('#lnkCancel').click(function(){
				$('#btnEditLink').trigger('click', [true]);
				return false;
			});

			//auto-check for permalink radio buttons
			$('#pagelink-container .option span').click(function(){
				$('input[type=radio]', $(this).parent()).click();
			});
			$('#pagelink-container .option input[type=text]').focus(function(){
				$('input[type=radio]', $(this).parent()).click();
			});

			$('.page-menubar li a').click(function(){
				//show pointer icon
				$('.tooltip-pointer-up.show').removeClass('show').addClass('hide');
				$('.tooltip-pointer-up', $(this).parent()).removeClass('hide').addClass('show');

				//show content
				$('.content-items > div.show').removeClass('show').addClass('hide');
				$('.content-items > .content-' + $(this).parent().attr('id')).removeClass('hide').addClass('show');

				return false;
			});

			//for page header radio buttons
			$('input[name=pageheader]').click(function(){
				var itemToShow = $(this).parent().find('.subitem');
				//do not re-show
				if (!itemToShow.hasClass('shown')) {
					$('#page-header-container .option .shown').slideUp('slow').removeClass('shown');
					itemToShow.slideDown('slow').addClass('shown');
				}
				this.form.encoding = (this.id == 'radUploadLogo') ? 'multipart/form-data':'application/x-www-form-urlencoded';
			});

			$('#btnSave').click(function(){
				//@todo: temporary only
				//location.href = 'page';
				//return false;

				// @todo: Consider doing some AJAX form validation here?

				return true;
			});

			$('#btnCancel').click(function(){
				location.href = $(this).attr('data-cancel-url');
			});

			$('#sitebuilder-navbar-form').bind('reset', function(e, postResetCallback){
				$(this).find('.toggle-default-value').addClass('grayed-out');
				if (typeof postResetCallback == 'function') postResetCallback();
			});

			$('.addNavLink').click(function(){
				//reset form and then set flag for adding a main nav item
				$('#sitebuilder-navbar-form').trigger('reset', [function(){$('#parentnavid').val('');}]);

				$('#navbar-dialog').dialog('option', 'title', 'Add Navigation Bar');
				$('#navbar-dialog').dialog('open');
				return false;
			});

			$('.addSubNavLink a').live('click', function(){
				var id = $(this).closest('ul.subnav').attr('id').replace(/subnav-/, '');

				//reset form and then set flag for adding a subnav item
				$('#sitebuilder-navbar-form').trigger('reset', [function(){$('#parentnavid').val(id);}]);

				var mainNavItemText = $('#main-nav #main-nav-' + id + ' .nav-title').text();
				$('#navbar-dialog').dialog('option', 'title', mainNavItemText + ': Add Sub-Navigation Bar');
				$('#navbar-dialog').dialog('open');
				return false;
			});

			$('#main-nav .nav-item').live('mousedown', function(e, moveSubnav){
				//if (!$(this).hasClass('selected')){
					$('#main-nav .nav-item.selected').removeClass('selected');
					$(this).addClass('selected');

					$('.subnav.visible').removeClass('visible').addClass('invisible');
					var $subnavHeader = $('#subnav-header li').eq(0);
					$('#subnav-' + $(this).attr('id').replace(/main-nav-/, ''))
						.addClass('visible')
						.removeClass('invisible')
						//jQuery's .width() shows different results for diff browsers when value is a float, so just use .css('width')
						.css('left', $(this).index() * ($subnavHeader.outerWidth(true) - $subnavHeader.width() + parseFloat($subnavHeader.css('width'))) + 'px');

					$('#subnav-header > li.selected').removeClass('selected');
					$('#subnav-header > li').eq($(this).index()).addClass('selected');
				//}
			});

			$('#main-nav .nav-item').live('mouseup', function(e, scroll){
				if (!$(this).hasClass('selected')) return false;
				if (typeof scroll == 'undefined') scroll = true; //undefined occurs when user does the actual mouseup action (not undefined when programmatically triggered by the script)

				var $subnavHeader = $('#subnav-header li').eq(0);
				$('#subnav-' + $(this).attr('id').replace(/main-nav-/, ''))
					.addClass('visible')
					.removeClass('invisible')
					//jQuery's .width() shows different results for diff browsers when value is a float, so just use .css('width')
					.css('left', $(this).index() * ($subnavHeader.outerWidth(true) - $subnavHeader.width() + parseFloat($subnavHeader.css('width'))) + 'px');

				$('#subnav-header > li').eq($(this).index()).addClass('selected');

				if (scroll){
					var left = parseInt($('.subnav.visible').css('left'), 10);
					if (isNaN(left)) return false;
					var diff = left - 40; //subtract 40 to make the nav item to the left of the current nav item partially visible thereby making that item easily selectable without manually scrolling
					$('.nav-container').animate({
					   scrollLeft: diff
					}, 'slow');
				}
			});

			//for subnav items
			$('.subnav-list .nav-item').live('mousedown', function(e){
				$('.subnav-list .nav-item.selected').removeClass('selected');
				$(this).addClass('selected');
			});

			$('#subnav-header li').live('click', function(){
				$('#main-nav .nav-item').eq($(this).index()).trigger('mousedown');
				$('#main-nav .nav-item').eq($(this).index()).trigger('mouseup');
			});

			//make main nav items draggable and droppable
			$('#main-nav').sortable({
				placeholder: "nav-item highlight round-corner5",
				stop: function(event, ui){
					ui.item.trigger('mousedown');
					ui.item.trigger('mouseup', [true]);
				},
				update:function(event, ui){

				},
				sort:function(event, ui){
					ui.item.addClass('shadow');
				},
				start:function(event, ui){
					$('.subnav.visible').removeClass('visible').addClass('invisible');
					$('#subnav-header > li.selected').removeClass('selected');
					ui.item.removeClass('shadow');
					if ($.browser.msie && parseInt($.browser.version, 10) == 8){ //IE8 nav item height is bigger
						ui.item.height(ui.item.height()-4);
					}
					ui.item.css('z-index', '99999'); //for IE7*/
					ui.placeholder.height(ui.item.height());
				},
				handle:'.grip-icon',
				items:'.nav-item'
			}).disableSelection();

			//make subnav items draggable and droppable
			makeSubnavSortable();

			$('.sb-page-edit #page, .sb-page-edit #navpagetitle, .sb-page-edit #navwebtitle, .sb-page-edit #navweburl').focus(function(){
				$('input[type=radio]', $(this).parent().prev()).click();
			});

			//Edit button in Add Navigation Bar dialog
			$('#btnEditUserGroup').toggle(toggleShowUserGroup, toggleHideUserGroup);

			//close button of main nav item
			$('#main-nav .nav-item .close-button').live('click', function(){
				//ask for user confirmation before removing the nav item
				$('#confirm-dialog .dialog-content').attr('data-navtype', 'main');
				$('#confirm-dialog .dialog-content').html('<p>Do you really want to remove the <strong>' + $(this).prev().text() + '</strong> navigation item?</p><p>All its sub-navigation items will also be removed.</p>');
				$('#confirm-dialog').dialog('open');
			});

			//close button of subnav item
			$('.subnav-list .nav-item .close-button').live('click', function(){
				//ask for user confirmation before removing the subnav item
				$('#confirm-dialog .dialog-content').attr('data-navtype', 'sub');
				$('#confirm-dialog .dialog-content').html('<p>Do you really want to remove the <strong>' + $(this).prev().text() + '</strong> sub-navigation item?</p>');
				$('#confirm-dialog').dialog('open');
			});

			//Add Navigation Bar dialog
			$('#navbar-dialog').dialog({
				title:'Add Navigation Bar',
				autoOpen:false,
				modal:true,
				resizable:false,
				closeOnEscape:false,
				width:600,
				dialogClass:'sb-dialog-container navbar-dialog-container shadow-dark',
				open:function(){
					//hide #usergroup-list if shown and reset text
					if (!$('#usergroup-list').is(':hidden')){
						$('#btnEditUserGroup').trigger('click', [true]);
					}
					$('.usergroup-label').html('Select the user groups that can view this tab.');
				},
				create:function(){
					$('#btnAddNavBar').click(function(){
						var url, title, newWin, usergroups = [];
						if ($('#navbar-dialog input[name=navtype]:checked').val() == 'webaddress'){
							url = $.trim($('#navweburl').val());
							title = $.trim($('#navwebtitle').val());
							newWin = $('#newwin').is(':checked');

							//validate entries for Web Address fields
							if (title == $('#navwebtitle').attr('defaultValue')){
								showErrorDialog('Please enter the Web address title.');
								return false;
							}
							if (url == $('#navweburl').attr('defaultValue')){ //@todo:validate url format
								showErrorDialog('Please enter the Web address.');
								return false;
							}
						}
						else {
							url = $('#page option:selected').val();
							title = $('#navpagetitle').val();
							newWin = false;

							//validate entries for Page List fields
							if (!url){
								showErrorDialog('Please select a page.');
								return false;
							}
							if (title == $('#navpagetitle').attr('defaultValue')){
								showErrorDialog('Please enter the page title.');
								return false;
							}
						}
						$('#usergroup-list input:checked').each(function(){
							usergroups.push(this.value);
						});

						//add main nav item
						if ($('#parentnavid').val() == ''){
							//main nav items have to stay in one line so we have to expand the width of main-nav as needed
							var $navItem = $('#main-nav .nav-item');
							if (($navItem.outerWidth(true) * ($navItem.length+1)) > $('.nav-container').width()){
								$('#main-nav, #subnav-header').width($('#main-nav').width() + $navItem.outerWidth(true));
							}

							//add sub navigation header
							$('#subnav-header').append('<li>Sub Navigation<span>&#9660;</span></li>');

							var navId = 'new-' + new Date().getTime();

							//add sub navigation content
							$('<ul id="subnav-{0}" class="subnav invisible">\
									<li class="addSubNavLink"><a href="#">+ Sub-Navigation</a></li>\
							   </ul>'.format(navId))
							   .appendTo('.subnav-list');

							//add navigation item
							$('<li id="main-nav-{0}" class="nav-item round-corner5 shadow" data-url="{1}" data-usergroups="{2}" data-new-window="{3}">\
								<div class="grip-icon left"><div>&uml;</div><div>&uml;</div><div>&uml;</div><div>&uml;</div></div>\
								<div class="nav-title left">{4}</div>\
								<div class="close-button right">x</div>\
								<div class="clear"></div>\
							   </li>'.format(navId, url, usergroups.join(','), newWin, title)
							   ).appendTo('#main-nav')
								.trigger('mousedown')
								.trigger('mouseup', [false]);

							//scroll to the rightmost
							var navContainer = $('.nav-container').get(0);
							$(navContainer).animate({
							   scrollLeft: navContainer.scrollWidth - navContainer.clientWidth
							}, 'fast');

							//call .sortable() again to make the recently added subnav item draggable and droppable
							makeSubnavSortable();
						}
						else {	//add subnav item
							$('<li class="nav-item round-corner5 shadow" data-url="{0}" data-usergroups="{1}" data-new-window="{2}">\
								<div class="grip-icon left"><div>&uml;</div><div>&uml;</div><div>&uml;</div><div>&uml;</div></div>\
								<div class="nav-title left">{3}</div>\
								<div class="close-button right">x</div>\
								<div class="clear"></div>\
							   </li>'.format(url, usergroups.join(','), newWin, title)
							).insertBefore('.subnav-list #subnav-' + $('#parentnavid').val() + ' .addSubNavLink');

							adjustNavContainerHeight();

							$('#main-nav #main-nav-' + $('#parentnavid').val()).trigger('mouseup', [true]);

						}

						$('#navbar-dialog').dialog('close');

					});

					$('#btnCancelNavBar').click(function(){
						$('#navbar-dialog').dialog('close');
					});
				}
			});

			//Confirm Delete dialog
			$('#confirm-dialog').dialog({
				title:'Remove Navigation Item?',
				autoOpen:false,
				modal:true,
				resizable:false,
				closeOnEscape:false,
				width:500,
				dialogClass:'sb-dialog-container confirm-dialog-container shadow-dark',
				create:function(){
					$('#btnYes').click(function(){
						if ($('#confirm-dialog .dialog-content').attr('data-navtype') == 'main'){ //main nav item
							$('#main-nav .nav-item.selected').remove();
							$('#subnav-header li.selected').remove();
							$('.subnav-list .subnav.visible').remove();
						}
						else { //subnav item
							$('.subnav-list .nav-item.selected').remove();
							adjustNavContainerHeight();
						}
						$('#confirm-dialog').dialog('close');
					});

					$('#btnNo').click(function(){
						$('#confirm-dialog').dialog('close');
					});
				},
				open:function(){
					$('#btnNo').focus();
				}
			});

			initErrorDialog();
		}

		//adjust height of nav-container based on the tallest absolutely positioned subnav when adding or removing a subnav item to avoid vertical scrollbars to appear
		function adjustNavContainerHeight(){
			var tallestSubnavHeight = 0;
			$('.subnav-list .subnav').each(function(){
				if ($(this).outerHeight(true) > tallestSubnavHeight){
					tallestSubnavHeight = $(this).outerHeight(true);
				}
			});

			var offset = 27;
			var navTotalHeight = tallestSubnavHeight + $('#main-nav').outerHeight(true) + $('#subnav-header').outerHeight(true) + offset;

			if (navTotalHeight > $('.nav-container').height()){
				$('.nav-container').height(navTotalHeight);
			}
			else if (navTotalHeight > parseFloat($('.nav-container').css('min-height'))){
				$('.nav-container').height(navTotalHeight);
			}
			else {
				$('.nav-container').height('auto');
			}
		}

		function adjustNavWidth(navItemAdded){
			var $navItem = $('#main-nav .nav-item');
			var offset = 20;
			var n = (navItemAdded) ? 1 : 0;
			if (($navItem.outerWidth(true) * ($navItem.length + n)) > $('.nav-container').width()){
				$('#main-nav, #subnav-header').width($('#main-nav').width() + $navItem.outerWidth(true) + offset);
			}
		}

		function makeSubnavSortable(){
			$('.subnav-list .subnav').sortable({
				placeholder: "nav-item highlight round-corner5",
				stop: function(event, ui){
					adjustNavContainerHeight();
				},
				update:function(event, ui){

				},
				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 nav item height is bigger
						ui.item.height(ui.item.height()-4);
					}
					ui.item.css('z-index', '99999'); //for IE7*/
					ui.placeholder.height(ui.item.height());
				},
				scroll:false,
				handle:'.grip-icon',
				items:'.nav-item'
			}).disableSelection();
		}

		function selectPermalinkOption(){
			var subdomain = $.trim($('#urlscheme').text()) + $.trim($('#subdomain').val()) + $.trim($('#urlhostname').text());
			if ($.trim($('#displaylink').text()) == subdomain){
				$('#subdomain-radio').click();
			}
			else { //default
				$('#resturl-radio').click();
			}
		}

		function toggleShowUserGroup(e){
			$('#usergroup-list').slideDown('slow');
			$(this).html('Done');
			$('.usergroup-label').html('Select the user groups that can view this tab.');
		}

		function toggleHideUserGroup(e, noAnimation){
			if (noAnimation){
				$('#usergroup-list').hide();
			}
			else {
				$('#usergroup-list').slideUp('slow');
			}
			$(this).html('Edit');
			if ($('#usergroup-list input:checked').length == $('#usergroup-list input').length)
				$('.usergroup-label').html('All users can view this tab.');
			else if ($('#usergroup-list input:checked').length > 0)
				$('.usergroup-label').html('Some users can view this tab.');
			else
				$('.usergroup-label').html('No user can view this tab.');
		}

		initPage();
	});
})(jQuery);