arButtons['save_and_exit'] = ['BXButton',
	{
		id : 'save_and_exit',
		iconkit : '_global_iconkit.gif',
		codeEditorMode : true,
		name : BX_MESS.TBSave,
		title : BX_MESS.TBSave,
		show_name : true,
		handler : function (){window.setTimeout(function(){BXVisualPageEditorDialogManager.getInstance().save();}, 100);}
	}
];

arButtons['exit'] = ['BXButton',
	{
		id : 'exit',
		iconkit : '_global_iconkit.gif',
		codeEditorMode : true,
		name : BX_MESS.TBExit,
		handler : function (){
			this.pMainObj.OnEvent("OnSelectionChange");
			window.setTimeout(function(){BXVisualPageEditorDialogManager.getInstance().exit();}, 100);
		}
	}
];

var ContentPlaceHolderList = ['BXList', {
	width: '150',
	height: '110',
	field_size: '120px',
	title: '(template)',
	bSetGlobalStyles: true,
	disableOnCodeView: false,
	values: [],
	OnCreate: function()
	{
		if (!this.pMainObj.arTemplateParams.CPH)
			return;
		
		this.values = this.pMainObj.arCPH ? this.pMainObj.arCPH : [];
		this.pMainObj.pCPHListbox = this;
		this.refreshList = function()
		{
			var arSC = this.pMainObj.pASPXParser.arShadowedControls;
			var cph = this.pMainObj.arTemplateParams.CPH;
			cph = cph ? cph : [];
			var _cph = {};
			// Refresh CPH list
			this.pMainObj.arCPH = [];
			var id, ocphid;
			for (var i = 0, l = cph.length; i < l; i++)
			{
				ocphid = cph[i];
				id = cph[i].toLowerCase();
				_cph[id] = true;
				this.pMainObj.arCPH.push({name:cph[i], value: id});
				if (arSC[id])
					continue;
				arSC[id] = { // Add new CPH to arShadowedControls
					id: id,
					ocphid: ocphid,
					attributes: {ID: id, runat: 'server'},
					prefix: 'asp',
					control: 'ContentPlaceHolder',
					close: '>',
					tagend: ['</asp:ContentPlaceHolder>']
				};
			}
			this.SetValues(this.pMainObj.arCPH);

			// Find first nonempty CPH and select it
			for (var id in arSC)
			{
				if (arSC[id].contentVal && _cph[id] && arSC[id].contentVal.length > 0)
				{
					this.SelectByVal(id);
					this.OnChange({value:id});
					break;
				}
			}
		};
		this.pMainObj.AddEventHandler("OnTemplateChanged", this.refreshList, this);
	},
	OnInit: function()
	{
		if (!this.pMainObj.arTemplateParams.CPH)
			return;
			
		this.SelectByVal(this.pMainObj.cphID);
		var arSC = this.pMainObj.pASPXParser.arShadowedControls;
		var cph = this.pMainObj.arTemplateParams.CPH;
		var _cph = {};
		for (var i = 0, l = cph.length; i < l; i++)
			_cph[cph[i].toLowerCase()] = true;

		var selId = false;

		for (var id in arSC)
		{
			if (id.toLowerCase() == this.pMainObj.arConfig.defaultCPH.toLowerCase())
			{
				selId = id;
				break;
			}
		}

		if (!selId)
			for (var id in arSC)
			{
				if (!selId) selId = id;
				if (arSC[id].contentVal && _cph[id] && arSC[id].contentVal.length > 0)
				{
					selId = id;
					break;
				}
			}
		this.SelectByVal(selId);
		this.pMainObj.pASPXParser.SetCurrentCPH(selId, true);
	},
	OnChange: function(selected)
	{
		this.pMainObj.pASPXParser.SetCurrentCPH(selected.value);
	}
	}
];


var arGlobalToolbar = [
	'line_begin',

	arButtons['save_and_exit'], arButtons['exit'],
	arButtons['Fullscreen'],
	arButtons['Settings'],
	arButtons['Cut'], arButtons['Copy'], arButtons['Paste'], arButtons['pasteword'], arButtons['pastetext'], arButtons['SelectAll'],
	arButtons['Undo'], arButtons['Redo'],
	arButtons['borders'], 'separator',
	arButtons['table'], arButtons['anchor'], arButtons['CreateLink'], arButtons['deletelink'], arButtons['image'],
	arButtons['SpecialChar'], arButtons['spellcheck'],
	arButtons['insert_flash'],

	arButtons['InsertHorizontalRule'], 'separator',
	arButtons['InsertOrderedList'], arButtons['InsertUnorderedList'], 'separator',
	arButtons['Outdent'], arButtons['Indent'],
	arButtons['BackColor'], arButtons['ForeColor'],

	'line_end',
	'line_begin',

	arButtons['wysiwyg'],
	arButtons['source'],
	arButtons['split'],
	arButtons['Wrap'],

	arButtons['FontStyle'], arButtons['HeadingList'], arButtons['FontName'], arButtons['FontSize'], 'separator',
	arButtons['Bold'], arButtons['Italic'], arButtons['Underline'], 'separator',
	arButtons['JustifyLeft'], arButtons['JustifyCenter'], arButtons['JustifyRight'], arButtons['JustifyFull'], 'separator',
	arButtons['RemoveFormat'], arButtons['Optimize'], 'separator',
	
	ContentPlaceHolderList,
	
	'line_end'
];

function RefreshValuesCPHToolbar(pMainObj)
{
	if (pMainObj && pMainObj.pCPHListbox && pMainObj.arCPH)
		pMainObj.pCPHListbox.SetValues(pMainObj.arCPH);
}


arEditorFastDialogs['asksave'] = function(pObj)
{
	var str = '<table height="100%" width="100%" id="t1" border="0">' +
	'<tr>' +
		'<td colspan="3">' +
			'<table height="100%" width="100%" id="t1" border="0" style="font-size:14px;">' +
			'<tr>' +
			'<td></td>' +
			'<td>' + BX_MESS.DIALOG_EXIT_ACHTUNG + '</td>' +
			'</tr>' +
			'</table>' +
		'</td>' +
	'</tr>' +
	'<tr id="buttonsSec" valign="top">' +
		'<td align="center"><input style="font-size:12px; height: 25px; width: 180px;" type="button" id="asksave_b1" value="' + BX_MESS.DIALOG_SAVE_BUT + '"></td>' +
		'<td align="center"><input style="font-size:12px; height: 25px; width: 180px;" type="button" id="asksave_b2" value="' + BX_MESS.DIALOG_EXIT_BUT + '"></td>' +
		'<td align="center"><input style="font-size:12px; height: 25px; width: 180px;" type="button" id="asksave_b3" value="' + BX_MESS.DIALOG_EDIT_BUT + '"></td>' +
	'</tr>' +
'</table>';

	var OnClose = function(){pObj.Close();};
	var OnSave = function(t)
	{
		window.setTimeout(function(){BXVisualPageEditorDialogManager.getInstance().save();}, 100);
		OnClose();
	};
	var OnExit = function(t)
	{
	    if(typeof(jsPopup) == "undefined")
	        throw "Could not find jsPopup!";
	    window.setTimeout(function(){BXVisualPageEditorDialogManager.getInstance().exitWithDisclaimingChanges();}, 100);
	    OnClose();
	};

	return {
		title: BX_MESS.EDITOR,
		innerHTML : str,
		OnLoad: function()
		{
			document.getElementById("asksave_b1").focus();
			document.getElementById("asksave_b1").onclick = OnSave;
			document.getElementById("asksave_b2").onclick = OnExit;
			document.getElementById("asksave_b3").onclick = OnClose;
		}
	};
}

//---BXVisualPageEditorDialogManager--//
BXVisualPageEditorDialogManager = function()
{
    this._initialized = false;
    this._chargeID = null;
    this._charge = null;
    this._redirectAfterExit = false;
    this._redirectionUrl = null;
}

BXVisualPageEditorDialogManager.prototype = 
{
	initialize: function()
	{
		if(this._initialized)
			throw "Already initialized!";
		this._initialized = true;
	},

	start: function(chargeName)
	{
		this._chargeID  = chargeName;
		jsUtils.addCustomEvent("EditorLoadFinish_" + this._chargeID, BXVisualPageEditorDialogManager.onEditorLoad);
	},

	save: function()
	{
		this._ensureChargeIsAssigned();
		//this._charge.isSubmited = true;
		this.set_charge(null);
		if(typeof(window["BX_DOTNET_WEB_EDITOR_CONTEXT"]) == "undefined")
			throw "Could not find editor context";

		var buttonId = BX_DOTNET_WEB_EDITOR_CONTEXT.ButtonIdSave;
		var button = typeof(buttonId) == "string" ? document.getElementById(buttonId) : null;

		if(!button)
			throw "Could not find save button";

		button.onclick();
	},

	exit: function()
	{
		//if (this._charge.bFullscreen)
		//	this._charge.SetFullscreen(false);
		this._ensureChargeIsAssigned();

		var need_to_ask = (this._charge.IsChanged() && !this._charge.isSubmited);

		if (need_to_ask)
		{
			this._charge.OpenEditorDialog("asksave", false, 600, {window: window, savetype: 'save', popupMode: true}, true);
			return;
		}

		if(this._charge)
			this._charge.prepareForClose();
		this.set_charge(null);
		if(typeof(jsPopup) == "undefined")
			throw "Could not find jsPopup!";

		jsPopup.CloseDialog();
		window.setTimeout(function(){BXVisualPageEditorDialogManager.getInstance().redirectIfNeed();}, 500);
    },

    _onBeforeCloseDialog: function()
    {
        this._ensureChargeIsAssigned();

	    var need_to_ask = (this._charge.IsChanged() && !this._charge.isSubmited);

	    if (need_to_ask)
	    {
		    this._charge.OpenEditorDialog("asksave", false, 600, {window: window, savetype: 'save', popupMode: true}, true);
		    jsPopup.bDenyClose = true;
		    return;
	    }
		if(this._charge)
			this._charge.prepareForClose();

        this.set_charge(null);
	    jsPopup.bDenyClose = false;
	    window.setTimeout(function(){BXVisualPageEditorDialogManager.getInstance().redirectIfNeed();}, 500);
   },

   exitWithDisclaimingChanges: function()
   {
   		if(this._charge)
			this._charge.prepareForClose();

        this.set_charge(null);

        if(typeof(jsPopup) == "undefined")
            throw "Could not find jsPopup!";
        jsPopup.CloseDialog();
        window.setTimeout(function(){BXVisualPageEditorDialogManager.getInstance().redirectIfNeed();}, 500);
   },

   get_charge: function(){
        return this._charge;
   },

	set_charge: function(obj)
	{
		if(typeof(jsUtils) == "undefined")
			throw "Could not find jsUtils!";

		if(this._charge != null)
		jsUtils.removeCustomEvent('OnBeforeCloseDialog', this._onBeforeCloseDialog);

		this._charge = obj;

		if(this._charge != null)
			jsUtils.addCustomEvent('OnBeforeCloseDialog', this._onBeforeCloseDialog, [], this);
	},

	_ensureChargeIsAssigned: function()
	{
		if(this._charge == null)
			throw "BXVisualPageEditorDialogManager: charge is not assigned!";
	},

	get_redirectAfterExit: function()
	{
		return this._redirectAfterExit;
	},

	set_redirectAfterExit: function(flag)
	{
		this._redirectAfterExit = flag;
	},

	get_redirectionUrl: function()
	{
		return this._redirectionUrl;
	},

	set_redirectionUrl: function(url)
	{
		this._redirectionUrl = url;
	},

	redirectIfNeed: function()
	{
		if(this._redirectAfterExit && this._redirectionUrl && typeof(this._redirectionUrl) == "string")
		{
			if(typeof(window["jsUtils"]) == "undefined")
				throw "Could not find jsUtils!";
			jsUtils.Redirect(arguments, this._redirectionUrl);
		}
	}
}

BXVisualPageEditorDialogManager._instance = null;
BXVisualPageEditorDialogManager.getInstance = function(){
	if(this._instance == null){
        this._instance = new BXVisualPageEditorDialogManager();
        this._instance.initialize();
	}
    return this._instance;
}

BXVisualPageEditorDialogManager.onEditorLoad = function(){
    var self = BXVisualPageEditorDialogManager.getInstance();
    var charge = window.document.getElementById(self._chargeID).pMainObj;
    self.set_charge(charge);
    self._charge.AddEventHandler("OnFullscreen", jsPopup.StretchDialogContentOnFullScreen, jsPopup);

    jsPopup.SetAllButtonsDisabled(false);
}