﻿

/**
@class Static class with all generic dialog functionality.
*/
var Dialogs = {};

/** Callback function to call after ColorPicker dialog is closed */
Dialogs.ColorPickerDialogCallback = null;

/** Default speed increments for holding the numeric spinners in the dialogs */
Dialogs.NumericSpinnerIncrements = [{ count: 5, mult: 1, delay: 170 },
									  { count: 15, mult: 1, delay: 100 },
									  { count: 0, mult: 1, delay: 50}];

/** Backup of the HTML of the opened dialogs. This is a stack, please push/pop elements */
Dialogs.dialogElementBackup = Array();

/** Is Fullscreen viewer open? */
Dialogs.fullScreenViewerOpen = false;

/** Is replace dialog open? */
Dialogs.ReplacePictureDialogRunning = false;

//===================================== GENERIC DIALOGS ======================================//

Dialogs.ShowErrorMessage = function (message, title)
{
	title = title ? title : "Error";
	Dialogs.ShowModalMessage(message, title);
},

Dialogs.ShowInfoMessage = function (message, title)
{
	title = title ? title : "Notice";
	Dialogs.ShowModalMessage(message, title);
},


Dialogs.ShowModalMessage = function (message, title)
{
	var titleText = title ? title : "";
	message = (message != null && message != "") ? message : "";
	
	message = message.replaceAll("\n", "<br>");
	$("<div class='modal-dialog-text'>" + message + "</div>").dialog(
	{
		modal: true,
		resizable: false,
		title: titleText,
		'zIndex': 60004,
		buttons:
		[
			{
				text: "OK",
				click: function () { $(this).dialog("close"); }
			}
		]
	});

},

//===================================== FULL SCREEN VIEWER ======================================//

/**
Opens the dialog, showing the specified sequence in a full-screen slideshow.
@param {SequenceBox}	originalSequence		The sequence to show.
@param {Integer}		selectedItemIndex		The sequence child to show upon start.
*/
Dialogs.OpenFullScreenViewer = function (originalSequence, selectedItemIndex)
{
	if (Dialogs.fullScreenViewerOpen) return;
	Dialogs.fullScreenViewerOpen = true;
	dialogElement = $('.full-screen-viewer-dialog');
	width = 800;
	cleanupCallback = null;
	if (typeof (Editor) != 'undefined') Editor.isShowingDialog = true;
	Dialogs.dialogElementBackup.push(dialogElement.html());
	dialogElement.dialog({ 'resizable': false, 'modal': true, 'zIndex': 60003, 'width': width, close: function (event, ui)
	{
		$('.ui-widget-overlay').removeClass('fullscreen');
		$('.ui-dialog').removeClass('fullscreen');
		if (typeof (cleanupCallback) == 'function')
		{
			cleanupCallback();
		}
		Dialogs.CleanupDialogInternal(dialogElement);
	}
	});
	$('.ui-widget-overlay').addClass('fullscreen'); // Show the black overlay instead of the blue
	$('.ui-dialog').addClass('fullscreen'); // Show the black overlay instead of the blue
	dialogElement.show(); // can do .hide().fadeIn(300) instead
	$('.ui-widget-overlay').show(); //testt
	var parentVisualBox = null;

	var width = parseInt(dialogElement.find('.slideshow-parent-cell').innerWidth());
	var height = parseInt(dialogElement.find('.slideshow-parent-cell').innerHeight());
	dialogElement.find('.slideshow-parent').height(height + 'px'); // 100% DIV height inside table cell does not work in IE8. Lets set it explicitly.
	var pagination = typeof (originalSequence.vbPaginationVisible) != 'undefined' ? originalSequence.vbPaginationVisible : 'Hover';
	//console.log(width, height, originalSequence.vbFullScreenResizing);
	var attributes =
	{
		vbX: 0,
		vbY: 0,
		vbZ: 70000,
		vbWidth: width,
		vbHeight: height,
		vmClass: 'SlideShowBox',
		childContainer: dialogElement.find('.slideshow-parent'),
		vbPaginationVisible: pagination,
		vbItemResizing: originalSequence.vbFullScreenResizing,
		vbItemClickAction: 'ShowNextItem'
	};
	// Start a slideshow
	var slideShow = new SlideShowBox(attributes, true, parentVisualBox)
	// Add all the slides to the slideshow
	for (var idx in originalSequence.vcChildren)
	{
		var item = originalSequence.vcChildren[idx];
		var imageUrl = item.vcImageUrl;
		// Add slide
		var originalAttributes = {dontShowYet: true, vcImageOriginalWidth: item.vcImageOriginalWidth, vcImageOriginalHeight: item.vcImageOriginalHeight};
		var pic = slideShow.AddPicture(imageUrl, false, originalAttributes);
		// Copy info from original sequence
		pic.vmName = item.vmName;
		pic.vmTitle = item.vmTitle;
		pic.vmDescription = item.vmDescription;
		pic.vmLink = item.vmLink;
		pic.vcImageOriginalWidth = item.vcImageOriginalWidth;
		pic.vcImageOriginalHeight = item.vcImageOriginalHeight;
		pic.ResizeObjectTo(pic, pic.vbWidth, pic.vbHeight);
		pic.OnInfoChanged();

	}
	slideShow.SelectChildByIndex(selectedItemIndex);

	// Don't catch clicks on image
	dialogElement.find('.image').unbind('click').click(function (event)
	{
		event.stopPropagation();
	});
	console.log("XXX");
console.log(dialogElement.find('.paginator .background, .paginator .text, .paginator .loading, .paginator .inner'));
console.log("XXX");
	dialogElement.find('.paginator .background, .paginator .text, .paginator .loading, .paginator .inner').unbind('click').click(function (event)
	{
		event.stopPropagation();
	});

	// Catch clicks outside image - make them close the dialog.
	dialogElement.unbind('click').click(function (event)
	{
		Dialogs.CloseFullScreenViewer();
	});
	return dialogElement;
}

/**
Closes the dialog with the specified element.
@param {jQuery Object}		dialogElement	A jQuery object which selects the parent DOM-element of the dialog to close, e.g. $('#my-dialog')
@returns {jQuery Object}	The dialog element, as selected by jQuery.
*/
Dialogs.CloseFullScreenViewer = function()
{
	if (!Dialogs.fullScreenViewerOpen) return;
	Dialogs.fullScreenViewerOpen = false;
	dialogElement = $('.full-screen-viewer-dialog');
	Dialogs.CleanupDialogInternal(dialogElement);
	dialogElement.dialog('close');
	var html = Dialogs.dialogElementBackup.pop();
	dialogElement.html("<span></span");
	dialogElement.html(html);
	return dialogElement;
}




//===================================== LOGIN DIALOG ======================================//


/**
Open the login or register dialog, depends if the user has logged in before.
@param {Function}	callbackFunction	The function to call when the dialog is closed.
*/
Dialogs.OpenLoginOrRegisterDialog = function(callbackFunction)
{
	
	if ($.cookie('auth') == 'google')
	{
		// User that came from Google
		Dialogs.OpenLoginDialog(callbackFunction);
		window.top.location = "/auth"
	}
	
	
	if ($.cookie('im-is-registered') == '1')
	{
		// Existing users
		Dialogs.OpenLoginDialog(callbackFunction);

	}
	else
	{
		// New users
		Dialogs.OpenRegisterDialog(callbackFunction);
	}
}

/**
Open the login dialog.
@param {Function}	callbackFunction	The function to call when the dialog is closed.
*/
Dialogs.OpenLoginDialog = function(callbackFunction)
{
	var dialogElement = $('.login-dialog');
	Dialogs.LoggedInSuccessfully = false;
	Dialogs.LoginDialogSkipCallback = false;
	Dialogs.OpenDialogInternal(dialogElement, 420, function()
	{
		if (!Dialogs.LoginDialogSkipCallback) callbackFunction(Dialogs.LoggedInSuccessfully);
	}
	);
	dialogElement.find(".register").click(function()
	{
		Dialogs.LoginDialogSkipCallback = true;
		Dialogs.CloseLoginDialog(false);
		Dialogs.OpenRegisterDialog(callbackFunction)
	});

	dialogElement.find(".forgot").click(function()
	{
		Dialogs.LoginDialogSkipCallback = true;
		Dialogs.CloseLoginDialog(false);
		Dialogs.OpenForgotDialog(callbackFunction)
	});

}


/**
Close the login dialog.
@param {boolean}	save	Specifies whether the changes in the dialog should be saved and applied to the text.
*/
Dialogs.CloseLoginDialog = function (save)
{
	var dialogElement = $('.login-dialog');
	if (save)
	{
		dialogElement.find(".kvp-vertical").removeClass("error");
		var name = dialogElement.find(".name").val();
		var namePattern = /^[a-zA-Z0-9]+$/;
		var failed = false;
		if (!namePattern.test(name))
		{
			dialogElement.find(".kvp-name").addClass("error");
			dialogElement.find(".kvp-name .key-error").html('Please enter a valid name:');
			failed = true;
		}

		var password = dialogElement.find(".password").val();
		var passwordPattern = /^[a-zA-Z0-9]+$/;
		if (!passwordPattern.test(password))
		{
			dialogElement.find(".kvp-password").addClass("error");
			dialogElement.find(".kvp-password .key-error").html('Please enter a valid password:');
			failed = true;
		}

		if (failed) return false;

		var options =
			{
				type: 'POST',
				url: Configuration.GetLoginPostPath(),
				dataType: 'json',
				success: function (res, statusText, xhr, formElement)
				{
					if (typeof (res.Error) != 'undefined')
					{
						var error = res.Error;
						if (error == 'Wrong Password')
						{
							dialogElement.find(".kvp-password").addClass("error");
							dialogElement.find(".kvp-password .key-error").html('Wrong password, please try again:');
						}
						else
						{
							if (error == 'Wrong Username') error = 'User not found, please try again:';
							dialogElement.find(".kvp-name").addClass("error");
							dialogElement.find(".kvp-name .key-error").html(error);
						}
					}
					else
					{
						$.cookie('im-is-registered', '1', { expires: 365*10 });
						Dialogs.LoggedInSuccessfully = true;
						username = $.cookie('username'); // update the GLOBAL username
						if (username == null) username == "User";
						Login.UpdateGuiOnUserLoggedIn(username);
						Dialogs.CloseDialogInternal(dialogElement);
					}
				}
			};
		dialogElement.find(".login-dialog-form").ajaxSubmit(options);
	}
	else
	{
		// Just close it...
		Dialogs.CloseDialogInternal(dialogElement);
	}
}




/**
Redirection helper
@param {String}	successUrl		URL to redirect the user to, after a successful login.
@param {String}	[failureUrl]	URL to redirect the user to, after the user refused to login.
If failureUrl is not specified, will redirect to successUrl in either case.
*/
Dialogs.RedirectCallback = function (successUrl, failureUrl)
{
	return function (success)
	{
		if (success)
		{
			window.top.location = successUrl;
		}
		else
		{
			if (typeof (failureUrl) == 'string')
			{
				window.top.location = failureUrl;
			}
		}
	}
}





//===================================== FORGOT DIALOG ======================================//


/**
Open the login dialog.
@param {Function}	callbackFunction	The function to call when the dialog is closed.
*/
Dialogs.OpenForgotDialog = function(callbackFunction)
{
	var dialogElement = $('.forgot-dialog');
	Dialogs.OpenDialogInternal(dialogElement, 420, function()
	{
		callbackFunction(Dialogs.LoggedInSuccessfully);
	}
	);

	dialogElement.find(".login").click(function()
	{
		Dialogs.CloseForgotDialog(false);
		Dialogs.OpenLoginDialog(callbackFunction)
	});

}


/**
Close the login dialog.
@param {boolean}	save	Specifies whether the changes in the dialog should be saved and applied to the text.
*/
Dialogs.CloseForgotDialog = function(save, callbackOnSuccess)
{
	var dialogElement = $('.forgot-dialog');
	if (save)
	{
		var failed = false;
		var email = dialogElement.find(".email").val();
		var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
		if (!emailPattern.test(email))
		{
			dialogElement.find(".kvp-email").addClass("error");
			dialogElement.find(".kvp-email .key-error").html('Please enter a valid e-mail:');
			failed = true;
		}

		if (failed) return false;

		var options =
			{
				type: 'GET',
				url: Configuration.GetForgotPostPath(),
				dataType: 'json',
				iframe: false, /* set iframe to false, otherwise it will send POST instead of GET */
				success: function(res, statusText, xhr, formElement)
				{
					dialogElement.find(".kvp-vertical").removeClass("error");
					if (typeof (res.Error) != 'undefined')
					{
						Dialogs.ShowErrorMessage(res.Error, "Error Sending E-Email");
					}
					else
					{
						Dialogs.ShowInfoMessage("You will receive an email shortly!\nThank you.", "E-mail Sent");
						Dialogs.CloseDialogInternal(dialogElement);
					}
				}
			};
		dialogElement.find(".forgot-dialog-form").ajaxSubmit(options);
	}
	else
	{
		// Just close it...
		Dialogs.CloseDialogInternal(dialogElement);
	}
}





//===================================== REGISTRATION DIALOG ======================================//

/**
Open the register dialog.
@param {Function}	callbackFunction	The function to call when the dialog is closed.
*/
Dialogs.OpenRegisterDialog = function(callbackFunction)
{
	var dialogElement = $('.register-dialog');
	Dialogs.RegisteredSuccessfully = false;
	Dialogs.OpenDialogInternal(dialogElement, 420, function()
	{
		if (Dialogs.RegisteredSuccessfully)
		{
			callbackFunction(Dialogs.RegisteredSuccessfully);
		}
	}
	);
	dialogElement.find(".login").click(function()
	{
		Dialogs.CloseRegisterDialog(false);
		Dialogs.OpenLoginDialog(callbackFunction)
	});

}


/**
Close the register dialog.
@param {boolean}	save	Specifies whether the changes in the dialog should be saved and applied to the text.
*/
Dialogs.CloseRegisterDialog = function(save)
{
	var dialogElement = $('.register-dialog');

	
	
	if (save)
	{
		dialogElement.find(".kvp-vertical").removeClass("error");
		var failed = false;

		var agree = dialogElement.find(".agree:checked").val();
		if (!agree)
		{
			dialogElement.find(".kvp-agree").addClass("error");			
			failed = true;			
		}

		var email = dialogElement.find(".email").val();
		var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
		if (!emailPattern.test(email))
		{
			dialogElement.find(".kvp-email").addClass("error");
			dialogElement.find(".kvp-email .key-error").html('Please enter a valid e-mail:');
			failed = true;
		}

		var username = dialogElement.find(".username").val();
		var usernamePattern = /^[a-zA-Z0-9]{3,20}$/;
		if (!usernamePattern.test(username))
		{
			dialogElement.find(".kvp-username").addClass("error");
			dialogElement.find(".kvp-username .key-error").html('Username must be 3-20 alphanumeric chars:');
			failed = true;
		}

		var password = dialogElement.find(".password").val();
		var passwordPattern = /^[a-zA-Z0-9]{3,20}$/;
		if (!passwordPattern.test(password))
		{
			dialogElement.find(".kvp-password").addClass("error");
			dialogElement.find(".kvp-password .key-error").html('Password must be 3-20 alphanumeric chars:');
			failed = true;
		}

		if (failed) return false;

		var options =
			{
				type: 'POST',
				url: Configuration.GetRegisterPostPath(),
				dataType: 'json',
				success: function(res, statusText, xhr, formElement)
				{
					
					if (typeof (res.Error) != 'undefined')
					{
						var error = res.Error;
						if (error == "Wrong Username")
						{
							error = "Username already exists";
						}
						dialogElement.find(".kvp-username").addClass("error");
						dialogElement.find(".kvp-username .key-error").html(error);

					}
					else
					{
						$.cookie('im-is-registered', '1', { expires: 365 * 10 });
						Dialogs.RegisteredSuccessfully = true;
						Dialogs.CloseDialogInternal(dialogElement);
					}
				}
			};
		
		
		
		usernameNew = username;
		
		Tracking.TrackImEvent("registered/");
		dialogElement.find(".register-dialog-form").ajaxSubmit(options);
	}
	else
	{
		// Just close it...
		Dialogs.CloseDialogInternal(dialogElement);
	}
}


//===================================== SAVE AS DIALOG ======================================//

Dialogs.SaveAsDialogSave = false;

/**
Open the link dialog.
@param {Function}	callbackFunction	The function to call when the dialog is closed.
*/
Dialogs.OpenSaveAsDialog = function(callbackFunction)
{
	var dialogElement = $('.save-as-dialog');
	Dialogs.SaveAsDialogSave = false;
	dialogElement.find(".error").html('&nbsp');
	Dialogs.OpenDialogInternal(dialogElement, 500, function()
	{
		var name = dialogElement.find(".name").val();
		callbackFunction(Dialogs.SaveAsDialogSave, name);
	}
	);
}

/**
Close the color picker dialog.
@param {boolean}	save	Specifies whether the changes in the dialog should be saved and applied to the text.
*/
Dialogs.CloseSaveAsDialog = function(save)
{
	var dialogElement = $('.save-as-dialog');
	if (save)
	{
		Dialogs.SaveAsDialogSave = true;
		var name = dialogElement.find(".name").val();
		var namePattern = /^[a-zA-Z0-9_-]{2,30}$/;
		if (!namePattern.test(name))
		{
			dialogElement.find(".error").html('Name must be 2-30 alphanumeric chars, without spaces');
			return false;
		}
		else
		{
			var name = dialogElement.find(".name").val();			
			Dialogs.CloseDialogInternal(dialogElement);
		}

	}
	else
	{
		Dialogs.SaveAsDialogSave = false;
		Dialogs.CloseDialogInternal(dialogElement);
	}
}


//===================================== LINK DIALOG DIALOG ======================================//

/**
Open the info (title/description/link) dialog.
@param {Function}	callbackFunction	The function to call when the dialog is closed.
*/
Dialogs.OpenSuperboxEditDialog = function(callbackFunction, objPointer)
{
	if (!callbackFunction) callbackFunction = function() { };
	
	if (!objPointer){
		alert("not superbox")
		obj = CurrentPage().GetSelectedChild();
	} else {
		alert("superbox")
		obj = objPointer;
	}
	
	
	var link = obj.vmLink;
	var anchor = obj.vmAnchor;

	// Open the dialog
	var dialogElement = $('.superbox-edit-dialog');
	Dialogs.OpenDialogInternal(dialogElement, 540, function()
	{
		Dialogs.SaveSuperboxEditToDialog(objPointer);
	}
	);
	
	
	dialogElement.find('.text-style-button').unbind('click').click(function()
	{
		Uploader.HideButton(); // Hide flash button so it doesn't overlay new dialogs
		var target = $(this).attr('id').replace('text-style-','');
		if (target == 'title')
			obj.OpenTextStyleDialog('Title', obj.vbTitleStyle, obj.defaultTitleStyle, obj.contentElement.find('.title'));
		if (target == 'description')
			obj.OpenTextStyleDialog('Description', obj.vbDescriptionStyle, obj.defaultDescriptionStyle, obj.contentElement.find('.description'));
		if (target == 'link')
			obj.OpenTextStyleDialog('Link', obj.vbLinkStyle, obj.defaultLinkStyle, obj.contentElement.find('.link'));
	});

	dialogElement.find(".ItemResizing").change(function()
	{
		Dialogs.SaveSuperboxEditToDialog(objPointer);
	});
	
	dialogElement.find(".checkbox").change(function()
	{
		Dialogs.SaveSuperboxEditToDialog(objPointer);
	});
			

	var pages = CurrentDevice().GetChildren();
	for (var i = 0; i < pages.length; i++)
	{
		var page = pages[i];
		var option = $('<option value="' + page.vbId + '">' + page.vmTitle + '</option>');
		dialogElement.find(".page-val").append(option);
	}

	dialogElement.find('.ItemResizing .' + obj.vbItemResizing).attr('selected', 'selected');

	dialogElement.find('.mainTitle').val(obj.vmTitle.replaceAll("<br>", "\n"));
	dialogElement.find('.description').val(obj.vmDescription.replaceAll("<br>", "\n"));
	dialogElement.find('.ImageEnabled').attr('checked', obj.vbImageEnabled ? true : false);
	dialogElement.find('.AudioEnabled').attr('checked', obj.vcAudioEnabled ? true : false);
	dialogElement.find('.AudioAutoPlay').attr('checked', obj.vcAudioAutoPlay ? true : false);
	dialogElement.find('.AudioLoop').attr('checked', obj.vcAudioLoop ? true : false);
	dialogElement.find('.mainTitle,.description,.link-text').unbind('keyup').keyup(function() 
			{ 
				Dialogs.SaveSuperboxEditToDialog(objPointer);
			});

	
	// Set type
	dialogElement.find(".link-val-container." + link.Type).show();
	dialogElement.find('.link-type .' + link.Type).attr('selected', 'selected');
	// Set URL
	dialogElement.find('.' + link.Type + '-val').val(link.Url); // Textbox
	// Set Target
	dialogElement.find('.target').val(link.Target);
	// Set Text
	dialogElement.find('.link-text').val(link.Text);
	
	dialogElement.find('.replace-image-button').hover(
			function() {Uploader.ShowButton($(this), null, 'image');}
			
	);
	dialogElement.find('.replace-audio-button').hover(
			function() {Uploader.ShowButton($(this), 'REPLACE-AUDIO', 'audio');}
	);
	
	
}


Dialogs.SaveSuperboxEditToDialog = function(objPointer)
{
	var dialogElement = $('.superbox-edit-dialog');
	
	var type = dialogElement.find('.link-type :selected').val();
	var target = dialogElement.find('.target').val();
	var text = dialogElement.find('.link-text').val();

	if (type == 'page')
		var link = dialogElement.find('.' + type + '-val :selected').val(); // Dropdown
	else
		var link = dialogElement.find('.' + type + '-val').val(); // Textbox

	
	if (type == 'website' && (link.indexOf('http://') != 0) && (link.indexOf('https://') != 0)) link = 'http://' + link;
	obj.vmTitle = dialogElement.find('.mainTitle').val().replace(/\n/g, "<br>");
	obj.vmDescription = dialogElement.find('.description').val().replace(/\n/g, "<br>");
	obj.vmLink = { Type: type, Url: link, Target: target, Text: text };
	obj.vbItemResizing = dialogElement.find('.ItemResizing :selected').val();
	obj.vbImageEnabled = dialogElement.find('.ImageEnabled').is(':checked');
	obj.vcAudioEnabled = dialogElement.find('.AudioEnabled').is(':checked');
	obj.vcAudioAutoPlay = dialogElement.find('.AudioAutoPlay').is(':checked');
	obj.vcAudioLoop = dialogElement.find('.AudioLoop').is(':checked');
	
	if (!objPointer){
		CurrentPage().GetSelectedChild().UpdateContent(); 
	} else {
		objPointer.UpdateContent(); 
	}
	
}

Dialogs.ExportSuperboxDialog = function(textOnly)
{
	var dt = (new Date()).toUTCString();
	var name = prompt("Enter a name for this preset", "Preset from " + dt);
	Dialogs.SaveSuperboxEditToDialog();
	var json = CurrentPage().GetSelectedChild().GeneratePresetJson(name);
	json = "\n" + json + ",\n";
	alert(json);
}



/**
Close the color picker dialog.
@param {boolean}	save	Specifies whether the changes in the dialog should be saved and applied to the text.
*/
Dialogs.CloseSuperboxEditDialog = function()
{
	var dialogElement = $('.superbox-edit-dialog');
	Uploader.HideButton();
	Dialogs.CloseDialogInternal(dialogElement);
	// Update the texts on the superbox
	
	CurrentPage().GetSelectedChild().UpdateContent();
}

//===================================== LINK DIALOG DIALOG ======================================//

Dialogs.CloseLinkDialogSave = false;
/**
Open the info (title/description/link) dialog.
@param {Function}	callbackFunction	The function to call when the dialog is closed.
*/
Dialogs.OpenInfoDialog = function(obj, showLinkOnly, callbackFunction)
{
	
	if (obj.vmClass == 'SuperBox'){
		Dialogs.OpenSuperboxEditDialog(callbackFunction, obj);
		return;
	}
	
	var link = obj.vmLink;
	var anchor = obj.vmAnchor;
	Dialogs.CloseLinkDialogSave = false;


	// Open the dialog
	var dialogElement = $('.link-dialog');
	Dialogs.OpenDialogInternal(dialogElement, 500, function()
	{
		// If "Save"...
		if (Dialogs.CloseLinkDialogSave)
		{
			
			var type = dialogElement.find('.link-type :selected').val();
			var target = dialogElement.find('.target').val();

			if (type == 'page')
				var link = dialogElement.find('.' + type + '-val :selected').val(); // Dropdown
			else
				var link = dialogElement.find('.' + type + '-val').val(); // Textbox
	
			
			if (type == 'website' && (link.indexOf('http://') != 0) && (link.indexOf('https://') != 0)) link = 'http://' + link;


			var obj = {};
			obj.vmTitle = dialogElement.find('.mainTitle').val();
			obj.vmPlaceholder = dialogElement.find('.placeholder').val();
			obj.vmDescription = dialogElement.find('.description').val();
			if (type == 'file') // File upload links are changed asynchronously when upload is finished
			{
				obj.vmLink = CurrentPage().GetSelectedChild().vmLink;
			}
			else
			{
				obj.vmLink = { Type: type, Url: link, Target: target };
			}
			
			obj.vmAnchor = dialogElement.find('.anchor').val();
			console.log("Saving options dialog. Returning the following object to VB: ", obj);

			callbackFunction(obj);
		}
	}
	);

	// Toggle between info / link-only mode.
	if (showLinkOnly)
	{
		dialogElement.dialog('option', 'title', 'Set Link');
		dialogElement.find('.instructions-info').hide();
		dialogElement.find('.kvp.info-only').hide();
		dialogElement.find('.instructions-link').show();
	}
	else
	{
		dialogElement.dialog('option', 'title', 'Set Info');
		dialogElement.find('.instructions-info').show();
		dialogElement.find('.kvp.info-only').show();
		dialogElement.find('.instructions-link').hide();
	}


	dialogElement.find(".link-type").change(function()
	{
		var type = dialogElement.find('.link-type :selected').val();
		dialogElement.find(".link-val-container").hide();
		dialogElement.find(".link-val-container." + type).show();
		if (type=='file')
		{
			Uploader.ShowButton(dialogElement.find(".upload-button"), 'UPLOAD-LINK-FILE', 'file');
			url = CurrentPage().GetSelectedChild().vmLink.Url;
			if (url != null && url != '')
			{
				var index = url.lastIndexOf("/");
				var filename = url.substr(index+1);
			}
			else
			{
				filename = 'None, please upload:';
			}
			dialogElement.find('.link-val-container.file .filename').html(filename);
			}
		else
		{
			Uploader.HideButton();
		}
	});


	var pages = CurrentDevice().GetChildren();
	for (var i = 0; i < pages.length; i++)
	{
		var page = pages[i];
		var option = $('<option value="' + page.vbId + '">' + page.vmTitle + '</option>');
		dialogElement.find(".page-val").append(option);
	}

	dialogElement.find('.mainTitle').val(obj.vmTitle);
	dialogElement.find('.description').val(obj.vmDescription);
	dialogElement.find('.anchor').val(obj.vmAnchor);
	dialogElement.find('.placeholder').val(obj.vmPlaceholder);

	// Set type
	dialogElement.find(".link-val-container." + link.Type).show();
	dialogElement.find('.link-type .' + link.Type).attr('selected', 'selected');
	if (link.Type=='file') Uploader.ShowButton(dialogElement.find(".upload-button"), 'UPLOAD-LINK-FILE', 'file');
	// Set URL
	dialogElement.find('.' + link.Type + '-val').val(link.Url); // Textbox
	// Set Target
	dialogElement.find('.target').val(link.Target);
	
	// Set ID for upload filename
	var filenameElementId = 'vb-'+CurrentPage().GetSelectedChild().vbId+'-download-name';
	dialogElement.find('.link-val-container.file .filename').attr('id', filenameElementId);

	
	dialogElement.find(".link-type").change();
}


/**
Close the color picker dialog.
@param {boolean}	save	Specifies whether the changes in the dialog should be saved and applied to the text.
*/
Dialogs.CloseLinkDialog = function(save)
{
	var dialogElement = $('.link-dialog');
	Uploader.HideButton();
	Dialogs.CloseLinkDialogSave = save;
	Dialogs.CloseDialogInternal(dialogElement);
}




//===================================== COLOR PICKER DIALOG ======================================//

/**
Open the color picker dialog.
@param {String}		initialColor		The initial color to start the color picker with, in hexadecimal format: #FFFFFF.
@param {Function}	callbackFunction	The function to call when the dialog is closed.
*/
Dialogs.OpenColorPickerDialog = function(initialColor, callbackFunction)
{
	var dialogElement = $('.generic-colorpicker-dialog');
	Dialogs.ColorPickerDialogCallback = callbackFunction;

	Dialogs.OpenDialogInternal(dialogElement, 400);
	dialogElement.find('.static-color-picker-value').val(initialColor);
	// Remove old color picker
	dialogElement.find('.static-color-picker').children().remove();
	dialogElement.find('.static-color-picker').removeData('colorpickerId');
	// Put new color picker
	dialogElement.find('.static-color-picker').ColorPicker(
				{
					flat: true,
					color: initialColor,
					onChange: function(hsb, hex, rgb)
					{
						dialogElement.find('.static-color-picker-value').val('#' + hex);
					}
				});
}


/**
Close the color picker dialog.
@param {boolean}	save	Specifies whether the changes in the dialog should be saved and applied to the text.
*/
Dialogs.CloseColorPickerDialog = function(save)
{
	var dialogElement = $('.generic-colorpicker-dialog');
	if (save)
	{
		var hex = dialogElement.find('.static-color-picker-value').val();
		Dialogs.ColorPickerDialogCallback(hex);
	}
	Dialogs.ColorPickerDialogCallback = null;

	Dialogs.CloseDialogInternal(dialogElement);
}




//===================================== NEW PAGE DIALOG ======================================//

Dialogs.NewPageDialogGridElementsX = 3;
Dialogs.NewPageDialogGridElementsY = 2;


/**
Open the "Add a new page" dialog.
@param {Function}	callbackFunction	The function to call when the dialog is closed.
*/
Dialogs.OpenNewPageDialog = function(callbackFunction)
{
	var dialogElement = $('.new-page-dialog');
	dialogElement = Dialogs.OpenDialogInternal(dialogElement, 920, callbackFunction);

	var parentElement = CurrentDevice();
	var children = parentElement.GetChildren();
	dialogElement.find(".children").empty();
	// For each row (each row represents a child item)
	for (var i = 0; i < children.length; i++)
	{
		var childVB = children[i];
		var childUI = dialogElement.find(".child-template").clone().removeClass('child-template').addClass('real-child');

		// Fill internal info (VBID etc.)
		childUI.attr('id', "child-" + childVB.vbId);

		// Fill info
		childUI.find('.name').html(childVB.vmTitle);
		var imageUrl = '../images/reorder/page-placeholder.png';
		childUI.find('.preview').css('background', "url('" + imageUrl + "') no-repeat");
		childUI.find('.preview').css('background-size', "100%");
		childUI.find('.preview').css('-moz-background-size', "100%");


		childUI.click(function()
		{
			var pageVbid = $(this).attr('id').substring(6);
			var page = CurrentDevice().GetChildObjectByVbid(pageVbid);
			Dialogs.CloseNewPageDialog(false);

			if (page.vbShowInMenu)
			{
				// Already visible, duplicate
				CurrentDevice().DuplicateChildByVbid(pageVbid, true);
				// Select the last page
				CurrentDevice().SelectChildByIndex(CurrentWebsite().vcChildren.length - 1); // LG: Possible bug here? testt
			}
			else
			{
				// Not visible, make visible
				page.vbShowInMenu = true;
				// Select the shown page
				CurrentDevice().SelectChildByVbid(pageVbid); // LG: Possible bug here? testt
			}
		});

		// Append this row and show it
		dialogElement.find(".children").append(childUI).show();
	}
	dialogElement.find(".children .child-template").hide();
	dialogElement.find(".children").disableSelection();
	Dialogs.NewPageDialogGoToPage(0);

}


Dialogs.CloseNewPageDialog = function(save)
{
	var dialogElement = $('.new-page-dialog');
	Dialogs.CloseDialogInternal(dialogElement);
}


Dialogs.NewPageDialogGoToPage = function(pageNumber)
{
	Dialogs.NewPageDialogCurrentPage = pageNumber;
	Dialogs.NewPageDialogUpdate(500);
}


Dialogs.NewPageDialogUpdate = function(fade)
{
	var dialogElement = $('.new-page-dialog');
	var childElements = dialogElement.find('.children').children();
	childElements.show();
	var maxItemsInPage = Dialogs.NewPageDialogGridElementsX * Dialogs.NewPageDialogGridElementsY; 
	var minVisibleItemIndex = Dialogs.NewPageDialogCurrentPage * maxItemsInPage;
	var maxVisibleItemIndex = minVisibleItemIndex + maxItemsInPage - 1;
	var numberOfPages = Math.floor((childElements.size() - 1) / maxItemsInPage) + 1;
	dialogElement.find(".paginator .inner").children().remove();
	if (numberOfPages > 1)
	{
		dialogElement.find(".paginator").css('height', '20px');
		for (var i = 0; i < numberOfPages; i++)
		{
			var gallery = this;
			var isThisPageSelected = (i == Dialogs.NewPageDialogCurrentPage);
			var imagePath = isThisPageSelected ? "../images/editor/gallery-page-selected.png" : "../images/editor/gallery-page.png";
			var pageTo = dialogElement.find(".paginator .inner").append("<img class='page-button' src='" + imagePath + "' id='pageTo-" + i + "'/>");
			pageTo.unbind('click').click(function(event)
			{
				var idx = parseInt(event.target.id.substring(7));
				Dialogs.NewPageDialogGoToPage(idx);
				event.stopPropagation();
			});
		}
	}
	else
	{
		dialogElement.find(".paginator").css('height', '0');
	}


	childElements.each(function(index, element)
	{
		var showThisItem = (index >= minVisibleItemIndex && index <= maxVisibleItemIndex);
		if (!showThisItem)
		{
			$(this).hide()
		}
		else
		{
			$(this).show();
		}
				
		// Find current column and row
		var currentCol = (index % Dialogs.NewPageDialogGridElementsX) + 1;
		var lastCol = (currentCol == Dialogs.NewPageDialogGridElementsX);
		var currentRow = Math.floor(index / Dialogs.NewPageDialogGridElementsX) + 1;
		var lastRow = (currentRow == Dialogs.NewPageDialogGridElementsY);
		//debug.log(index, currentCol, lastCol, currentRow, lastRow);
			
		// Add margins to cell (this is our grid spacing)
		if (lastCol) $(this).css('margin-right', '0');
		if (lastRow) $(this).css('margin-bottom', '0');
		
	});

}


//===================================== REORDER DIALOG ======================================//


Dialogs.ReorderDialogParent = null;

/** Reorder dialog: (1) Pictures Sequences (2) Pages Sequence */
Dialogs.ReorderDialogType = null;

/**
Open the order generic dialog.
@param {Function}	callbackFunction	The function to call when the dialog is closed.
*/
Dialogs.OpenReorderDialog = function(type, parent)
{
	Dialogs.ReorderDialogType = type;
	Dialogs.ReorderDialogParent = parent;
	var dialogElement = $('.generic-reorder-dialog');
	dialogElement = Dialogs.OpenDialogInternal(dialogElement, 500, Dialogs.CleanupReorderDialog);

	if (Dialogs.ReorderDialogType == 1) // Show "Add a Pic" button
	{
		$('.generic-reorder-dialog .buttons .new-item').html("Add a picture");
		var uploadBottomOffsetX = 10;
		var uploadBottomOffsetY = -42;

		// Move the upload button to follow the dialog
		Uploader.ShowButton($('.generic-reorder-dialog .buttons .new-item'), null);
		Uploader.MoveButton(dialogElement.offset().left + uploadBottomOffsetX,
						dialogElement.offset().top + dialogElement.height() + uploadBottomOffsetY);
		dialogElement.bind("dialogdragstop", function(event, ui)
		{
			Uploader.MoveButton(dialogElement.offset().left + uploadBottomOffsetX,
						dialogElement.offset().top + dialogElement.height() + uploadBottomOffsetY);
		});
	}
	else if (Dialogs.ReorderDialogType == 2)	// Show "Add a Page" button
	{
		$('.generic-reorder-dialog .buttons .new-item').html("Add a Page");
		$('.generic-reorder-dialog .buttons .new-item').click(function()
		{
			Dialogs.OpenNewPageDialog(function()
			{
				setTimeout(function() {Dialogs.RefreshReorderDialog()}, 0);
			}
			);
			
		});
	}
	else if (Dialogs.ReorderDialogType == 3) // Menu items
	{
		$('.generic-reorder-dialog .buttons .new-item').html("Add an Item");
		$('.generic-reorder-dialog .buttons .new-item').click(function()
		{
			var menuItem = new MenuItemBox();
			menuItem.vmTitle = 'New Menu Item';
			menuItem.vmLink = { Type: 'none', Url: '', Target: '_blank' };
			parent.vcChildren.push(menuItem);			
			menuItem.OpenInfoDialog(function() { Dialogs.RefreshReorderDialog(); })
			
		});
	}

	Dialogs.RefreshReorderDialog(dialogElement);

}


Dialogs.ClearReorderDialog = function ()
{
	var dialogElement = $('.generic-reorder-dialog');
	dialogElement.find(".children .real-child").remove();
	dialogElement.find(".children .child-template").show();
}

Dialogs.OnSortUpdate = function(event, ui)
{
	var dialogElement = $('.generic-reorder-dialog');
	var parentElement = Dialogs.ReorderDialogParent;
	var movedLine = ui.item;
	var vbid = movedLine.attr('id').substring(6);

	// Final original and new index
	var originalIndex = parentElement.GetChildIndexByVbid(vbid);
	var newIndex = -1;
	dialogElement.find(".children .real-child").each(function(index, element) { if (element.id == movedLine.attr('id')) newIndex = index; });

	// Make the swap, then update GUI
	if (newIndex < 0 || newIndex >= parentElement.vcChildren.length) return;
	parentElement.MoveChildFromIndexToIndex(originalIndex, newIndex);
	parentElement.SelectChildByIndex(newIndex);
	Dialogs.RefreshReorderDialog();

}

Dialogs.ReorderDialogMoveElement = function (vbid, moveUp)
{
	// Find original and new index
	var parentElement = Dialogs.ReorderDialogParent;
	var originalIndex = parentElement.GetChildIndexByVbid(vbid);
	var newIndex = originalIndex + (moveUp ? -1 : 1);

	// Make the swap, then update GUI
	if (newIndex < 0 || newIndex >= parentElement.vcChildren.length) return;
	parentElement.MoveChildFromIndexToIndex(originalIndex, newIndex);
	if (originalIndex == parentElement.vcSelectedChildIndex)
		parentElement.SelectChildByIndex(newIndex); // Move along with the swap
	else
		parentElement.SelectChildByIndex(parentElement.vcSelectedChildIndex); // Just refresh, keep current selection
	Dialogs.RefreshReorderDialog();

}

Dialogs.RefreshReorderDialog = function()
{
	var dialogElement = $('.generic-reorder-dialog');
	if (dialogElement.css('display') == 'none') return; // Rorder Dialog is not opened
	Dialogs.ClearReorderDialog();
	var parentElement = Dialogs.ReorderDialogParent;
	var selectedChild = parentElement.GetSelectedChild();
	var children = parentElement.GetChildren();

	// For each row (each row represents a child item)
	for (var i = 0; i < children.length; i++)
	{
		var childVB = children[i];
		var childUI = dialogElement.find(".children .child-template").clone().removeClass('child-template').addClass('real-child');

		// Is this the selected child?
		if (childVB.vbId == selectedChild.vbId) childUI.addClass('selected');

		var imageUrl = '';
		if (childVB.vmClass == 'PictureBox') imageUrl = childVB.vcImageUrl.replace('get_pic?', 'get_pic?width=60&height=60&');
		if (childVB.vmClass == 'SuperBox') imageUrl = childVB.vcChildren[0].vcImageUrl.replace('get_pic?', 'get_pic?width=60&height=60&');
		if (childVB.vmClass == 'PageBox') imageUrl = '../images/reorder/page-placeholder.png';
		childUI.find('.preview').css('background', "url('" + imageUrl + "') no-repeat");
		childUI.find('.preview').css('background-size', "100%");
		childUI.find('.preview').css('-moz-background-size', "100%");

		// Fill internal info (VBID etc.)
		childUI.attr('id', "child-" + childVB.vbId);
		childUI.find('.actions').attr('id', "actions-" + childVB.vbId);
		childUI.find('.actions2').attr('id', "actions-" + childVB.vbId);

		childUI.click(function() { var vbid = $(this).attr('id').substring(6); parentElement.SelectChildByVbid(vbid); Dialogs.RefreshReorderDialog(); });

		// Fill info
		childUI.find('.name').val(childVB.vmTitle);
		childUI.find('.name').keyup(function() { var vbid = $(this).parent().attr('id').substring(8); parentElement.GetChildObjectByVbid(vbid).vmTitle = $(this).val(); Dialogs.RefreshMenuIfNecessary(); });
		childUI.find('.name').click(function(e) { e.stopPropagation(); return true; });
		childUI.find('.toggle').css('display', Dialogs.ReorderDialogType == 2 ? 'block' : 'none');
		childUI.find('.toggle .checkbox').attr('checked', childVB.vbShowInMenu ? true : false);
		childUI.find('.name').css('width', Dialogs.ReorderDialogType == 2 ? '150px' : '185px');

		// Hide/show actions
		childUI.find('.actions .setinfo').css('display', Dialogs.ReorderDialogType==2?'none':'block'); // Jonathan's testt SEO removed
		childUI.find('.actions .duplicate').css('display', Dialogs.ReorderDialogType==3?'none':'block');

		// Event handlers
		childUI.find('.move .move-up').click(function() { var vbid = $(this).parent().parent().attr('id').substring(6); Dialogs.ReorderDialogMoveElement(vbid, true); });
		childUI.find('.move .move-down').click(function() { var vbid = $(this).parent().parent().attr('id').substring(6); Dialogs.ReorderDialogMoveElement(vbid), false; });
		childUI.find('.actions .setinfo').click(function() { 
			var vbid = $(this).parent().attr('id').substring(8); 
			parentElement.GetChildObjectByVbid(vbid).OpenInfoDialog(function() { Dialogs.RefreshReorderDialog(); }); });
				
		childUI.find('.actions .duplicate').click(function() { var vbid = $(this).parent().attr('id').substring(8); parentElement.DuplicateChildByVbid(vbid, false); Dialogs.RefreshReorderDialog(); })
		childUI.find('.actions .delete').click(function() { var vbid = $(this).parent().attr('id').substring(8); parentElement.DeleteChildElement(vbid); Dialogs.RefreshReorderDialog(); });
		childUI.find('.toggle .checkbox').click(function() { var vbid = $(this).parent().parent().attr('id').substring(6); parentElement.GetChildObjectByVbid(vbid).vbShowInMenu = $(this).attr('checked') ? true : false; CurrentPage().GetMenu().Refresh(); });

		// Append this row and show it
		dialogElement.find(".children").append(childUI).show();
	}
	dialogElement.find(".children .child-template").hide();

	dialogElement.find(".children").sortable({ axis: 'y', cursor: 's-resize', opacity: 1.0, update: Dialogs.OnSortUpdate });
	dialogElement.find(".children .actions").disableSelection();
	Dialogs.RefreshMenuIfNecessary();

}

Dialogs.RefreshMenuIfNecessary = function()
{
	
	console.log("Rfresh menu if necess "+Dialogs.ReorderDialogType);
	
	if (Dialogs.ReorderDialogType == 1) // Reorder items - update slide/gallery
	{
		if (CurrentPage().GetSelectedChild()){
			CurrentPage().GetSelectedChild().Refresh();
		}
		
	}
	
	if (Dialogs.ReorderDialogType == 2) // Reorder Pages - update main menu
	{
		if (CurrentPage() && CurrentPage().GetMenu()) CurrentPage().GetMenu().Refresh();
	}
	if (Dialogs.ReorderDialogType == 3) // Reorder items in regular menu - update the menu iteself
	{
		CurrentPage().GetSelectedChild().Refresh();
	}

}

Dialogs.CloseReorderDialog = function (save)
{
	var dialogElement = $('.generic-reorder-dialog');
	Dialogs.ClearReorderDialog(dialogElement);
	Dialogs.CloseDialogInternal(dialogElement);
}



Dialogs.CleanupReorderDialog = function()
{
	if (Dialogs.ReorderDialogType == 1) // Images
	{
		if (Editor.currentSubMenu == 'elements-menu' || Editor.currentSubMenu == 'clear')
		{
			// Simply hide the upload button
			Uploader.HideButton();
		}
		else
		{
			// Fix the position of the upload button
			Uploader.ShowButton($('.creator .submenu .submenu-content.' + Editor.currentSubMenu + ' .add-pic-button'), null);
		}
	}
	Viewer.WirePicturesInfo(); // So info-hover works even after replacing elements contents with clones
}



//===================================== TEXT ADVANCED-OPTIONS DIALOG ======================================//

/**
Open the text advanced-options dialog.
*/
Dialogs.OpenTextAdvancedDialog = function()
{
	var dialogElement = $('.text-advanced-dialog');
	dialogElement = Dialogs.OpenDialogInternal(dialogElement);
	dialogElement.find('.letter-spacing').spinner(
			{ 'min': -100, 'max': 100, 'step': 0.02, 'largeStep': 1, 'suffix': 'em', 'increment': Dialogs.NumericSpinnerIncrements });
	
	dialogElement.find('.line-height').spinner(
			{ 'min': -100, 'max': 100, 'step': 0.02, 'largeStep': 1, 'suffix': 'em', 'increment': Dialogs.NumericSpinnerIncrements });

	dialogElement.find('.padding-left,.padding-right,.padding-bottom').spinner(
			{ 'min': -100, 'max': 100, 'step': 2, 'largeStep': 1, 'suffix': 'px', 'increment': Dialogs.NumericSpinnerIncrements });
	
	
	
	var box = CurrentPage().GetSelectedChild();
	if (box.vmClass == 'ParagraphBox')
	{
		dialogElement.find('.scroll-group').show();
		dialogElement.find('.scroll').attr('checked', box.vbShowScroll);
	}
	else
	{
		dialogElement.find('.scroll-group').hide();
	}
	
	//testt: retrieve letter spacing
	/*var selectedText = tinyMCE.activeEditor.selection.getContent({format:"raw"});
	var el = CurrentPage().GetSelectedChild().contentElement.find('p:contains('+selectedText+')');
	debug.log(el)*/
	
	var letter_spacingg = '0em';
	var line_heightt = '1em';
	var left_marginn = '0px';
	var right_marginn = '0px';
	var bottom_marginn = '0px';
	var top_marginn = '0px';
	
	//testt:  initializing span properties
	dialogElement.find('.letter-spacing').val(letter_spacingg);
	dialogElement.find('.line-height').val(line_heightt);
	dialogElement.find('.padding-left').val(left_marginn);
	dialogElement.find('.padding-right').val(top_marginn);
	dialogElement.find('.padding-bottom').val(bottom_marginn);
	
	//separated the update
	dialogElement.find('.letter-spacing').unbind('change').change(function() { Dialogs.SaveTextAdvancedDialogLetterSpacing(); });
	dialogElement.find('.line-height').unbind('change').change(function() { Dialogs.SaveTextAdvancedDialogLineHeight(); });
	dialogElement.find('.padding-left, .padding-right, padding-top, padding-bottom').unbind('change').change(function() { Dialogs.SaveTextAdvancedDialog(); });
}


Dialogs.SaveTextAdvancedDialog = function()
{
	var dialogElement = $('.text-advanced-dialog');
	var paddingLeft = dialogElement.find('.padding-left').val();
	var paddingRight = dialogElement.find('.padding-right').val();
	var paddingTop = dialogElement.find('.padding-top').val();
	var paddingBottom = dialogElement.find('.padding-bottom').val();

	try
	{
		tinyMCE.activeEditor.formatter.apply('padding_left', { 'val': paddingLeft });
		tinyMCE.activeEditor.formatter.apply('padding_right', { 'val': paddingRight });
		tinyMCE.activeEditor.formatter.apply('padding_top', { 'val': paddingTop });
		tinyMCE.activeEditor.formatter.apply('padding_bottom', { 'val': paddingBottom });
	}
	catch(e)
	{
		// This code sometimes throws exceptions, e.g. when there's no proper text selection.
		// Let's surpress the exceptions, otherwise it will affect the numeric spinner increment behavoior.
	}

}


Dialogs.SaveTextAdvancedDialogLetterSpacing = function()
{
	var dialogElement = $('.text-advanced-dialog');
	var letterSpacing = dialogElement.find('.letter-spacing').val();

	try
	{
		tinyMCE.activeEditor.formatter.apply('letter_spacing', { 'val': letterSpacing });
	}
	catch(e)
	{
	}

}

Dialogs.SaveTextAdvancedDialogLineHeight = function()
{
	var dialogElement = $('.text-advanced-dialog');
	var lineHeight = dialogElement.find('.line-height').val();

	try
	{
		tinyMCE.activeEditor.formatter.apply('line_height', { 'val': lineHeight });
	}
	catch(e)
	{
	}

}



/**
Close the text advanced-options dialog.
@param {boolean}	save	Specifies whether the changes in the dialog should be saved and applied to the text.
*/
Dialogs.CloseTextAdvancedDialog = function(save)
{
	var dialogElement = $('.text-advanced-dialog');
	if (save)
	{
		var box = CurrentPage().GetSelectedChild();
		if (box.vmClass == 'ParagraphBox')
		{
			box.vbShowScroll = dialogElement.find('.scroll').is(':checked');
			box.UpdateScroll();
		}

		var letterSpacing = dialogElement.find('.letter-spacing').val();
		var lineHeight = dialogElement.find('.line-height').val();
		var paddingLeft = dialogElement.find('.padding-left').val();
		var paddingRight = dialogElement.find('.padding-right').val();
		var paddingBottom = dialogElement.find('.padding-bottom').val();

		if (letterSpacing != '0em')
			tinyMCE.activeEditor.formatter.apply('letter_spacing', { 'val': letterSpacing });
		else
			tinyMCE.activeEditor.formatter.toggle('letter_spacing', { 'val': letterSpacing });

		if (lineHeight != '1em')
			tinyMCE.activeEditor.formatter.apply('line_height', { 'val': lineHeight });
		else
			tinyMCE.activeEditor.formatter.toggle('line_height', { 'val': lineHeight });

		if (paddingLeft != '0em')
			tinyMCE.activeEditor.formatter.apply('padding_left', { 'val': paddingLeft });
		else
			tinyMCE.activeEditor.formatter.toggle('padding_left', { 'val': paddingLeft });


		if (paddingRight != '0em')
			tinyMCE.activeEditor.formatter.apply('padding_top', { 'val': paddingRight });
		else
			tinyMCE.activeEditor.formatter.toggle('padding_top', { 'val': paddingRight });
	}
	Dialogs.CloseDialogInternal(dialogElement);
}

//===================================== REPLCATE PIC DIALOG ======================================//


/**
Open the replace picture dialog.
@param {String}		initialColor		The initial color to start the color picker with, in hexadecimal format: #FFFFFF.
*/
Dialogs.OpenReplacePictureDialog = function (callbackFunction)
{
	var dialogElement = $('.replace-picture-dialog');
	Dialogs.ReplacePictureDialogRunning = true;
	Dialogs.OpenDialogInternal(dialogElement, 400);
	dialogElement.dialog({
		beforeClose: function (event, ui) { Dialogs.CloseReplacePictureDialog(); }
	});
	Uploader.ShowButton(dialogElement.find('.replace-pic-button'));
}


/**
Close the color picker dialog.
@param {boolean}	save	Specifies whether the changes in the dialog should be saved and applied to the text.
*/
Dialogs.CloseReplacePictureDialog = function ()
{
	if (!Dialogs.ReplacePictureDialogRunning) return;
	var dialogElement = $('.replace-picture-dialog');
	
	// Hide flash button, then reload the picture submenu, so the 'Replace Pic' is aligned with the flash button again.
	Uploader.HideButton();
	var picture = CurrentPage().GetSelectedChild();
	Editor.ShowSubMenu(picture.vmClass, picture);
	
	Dialogs.ReplacePictureDialogRunning = false;	
	Dialogs.CloseDialogInternal(dialogElement);
}


//===================================== HELPER METHODS ======================================//

/*
Opens the dialog with the specified element.
@param {jQuery Object}		dialogElement		A jQuery object which selects the parent DOM-element of the dialog to open, e.g. $('#my-dialog')
@param	{Integer}			[width=500]			The width of the dialog, in pixels.
@param	{Function}			[cleanupCallback]	An optional callback to be called to clean up the dialog when closed.
@returns {jQuery Object}	The dialog element, as selected by jQuery.
*/
Dialogs.OpenDialogInternal = function(dialogElement, width, cleanupCallback)
{
	if (typeof(Editor) != 'undefined') Editor.isShowingDialog = true;
	width = width ? width : 500;
	Dialogs.dialogElementBackup.push(dialogElement.html());
	//debug.log("After opening dialog: ", Dialogs.dialogElementBackup);
	
	dialogElement.dialog({ 'resizable': false, 'modal': true, 'zIndex': 60003, 'width': width, close: function(event, ui)
	{
		if (typeof (cleanupCallback) == 'function')
		{
			cleanupCallback();
		}
		Dialogs.CleanupDialogInternal(dialogElement);
	}
	});
	$('.ui-widget-overlay').removeClass('fullscreen');
	$('.ui-dialog').removeClass('fullscreen');
	$('.ui-dialog').removeClass('bigheader');
	$('.ui-dialog').removeClass('headerless');
	if (dialogElement.hasClass('headerless')) $('.ui-dialog').addClass('headerless');
	if (dialogElement.hasClass('bigheader')) $('.ui-dialog').addClass('bigheader');
	if (dialogElement.hasClass('cool')) $('.ui-dialog').addClass('cool');
	dialogElement.show(); // can do .hide().fadeIn(300) instead
	$('.ui-widget-overlay').show(); //testt
	return dialogElement;
}

/*
Closes the dialog with the specified element.
@param {jQuery Object}		dialogElement	A jQuery object which selects the parent DOM-element of the dialog to close, e.g. $('#my-dialog')
@returns {jQuery Object}	The dialog element, as selected by jQuery.
*/
Dialogs.CloseDialogInternal = function(dialogElement)
{
//	Dialogs.CleanupDialogInternal(dialogElement);
	dialogElement.dialog('close');
	return dialogElement;
}



/*
Performs cleanup when a dialog closes.
*/
Dialogs.CleanupDialogInternal = function(dialogElement)
{
	if (typeof (Editor) != 'undefined') Editor.isShowingDialog = false;
	//var html = Dialogs.dialogElementBackup.pop();
	//dialogElement.html("<span></span");
	//dialogElement.html(html);
	//debug.log("After closing dialog: ", Dialogs.dialogElementBackup);
}

