if (!jQueryMajCms) {
	"use strict";

	var jQueryMajCms = true;
	
	// extend maj and jQuery using an anonymous function to ensure variable scope safety.
	// this also allows us to change the maj namespace if we ever want to.
	(function(maj,$){

		//------------------------------------------------------------------------------
		// START: jQuery maj Plugin
		//------------------------------------------------------------------------------
		var jQueryMethods = {
			init: function(options) {},

			scrollIntoView: function() {
				try {
					this[0].scrollIntoView(true);
				} catch(err) {
				}

				return this;
			},

			// disabled/enable the moveUp/moveDown actions of for the various fragment editors.
			initMoveActions: function() {
				var $loEditors = this.find('.editor');
				$loEditors.each(function(index, element) {
					$('.toolbar .moveUp', element).toggleClass('disabled',index==0);
					$('.toolbar .moveDown', element).toggleClass('disabled',index==($loEditors.length-1));
				});

				return this;
			},

			deleteWebSitePageContentSection: function(webSitePageId, contentSectionId) {
				var $loThis = this;

				this.bind('click.majCms.deleteWebSitePageContentSection', function(e) {
					e.preventDefault();

					if ($loThis.is('.disabled, .working')) return;
					$loThis.toggleClass('working', true);

					// function to remove the 'working' class of this element.
					var mRemoveWorkingClass = function() {
						$loThis.toggleClass('working', false);
					};

					$().maj('showPrompt', {
						'middle': e.pageY,
						'message': 'Do you really want to delete this Section?',

						'okAction': {
							text: 'Yes, delete this Section',
							cssClass: 'red',
							callback: function() {

								var mCleanup = function() {
									$(this).remove();
									$('#pnlSections').majCms('initMoveActions');
								};

								// function to physically remove the section editor from the DOM.
								var mRemoveEditor = function() {
									$loThis.closest('.editor').slideUp(mCleanup);
								};

								maj.ajax.submitJob({
									url: 'WebSitePageDesignServices.aspx',
									successCallback: mRemoveEditor,
									failureCallback: mRemoveWorkingClass,
									parameters: { 'action': 'deleteSection', 'webSitePageId': webSitePageId, 'contentSectionId': contentSectionId}
								});

							}
						},

						'cancelAction': {
							text: 'No, leave it there',
							callback: mRemoveWorkingClass
						}
					});

				});

				return this;
			},

			// invokes the modal form to edit/add a content section.
			editWebSitePageContentSection: function(webSitePageId, contentSectionId, contentSectionIdToCopy, contentSectionIdToInsertAfter) {
				var $loThis = this;

				this.bind('click.majCms.editWebSitePageContentSection', function(e) {
					e.preventDefault();

					if ($loThis.is('.disabled, .working')) return;
					$loThis.toggleClass('working', true);

					var mRenderEditor = function(response) {
						// Append any extra Css and JavaScript required.
						$('head').maj('appendCssHrefs', response.CssHrefs)
										 .maj('appendJavaScriptUrls', response.JavaScriptUrls);

						$loPnlSections = $('#pnlSections');
						var $loEditor = $(response.HTMLFragments['editor']);

						if (contentSectionId) {
							// we have an existing section.
							$loThis.closest('.editor').replaceWith($loEditor);
						} else if (contentSectionIdToInsertAfter) {
							// we have a new section that is to be inserted after the editor this insert link is attached to.
							$loEditor.hide().insertAfter($loThis.closest('.editor'));
						} else {
							// we have a new section, by default it is inserted as the first section.
							$loPnlSections.prepend($loEditor.hide());
						}

						$loPnlSections.majCms('initMoveActions');

						if (contentSectionId) {
							// Highlight the updated section.
							$loEditor.find('.main').first().maj('highlightElement', 'editor done');
						} else {
							// Show the new section.
							$loEditor.slideDown();
						}

					}

					var loParams = [];
					loParams['majData'] = {'webSitePageId': webSitePageId, 'contentSectionId': contentSectionId, 'contentSectionIdToCopy': contentSectionIdToCopy, 'contentSectionIdToInsertAfter': contentSectionIdToInsertAfter};

					$().maj('showModalWindow', {
						'pageURL': 'WebSitePageDesignHtmlContentSection.aspx',
						'parameters': loParams,
						'postModalCallback': mRenderEditor,
						'commonCallback': function() {
							$loThis.toggleClass('working', false);
						}
					});
				});

				return this;
			},

			moveWebSitePageContentSection: function(webSitePageId, contentSectionId, moveUp) {
				this.bind('click.maj.moveWebSitePageContentSection', function(e) {
					e.preventDefault();

					var $loThis = $(this);
					var $loEditor = $loThis.closest('.editor');
					if ($loThis.is('.disabled, .working')) return;
					$loThis.toggleClass('working', true);

					var $loPnlSections = $('#pnlSections');
					var $loEditors = $loPnlSections.find('.editor');
					var liMyIdx = -1;
					$loEditors.each(function(index, element) {
						if (liMyIdx<0 && element==$loEditor[0]) {
							liMyIdx=index;
							return false;
						}
					});

					if (liMyIdx<0) return;

					var $loSwapWithEditor;
					if (moveUp) {
						if (liMyIdx==0) return;
						$loSwapWithEditor = $($loEditors[liMyIdx-1]);
					} else {
						if (liMyIdx==$loEditors.length-1) return;
						$loSwapWithEditor = $($loEditors[liMyIdx+1]);
					}

					var liSwapWithContentSectionId = $loSwapWithEditor.data('majCms.contentSectionId');
					if (!liSwapWithContentSectionId) return;

					var mRemoveWorking = function() {
						$loThis.toggleClass('working', false);
					};

					var mSwapEditors = function(response) {
						var liMyNewTop, liSwapNewTop;
						var loMyOffset = $loEditor.offset();
						var loSwapOffset = $loSwapWithEditor.offset();
						var liMyHeight = $loEditor.outerHeight();
						var liSwapHeight = $loSwapWithEditor.outerHeight();

						if (moveUp) {
							liMyNewTop = loSwapOffset.top;
							liSwapNewTop = loSwapOffset.top + liMyHeight + (loMyOffset.top - (loSwapOffset.top + liSwapHeight));
						} else {
							liMyNewTop = loMyOffset.top + liSwapHeight + (loSwapOffset.top - (loMyOffset.top + liMyHeight));
							liSwapNewTop = loMyOffset.top;
						};

						//var $loSwapShadow = $loSwapWithEditor.maj('shadowElement');
						var $loMyShadow = $loEditor.find('.main').first().maj('shadowElement', 'editor');
						var liExecCount = 0;

						var mActualSwap = function() {
							liExecCount++;
							if (moveUp) {
								$loSwapWithEditor.insertAfter($loEditor);
							} else {
								$loSwapWithEditor.insertBefore($loEditor);
							}
							$loPnlSections.majCms('initMoveActions');
							$loMyShadow.fadeOut(function(){ $loMyShadow.remove(); });
							mRemoveWorking();
						};

						$loMyShadow.fadeIn('fast').animate({'top': liMyNewTop}, {'complete': mActualSwap});
					};

					maj.ajax.submitJob({
						url: 'WebSitePageDesignServices.aspx',
						successCallback: mSwapEditors,
						failureCallback: mRemoveWorking,
						parameters: {'action': 'swapSections', 'webSitePageId': webSitePageId, 'contentSectionId': contentSectionId, 'swapWithContentSectionId': liSwapWithContentSectionId}
					});

				});
			},

			changeWebSitePageContentSectionStatus: function(webSitePageId, contentSectionId) {
				var $loThis = $(this);

				this.bind('click.maj.changeWebSitePageContentSectionStatus', function(e) {
					maj.ajax.submitJob({
						url: 'WebSitePageDesignServices.aspx',
						successCallback: null,
						commonCallback: function() {
							$loThis.toggleClass('working', false);
						},
						parameters: {'action': 'changeSectionStatus', 'webSitePageId': webSitePageId, 'contentSectionId': contentSectionId, 'ready': $loThis.is('.on')}
					});

				});
			},

			changeWebSitePageStatus: function(webSitePageId) {
				var $loThis = $(this);

				this.bind('click.maj.changeWebSitePageStatus', function(e) {
					maj.ajax.submitJob({
						url: 'WebSitePageDesignServices.aspx',
						successCallback: null,
						commonCallback: function() {
							$loThis.toggleClass('working', false);
						},
						parameters: {'action': 'changePageStatus', 'webSitePageId': webSitePageId, 'ready': $loThis.is('.on')}
					});

				});
			},

			webSitePageContentSectionEditor: function(webSitePageId, contentSectionId) {
				var $loToolbar = this.find('.toolbar').first();
				this.data('majCms.contentSectionId', contentSectionId);

				$loToolbar.find('.action.edit').majCms('editWebSitePageContentSection', webSitePageId, contentSectionId);
				$loToolbar.find('.action.createCopy').majCms('editWebSitePageContentSection', webSitePageId, 0, contentSectionId, contentSectionId);
				this.find('.action.insertSection').majCms('editWebSitePageContentSection', webSitePageId, 0, 0, contentSectionId);
				$loToolbar.find('.action.delete').majCms('deleteWebSitePageContentSection', webSitePageId, contentSectionId);

				$loToolbar.find('.action.moveUp').majCms('moveWebSitePageContentSection', webSitePageId, contentSectionId, true);
				$loToolbar.find('.action.moveDown').majCms('moveWebSitePageContentSection', webSitePageId, contentSectionId, false);

				$loToolbar.find('.majToggleSwitch').majCms('changeWebSitePageContentSectionStatus', webSitePageId, contentSectionId);
			},

			editWebSitePageTitle: function(webSitePageId) {
				return this.maj('designableLabel', {'addMessage': 'Add a Title to this Page', 'data': {'webSitePageId': webSitePageId}, 'pageUrl': 'WebSitePageDesignTitle.aspx'});
			},

			editWebSitePageIntro: function(webSitePageId) {
				return this.maj('designableLabel', {'addMessage': 'Add an Introduction to this Page', 'data': {'webSitePageId': webSitePageId}, 'pageUrl': 'WebSitePageDesignIntro.aspx'});
			},

			editWebSitePageName: function(webSitePageId) {
				return this.maj('designableLabel', {'addMessage': 'Give this Page a Name', 'data': {'webSitePageId': webSitePageId}, 'pageUrl': 'WebSitePageDesignName.aspx'});
			},

			highlightDaysCombo: function() {
				var $loThis = this;

				var mOnDaysChange = function() {
					var liDays = maj.math.parseNumber($loThis.find('select').val());
					$loThis.find('.newBadge').toggleClass('na', (liDays==0));
				};

				var lsNamespace = '.majCms.highlightDaysCombo';
				this.find('select').bind('change' + lsNamespace + ' blur' + lsNamespace + ' click' + lsNamespace, mOnDaysChange);
				mOnDaysChange();
			},

			imageSettings: function(imageId) {
				var $loThis = this;
				if ($loThis.is('.disabled, .working')) return;
				$loThis.toggleClass('working', true);

				var loParams = [];
				loParams['majData'] = {'imageId': imageId};

				$loThis.maj('showModalWindow', {
					'pageURL': 'CmsDesignInsertImageSettings.aspx',
					'parameters': loParams,
					'postModalCallback': function(response) {
						var lsImgHtml = response.HTMLFragments['img'];
						$('#txtHtmlContent').wysiwyg('insertHtml', lsImgHtml);
						$().maj('closeModalWindow');
					},
					'commonCallback': function() {
						$loThis.toggleClass('working', false);
					}
				});
			},

			imageFileUploader: function() {
				var loUploadFinishedCallback = function(response) {
					var loResponse = $.parseJSON(response);
					var loGrid = $('#grdImages');
					loGrid.find('tbody').prepend(loResponse.HTMLFragments['row']);
					loGrid.majCms('imageSettings', loResponse.Data['imageId']);
				};

				this.maj('imageFileUploader', {'uploadFinishedCallback': loUploadFinishedCallback});
				return this;
			},

			// inserts the image defined for a given row into a wysiwygeditor.
			insertImage: function() {
				var $loTableBody = this.find('table > tbody');

				$loTableBody.delegate('tr', 'click.majCms.insertImage', function(e) { 
					var $loRow = $(this);
					$loRow.majCms('imageSettings', $loRow.data('id'));

/*
					var $loLink = $(this);

					e.preventDefault();

					if ($loLink.is('.disabled, .working')) return;
					$loLink.toggleClass('working', true);

					var loParams = [];
					loParams['majData'] = {'url': $loLink.find('img').first().data('url')};

					$loThis.maj('showModalWindow', {
						'pageURL': 'CmsDesignInsertImageSettings.aspx',
						'parameters': loParams,
						'postModalCallback': function(response) {
							var lsImgHtml = response.HTMLFragments['img'];
							$('#txtHtmlContent').wysiwyg('insertHtml', lsImgHtml);
							$().maj('closeModalWindow');
						},
						'commonCallback': function() {
							$loLink.toggleClass('working', false);
						}
					});
*/
				});

			},

			wysiwygEditor: function() {
				var loHidden = {visible:false};

				//$('#wysiwyg').wysiwyg('insertImage', 'img/hourglass.gif');
				var loInsertImageCallback = function() {
					if (moModalResult) {
						this.wysiwyg('insertImage', moModalResult);
					}
				}

				var $loThis = this;
			
				this.wysiwyg({
					css: 'cms/style/majWysiwyg.css', 
					initialContent: '',
					autoSave: true,

					controls:{
						h1: loHidden, 
						h2: loHidden, 
						strikeThrough: loHidden,
						subscript: loHidden,
						superscript: loHidden,
						code: loHidden,
						createLink: loHidden,
						insertImage: loHidden,

						majInsertLink: {
							tooltip: 'Insert a Link',
							groupIndex: 11,
							visible: true,
							className: 'majCreateLink',
							exec: function() {
								var $loLink = $('.majCreateLink');
								if ($loLink.is('.working')) return;
								$loLink.toggleClass('working', true);

								$loThis.parent().maj('showModalWindow', {
									'pageURL': 'CmsDesignCreateLink.aspx',
									'postModalCallback': function(response) {
										var lsUrl = response.HTMLFragments['url'];
										$loThis.wysiwyg('createLink', lsUrl);
									},
									'commonCallback': function(response) {
										$loLink.toggleClass('working', false);
									}									
								});
							}
						},


						majInsertImage: {
							tooltip: 'Insert an Image',
							groupIndex: 11,
							visible: true,
							className: 'majInsertImage',
							exec: function() {
								var $loLink = $('.majInsertImage');
								if ($loLink.is('.working')) return;
								$loLink.toggleClass('working', true);
									
								$loThis.parent().maj('showModalWindow', {
									'pageURL': 'CmsDesignInsertImage.aspx',
									'commonCallback': function(response) {
										$loLink.toggleClass('working', false);
									}
								});
							}
						}
					}
				});

			},

			webSitePageActions: function() {
				this.delegate('tbody > tr > td > .action.delete', 'click.majCms.deleteWebSitePage', function(e) { 
					e.preventDefault();

					var $loThis = $(this);
					var $loRow = $loThis.closest('tr');
					var liWebSitePageId = $loRow.data('id');

					if ($loThis.is('.disabled, .working')) return;
					$loThis.toggleClass('working', true);

					// function to remove the 'working' class of this element.
					var mRemoveWorkingClass = function() {
						$loThis.toggleClass('working', false);
					};

					$().maj('showPrompt', {
						'middle': e.pageY,
						'message': 'This Page may be in use on this Web Site.  Do you really want to delete it?',

						'okAction': {
							text: 'Yes, delete this Page',
							cssClass: 'red',
							callback: function() {

								var mCleanup = function() {
									$loRow.remove();
								};

								// function to physically remove the row from the DOM.
								var mRemoveRow = function() {
									$loRow.fadeOut('slow', mCleanup);
								};

								maj.ajax.submitJob({
									url: 'WebSitePageDesignServices.aspx',
									successCallback: mRemoveRow,
									failureCallback: mRemoveWorkingClass,
									parameters: { 'action': 'deletePage', 'webSitePageId': liWebSitePageId }
								});

							}
						},

						'cancelAction': {
							text: 'No, leave it',
							callback: mRemoveWorkingClass
						}
					});

				});

				return this;
			}


		};


		$.fn.majCms = function(method) {
			// Method calling logic
			var loMethod = jQueryMethods[method];
			if (loMethod) {
				return loMethod.apply(this, Array.prototype.slice.call(arguments,1));
			} else if (typeof method === 'object' || !method) {
				return jQueryMethods.init.apply(this,arguments);
			} else {
				$.error('Method ' +	method + ' does not exist on jQuery.majCms');
			}
		};
		//------------------------------------------------------------------------------
		// END: jQuery majCms Plugin
		//------------------------------------------------------------------------------

	})(maj,jQuery);
}

