/*
 * FCKeditor - The text editor for Internet - http://www.fckeditor.net
 * Copyright (C) 2003-2008 Frederico Caldeira Knabben
 *
 * == BEGIN LICENSE ==
 *
 * Licensed under the terms of any of the following licenses at your
 * choice:
 *
 *  - GNU General Public License Version 2 or later (the "GPL")
 *    http://www.gnu.org/licenses/gpl.html
 *
 *  - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
 *    http://www.gnu.org/licenses/lgpl.html
 *
 *  - Mozilla Public License Version 1.1 or later (the "MPL")
 *    http://www.mozilla.org/MPL/MPL-1.1.html
 *
 * == END LICENSE ==
 *
 * Scripts related to the Link dialog window (see fck_link.html).
 */

var dialog	= window.parent ;
var oEditor = dialog.InnerDialogLoaded() ;

var FCK			= oEditor.FCK ;
var FCKLang		= oEditor.FCKLang ;
var FCKConfig	= oEditor.FCKConfig ;
var FCKRegexLib	= oEditor.FCKRegexLib ;
var FCKTools	= oEditor.FCKTools ;
var CurrentTPLAnchors = false;
var anchor_ = '';
var ServerPath = '';
var	links_path = new Array();
var first_real_url = '';
//#### Dialog Tabs
// Set the dialog tabs.
/*dialog.AddTab( 'Info', FCKLang.DlgLnkInfoTab ) ;

if ( !FCKConfig.LinkDlgHideTarget )
	dialog.AddTab( 'Target', FCKLang.DlgLnkTargetTab, ) ;

if ( FCKConfig.LinkUpload )
	dialog.AddTab( 'Upload', FCKLang.DlgLnkUpload, ) ;

if ( !FCKConfig.LinkDlgHideAdvanced )
	dialog.AddTab( 'Advanced', FCKLang.DlgAdvancedTag, false ) ;
*/
// Function called when a dialog tag is selected.
function OnDialogTabChange( tabCode )
{
	if (tabCode == 'Info') {
		updateDataArray();
		window.location.href = '../editor/plugins/MyImage/fck_image.html?from';
	}

	dialog.SetAutoSize( true ) ;
}



function updateDataArray()
{

		if (!window.parent.parentData) {
			window.parent.parentData = new Array();
		}
		window.parent.parentData['linkTxtUrl'] = BuildUrlByType();
		if (window.parent.parentData['linkTxtUrl'].length > 2) {
			if (GetE('txtAlt')) {
				window.parent.parentData['linkTxtAlt'] = GetE('txtAlt').value;
				window.parent.parentData['linkTxtTitle'] = GetE('txtAlt').value;
			}
			window.parent.parentData['linkCmbTarget'] = GetE('cmbTarget').value;
			window.parent.parentData['linkType'] =  GetE('cmbLinkType').value;
			window.location.href='dialog/fck_image.html?from';
		}
}


//#### Regular Expressions library.
var oRegex = new Object() ;

oRegex.UriProtocol = /^(((http|https|ftp|news):\/\/)|mailto:)/gi ;

oRegex.UrlOnChangeProtocol = /^(http|https|ftp|news):\/\/(?=.)/gi ;

oRegex.UrlOnChangeTestOther = /^((javascript:)|[#\/\.])/gi ;

oRegex.ReserveTarget = /^_(blank|self|top|parent)$/i ;

oRegex.PopupUri = /^javascript:void\(\s*window.open\(\s*'([^']+)'\s*,\s*(?:'([^']*)'|null)\s*,\s*'([^']*)'\s*\)\s*\)\s*$/ ;

// Accessible popups
oRegex.OnClickPopup = /^\s*on[cC]lick="\s*FCKOpenPopUp\(\s*this\s*,\s*event\s*,\s*[0-9]+\s*,\s*[0-9]+\s*\);"$/ ;
//oRegex.OnClickPopup = /^\s*on[cC]lick="\s*window.open\(\s*this\.href\s*,\s*(?:'([^']*)'|null)\s*,\s*'([^']*)'\s*\)\s*;\s*return\s*false;*\s*"$/ ;
//oRegex.PopupFeatures = /(?:^|,)([^=]+)=(\d+|yes|no)/gi ;
oRegex.PopupFeatures = /,[0-9]+,/gi ;

//#### Parser Functions

var oParser = new Object() ;

oParser.ParseEMailUrl = function( emailUrl )
{
	// Initializes the EMailInfo object.
	var oEMailInfo = new Object() ;
	oEMailInfo.Address	= '' ;
	oEMailInfo.Subject	= '' ;
	oEMailInfo.Body		= '' ;

	var oParts = emailUrl.match( /^([^\?]+)\??(.+)?/ ) ;
	if ( oParts )
	{
		// Set the e-mail address.
		oEMailInfo.Address = oParts[1] ;

		// Look for the optional e-mail parameters.
		if ( oParts[2] )
		{
			var oMatch = oParts[2].match( /(^|&)subject=([^&]+)/i ) ;
			if ( oMatch ) oEMailInfo.Subject = decodeURIComponent( oMatch[2] ) ;

			oMatch = oParts[2].match( /(^|&)body=([^&]+)/i ) ;
			if ( oMatch ) oEMailInfo.Body = decodeURIComponent( oMatch[2] ) ;
		}
	}

	return oEMailInfo ;
}

oParser.CreateEMailUri = function( address, subject, body )
{
	var sBaseUri = 'mailto:' + address ;

	var sParams = '' ;

	if ( subject.length > 0 )
		sParams = '?subject=' + encodeURIComponent( subject ) ;

	if ( body.length > 0 )
	{
		sParams += ( sParams.length == 0 ? '?' : '&' ) ;
		sParams += 'body=' + encodeURIComponent( body ) ;
	}

	return sBaseUri + sParams ;
}

//#### Initialization Code

// oLink: The actual selected link in the editor.
var oLink = dialog.Selection.GetSelection().MoveToAncestorNode( 'A' ) ;
if ( oLink )
	FCK.Selection.SelectNode( oLink ) ;

window.onload = function()
{
	// Translate the dialog box texts.
	oEditor.FCKLanguageManager.TranslatePage(document) ;

	// Fill the Anchor Names and Ids combos.
	//

	// Load the selected link information (if any).
	LoadSelection() ;
	//LoadAnchorNamesAndIds(1,first_real_url);

	// Update the dialog box.
	//SetLinkType( GetE('cmbLinkType').value ) ;

	// Show/Hide the "Browse Server" button.
	//GetE('divBrowseServer').style.display = FCKConfig.LinkBrowser ? '' : 'none' ;

	// Show the initial dialog content.
	GetE('divInfo').style.display = '' ;

	// Set the actual uploader URL.
/*	if ( FCKConfig.LinkUpload )
		GetE('frmUpload').action = FCKConfig.LinkUploadURL ;
*/
	// Set the default target (from configuration).
	SetDefaultTarget() ;

	// Activate the "OK" button.
	dialog.SetOkButton( true ) ;

	// Select the first field.
	switch( GetE('cmbLinkType').value )
	{
		case 'external' :
		case 'url' :
			SelectField( 'txtUrl' ) ;
			break ;
		case 'Doc' :
			SelectField( 'fileUrl' ) ;
			break ;
		case 'email' :
			SelectField( 'txtEMailAddress' ) ;
			break ;
		case 'anchor' :
			if ( GetE('divSelAnchor').style.display != 'none' )
				SelectField( 'cmbAnchorName' ) ;
			else
				SelectField( 'cmbLinkType' ) ;
	}
	dialog.SetAutoSize( true );
}

function MyPause()
{
	return;
}

var bHasAnchors ;

function UpdateAnchorNamesAndIds(load_url)
{
		new_url = window.frames["frmInternal"].document.location.href;
		if (new_url.match(/fckblank.html/)) {
			return;
		}
		var count_real_anchors = 0;
		var aAnchors = window.frames["frmInternal"].document.anchors ;
		if (aAnchors) {
			for ( var i = 0 ; i < aAnchors.length ; i++ )
			{
				var sName = aAnchors[i].name ;
				if ( sName && sName.length > 0 ) {
					count_real_anchors++;
					var AddAnchor = true;
					for ( var j = GetE('cmbAnchorName').options.length - 1 ; j >= 0 ; j-- )
					{
						count_real_anchors++;
						//alert(GetE('cmbAnchorName').options[j].value + ' == ' + aAnchors[i].name);
						if (GetE('cmbAnchorName').options[j].value == aAnchors[i].name)
						{
							AddAnchor = false;
						}
					}
					if (AddAnchor) {
						FCKTools.AddSelectOption( GetE('cmbAnchorName'), sName, sName ) ;
					}
				}
			}
		}
		if (count_real_anchors > 0)
		{
			bHasAnchors = true;
			for ( var i = 0 ; i < GetE('cmbAnchorName').length ; i++ )
			{
				if (anchor_ == GetE('cmbAnchorName').options[i].value)
					GetE('cmbAnchorName').options[i].selected=1;
			}



		} else {
			bHasAnchors = false ;
		}
		ShowE( 'divSelAnchor'	, bHasAnchors ) ;
		ShowE( 'divNoAnchor'	, !bHasAnchors ) ;

}

function LoadAnchorNamesAndIds(local,load_url)
{
	//alert('LoadAnchorNamesAndIds ' + local + ' load_url' + load_url);
	if (GetE('cmbAnchorName').options.length > 0) {
		GetE('cmbAnchorName').options.length = 0;
	}
	var count_real_anchors = 0;
//	return ;
	// Since version 2.0, the anchors are replaced in the DOM by IMGs so the user see the icon
	// to edit them. So, we must look for that images now.
	if (local) {
		var aAnchors = new Array() ;
		var i ;
		var oImages = oEditor.FCK.EditorDocument.getElementsByTagName( 'IMG' ) ;
		for( i = 0 ; i < oImages.length ; i++ )
		{
			if ( oImages[i].getAttribute('_fckanchor') )
				aAnchors[ aAnchors.length ] = oEditor.FCK.GetRealElement( oImages[i] ) ;
		}

		// Add also real anchors
		var oLinks = oEditor.FCK.EditorDocument.getElementsByTagName( 'A' ) ;
		for( i = 0 ; i < oLinks.length ; i++ )
		{
			if ( oLinks[i].name && ( oLinks[i].name.length > 0 ) )
				aAnchors[ aAnchors.length ] = oLinks[i] ;
		}

	//	var aIds = FCKTools.GetAllChildrenIds( oEditor.FCK.EditorDocument.body ) ;

		bHasAnchors = ( aAnchors.length > 0) ;
		if (bHasAnchors) {
			FCKTools.AddSelectOption( GetE('cmbAnchorName'), '', '' ) ;
			for ( i = 0 ; i < aAnchors.length ; i++ )
			{
				count_real_anchors++;
				var sName = aAnchors[i].name ;
				if ( sName && sName.length > 0 ) {
					FCKTools.AddSelectOption( GetE('cmbAnchorName'), sName, sName ) ;
				}
			}
		}
	}
	if (load_url) {
		window.frames["frmInternal"].document.location.href = ServerPath + load_url + GetAdmin();
	}


	if (count_real_anchors > 0) {
		bHasAnchors = true;
		for ( var i = 0 ; i < GetE('cmbAnchorName').length ; i++ )
		{
			if (anchor_ == GetE('cmbAnchorName').options[i].value)
				GetE('cmbAnchorName').options[i].selected=1;
		}

	} else {
		bHasAnchors = false ;
	}
	ShowE( 'divSelAnchor'	, bHasAnchors ) ;
	ShowE( 'divNoAnchor'	, !bHasAnchors ) ;
}

function LoadSelection()
{
	if ( !oLink ) {
		SetLinkType('internal');

		return ;
	}

	var sType = 'url' ;
	var oPopupMatch = '';
	// Get the actual Link href.
	var sHRef = oLink.getAttribute( '_fcksavedurl' ) ;
	if ( sHRef == null )
		sHRef = oLink.getAttribute( 'href' , 2 ) || '' ;

	// Look for a popup javascript link.
	var onclick = oLink.getAttribute( 'onclick_fckprotectedatt' ) ;
	if ( onclick )
	{
		// Decode the protected string
		onclick = decodeURIComponent( onclick ) ;
		oPopupMatch = oRegex.OnClickPopup.exec( onclick ) ;
		var popup_data = oPopupMatch.toString();
		if( oPopupMatch )
		{
			var aPopUp = new Array();
			var aPopUp = popup_data.split(",");
			var width = aPopUp[2];
			var exp = '\);\"$'
			var height = aPopUp[3].replace( /\);\"$/ , '' );
			GetE('txtPopupWidth').value = width;
			GetE('txtPopupHeight').value = height;
			GetE( 'cmbTarget' ).value = 'popup' ;
//			FillPopupFields( oPopupMatch[1], oPopupMatch[2] ) ;
			SetTarget( 'popup' ) ;
		}
	}

	// Search for the protocol.
	var sProtocol = oRegex.UriProtocol.exec( sHRef ) ;

	if ( sProtocol )
	{
		sProtocol = sProtocol[0].toLowerCase() ;
		GetE('cmbLinkProtocol').value = sProtocol ;

		// Remove the protocol and get the remaining URL.
		var sUrl = sHRef.replace( oRegex.UriProtocol, '' ) ;

		if ( sProtocol == 'mailto:' )	// It is an e-mail link.
		{
			sType = 'email' ;

			var oEMailInfo = oParser.ParseEMailUrl( sUrl ) ;
			GetE('txtEMailAddress').value	= oEMailInfo.Address ;
			GetE('txtEMailSubject').value	= oEMailInfo.Subject ;
			GetE('txtEMailBody').value		= oEMailInfo.Body ;
		}
		else				// It is a normal link.
		{
			sType = 'url' ;
			GetE('txtUrl').value = sUrl ;
		}
	}
	else					// It is another type of link.
	{
		sType = 'url' ;

		GetE('cmbLinkProtocol').value = '' ;
		GetE('txtUrl').value = sHRef ;
	}
	if (sType != 'email') {
		if (sHRef.match(/@@[0-9]+@@/)) {
			sType = 'internal' ;
		} else {

			var oldsType = GetAttribute( oLink, 'label', '' );

			id = oLink.getAttribute( 'id' , 2 );
			if (!id && !oldsType) {
				sType = 'external';
			} else if (id.match(/Doc_|_[0-9]+/)) {
				sType = 'Doc';
				GetE('fileUrl').value = GetE('txtUrl').value;
			} else {
				sType = 'external';
			}
		}
	}
	if ( !oPopupMatch )
	{
		// Get the target.
		var sTarget = oLink.target ;

		if ( sTarget && sTarget.length > 0 )
		{
			if ( oRegex.ReserveTarget.test( sTarget ) )
			{
				sTarget = sTarget.toLowerCase() ;
				GetE('cmbTarget').value = sTarget ;
			}
			else
				GetE('cmbTarget').value = 'frame' ;
			GetE('txtTargetFrame').value = sTarget ;
		}
	}

	// Get Advances Attributes
	if (oLink.getAttribute('alt',2)) {
		if(oLink.getAttribute('alt',2).length > 0)
			GetE('txtAlt').value = oLink.getAttribute('alt',2) + '' ;
		else
			GetE('txtAlt').value = '';
	}

	GetE('txtAttId').value			= oLink.id ;
//	GetE('txtAlt').value			= oLink.alt ;
//	GetE('txtAttName').value		= oLink.name ;
//	GetE('cmbAttLangDir').value		= oLink.dir ;
//	GetE('txtAttLangCode').value	= oLink.lang ;
//	GetE('txtAttAccessKey').value	= oLink.accessKey ;
//	GetE('txtAttTabIndex').value	= oLink.tabIndex <= 0 ? '' : oLink.tabIndex ;
//	GetE('txtAttTitle').value		= oLink.title ;
//	GetE('txtAttContentType').value	= oLink.type ;
//	GetE('txtAttCharSet').value		= oLink.charset ;

/*	var sClass ;
	if ( oEditor.FCKBrowserInfo.IsIE )
	{
		sClass	= oLink.getAttribute('className',2) || '' ;
		// Clean up temporary classes for internal use:
		sClass = sClass.replace( FCKRegexLib.FCK_Class, '' ) ;

		GetE('txtAttStyle').value	= oLink.style.cssText ;
	}
	else
	{
		sClass	= oLink.getAttribute('class',2) || '' ;
		GetE('txtAttStyle').value	= oLink.getAttribute('style',2) || '' ;
	}
	GetE('txtAttClasses').value	= sClass ;
*/
	// Update the Link type combo.
	if (sType == 'internal' && sHRef.length > 2 && sHRef.indexOf('#') > 0) {
		anchor_ = sHRef.slice(sHRef.lastIndexOf('#')+1);
		sHRef = sHRef.slice(0,sHRef.lastIndexOf('#'));
		GetE('txtUrl').value = sHRef ;
	}

	GetE('cmbLinkType').value = sType ;
	SetLinkType( sType )
}

//#### Link type selection.
function SetLinkType( linkType )
{
/*
	ShowE('divLinkTypeUrl'		, (linkType == 'url') ) ;
	ShowE('divLinkTypeAnchor'	, (linkType == 'anchor') ) ;
	ShowE('divLinkTypeEMail'	, (linkType == 'email') ) ;
*/
	if (!linkType) {
		linkType = 'internal';

	}
	ShowE('divLinkTypeInternal'	, (linkType == 'internal') ) ;
	ShowE('divLinkTypeExternal'	, (linkType == 'external') ) ;
	ShowE('divLinkTypeEMail'	, (linkType == 'email') ) ;
	ShowE('divLinkTypeFile' 	, (linkType == 'Doc') ) ;



	if (linkType == 'email') {
		ShowE('divNoMail1',0);
		ShowE('divNoMail2',0);
		ShowE('divNoMail3',0);
	} else {
		ShowE('divNoMail1',1);
		ShowE('divNoMail2',1);
		ShowE('divNoMail3',1);
	}
	if (linkType != 'internal') {
		ShowE( 'divNoAnchor', 0 ) ;
	}


	if(GetE('cmbTarget'))
	{
		if (GetE('cmbTarget').value == 'popup' ) {
			ShowE('divPopupSize',1);
		} else
		ShowE('divPopupSize',0);
	} else
		ShowE('divPopupSize',0);

	if ( linkType == 'internal' ) {
		LoadResources();

	}
	if ( linkType == 'email')
		window.parent.SetAutoSize( true ) ;

	dialog.SetAutoSize();

}



 function LoadResources() {
	var oXML = new FCKXml() ;
	var sConnUrl = window.location.href.replace( /core.*$/, 'admin/index.php?env=-dummy:fck--OnLoadCmsTree---&admin=1' );
	//alert(sConnUrl)
	oXML.LoadUrl(sConnUrl, GetCmsTreeCallBack ) ;	// Asynchronous load.
 }

function show_props(obj, objName) {
		var result = "";
		for (var i in obj) {
		  alert( objName + "." + i + " = " + obj[i] + " \n" );
		}
	}

 function GetCmsTreeCallBack( fckXml )
{
	//alert(fckXml);
	var oNodes = fckXml.SelectNodes( 'CmsPages/CmsPage' ) ;
	//alert(show_props(oNodes[0], 'oNodes'));
	//var links_path = new Array();
	GetE('cmbImternalPagName').options[0] = new Option('', '');
	for ( var j = 0 ; j < oNodes.length ; j++ )
	{
		var i = j + 1;
		var sCmsPage = oNodes[j].attributes.getNamedItem('path').value ;
		var sCmsId = oNodes[j].attributes.getNamedItem('st_id').value ;

		var real_url = false;
		if (sCmsPage == '@@'+sCmsId+'@@') {
			real_url = oNodes[j].attributes.getNamedItem('real_url').value ;
			links_path[i] = real_url;
		}

		var sTitle = oNodes[j].attributes.getNamedItem('title').value ;
		ServerPath = oNodes[j].attributes.getNamedItem('serverpath').value;
		GetE('cmbImternalPagName').options[i] = new Option(sTitle, sCmsPage);
		if (GetE('txtUrl')) {
			tmpUrl = GetE('txtUrl').value;
			// alert(GetE('txtUrl').value + ' ' + sCmsId + ' == ' + FCKConfig.page_id);
			if (tmpUrl.match(sCmsPage+'$')) {
				GetE('cmbImternalPagName').options[i].selected=1;
				LoadAnchorNamesAndIds(true,real_url);
				//alert(sCmsId + ' == ' + FCKConfig.page_id);
				//if (sCmsId == FCKConfig.page_id) {
					//LoadAnchorNamesAndIds(true,real_url);
				//}
				//alert(tmpUrl+GetAdmin());
				//if (real_url) {
					//window.frames["frmInternal"].document.location.href = real_url;
				//}
				//else {
					//window.frames["frmInternal"].document.location.href = tmpUrl+GetAdmin();
				//}
			}
		}
	}
}

function GetAdmin()
{
	return '&admin=1';
}


function ChangeInternalUrl(url,obj)
{
	if(url.match(/@@[0-9]+@@/) ) {
		for (var i=0; i < obj.options.length; i++) {
			if (obj.options[i].value == url) {
				myCmsId = url.replace( /@@/gi,'');
				//alert(myCmsId+' MYCMSID');
				load_url = links_path[i] + GetAdmin();
				if (myCmsId == FCKConfig.page_id) {
					LoadAnchorNamesAndIds(1,load_url);
				} else {
					window.frames["frmInternal"].document.location.href = links_path[i] + GetAdmin();
				}
				return;
			}
		}
	} else {
		window.frames["frmInternal"].document.location.href = url + GetAdmin();
	}
}




//#### Target type selection.
function SetTarget( targetType )
{
	//GetE('tdTargetFrame').style.display	= ( targetType == 'popup' ? 'none' : '' ) ;
	//GetE('tdPopupName').style.display	=
	//GetE('tablePopupFeatures').style.display = ( targetType == 'popup' ? '' : 'none' ) ;

	switch ( targetType )
	{
		case "_blank" :
		case "_self" :
		case "_parent" :
		case "_top" :
			GetE('txtTargetFrame').value = targetType ;
			break ;
		case "" :
			GetE('txtTargetFrame').value = '' ;
			break ;
	}

	if ( targetType == 'popup' ) {
		ShowE('divPopupSize',1);
		if (!GetE('txtPopupWidth').value)
			GetE('txtPopupWidth').value = 800;
		if (!GetE('txtPopupHeight').value)
			GetE('txtPopupHeight').value = 600;
		dialog.SetAutoSize( true ) ;
	} else {
		ShowE('divPopupSize',0);
	}
}

//#### Called while the user types the URL.
function OnUrlChange()
{
	var sUrl = GetE('txtUrl').value ;
	var sProtocol = oRegex.UrlOnChangeProtocol.exec( sUrl ) ;

	if ( sProtocol )
	{
		sUrl = sUrl.substr( sProtocol[0].length ) ;
		GetE('txtUrl').value = sUrl ;
		GetE('cmbLinkProtocol').value = sProtocol[0].toLowerCase() ;
	}
	else if ( oRegex.UrlOnChangeTestOther.test( sUrl ) )
	{
		GetE('cmbLinkProtocol').value = '' ;
	}
}

//#### Called while the user types the target name.
function OnTargetNameChange()
{
	//var sFrame = GetE('txtTargetFrame').value ;

	//if ( sFrame.length == 0 )
	//	GetE('cmbTarget').value = '' ;
	//else if ( oRegex.ReserveTarget.test( sFrame ) )
	//	GetE('cmbTarget').value = sFrame.toLowerCase() ;
	//else
	//	GetE('cmbTarget').value = 'frame' ;
	if(GetE('cmbTarget')) {
		if (GetE('cmbTarget').value == 'popup' ) {
			ShowE('divPopupSize',1);
		} else
		ShowE('divPopupSize',0);
	} else
		ShowE('divPopupSize',0);
}

// Accessible popups
function BuildOnClickPopup()
{
	var onclick = 'FCKOpenPopUp(this,event,'+ GetE('txtPopupWidth').value +','+ GetE('txtPopupHeight').value +');';
	return onclick;
}

//#### Fills all Popup related fields.
function FillPopupFields( windowName, features )
{
	alert(features+' FEATURES');
	if ( windowName )
		GetE('txtPopupName').value = windowName ;

	var oFeatures = new Object() ;
	var oFeaturesMatch ;
	while( ( oFeaturesMatch = oRegex.PopupFeatures.exec( features ) ) != null )
	{
		var sValue = oFeaturesMatch[2] ;

		if ( sValue == ( 'yes' || '1' ) )
			oFeatures[ oFeaturesMatch[1] ] = true ;
		else if ( ! isNaN( sValue ) && sValue != 0 )
			oFeatures[ oFeaturesMatch[1] ] = sValue ;
	}

	// Update all features check boxes.
	var aChkFeatures = document.getElementsByName('chkFeature') ;
	for ( var i = 0 ; i < aChkFeatures.length ; i++ )
	{
		if ( oFeatures[ aChkFeatures[i].value ] )
			aChkFeatures[i].checked = true ;
	}

	// Update position and size text boxes.
	if ( oFeatures['width'] )	GetE('txtPopupWidth').value		= oFeatures['width'] ;
	if ( oFeatures['height'] )	GetE('txtPopupHeight').value	= oFeatures['height'] ;
	if ( oFeatures['left'] )	GetE('txtPopupLeft').value		= oFeatures['left'] ;
	if ( oFeatures['top'] )		GetE('txtPopupTop').value		= oFeatures['top'] ;
}

function BuildUrlByType()
{
		switch ( GetE('cmbLinkType').value )
	{

		case 'internal' :
			sUri = GetE('cmbImternalPagName').value;
			//sUri = GetE('cmbLinkProtocol').value + sUri ;
			//alert(sUri);
			//var cmbAnchorName = GetE('cmbAnchorName').value
			//if (cmbAnchorName.length > 0)
			//	sUri = sUri+'#'+cmbAnchorName

			//if( GetE('cmbTarget').value == 'popup' )
			//	sUri = BuildPopupUri( sUri ) ;
			var cmbAnchorName = GetE('cmbAnchorName').value
			if (cmbAnchorName.length > 0)
				sUri = sUri+'#'+cmbAnchorName
			break ;

		case 'external' :
		case 'url' :

			sUri = GetE('txtUrl').value ;

			if ( sUri.length == 0 )
			{
				alert( FCKLang.DlnLnkMsgNoUrl ) ;
				return false ;
			}

			sUri = GetE('cmbLinkProtocol').value + sUri;

			break ;
		case 'Doc' :
			sUri = GetE('fileUrl').value ;
			GetE('txtUrl').value = GetE('fileUrl').value ;
			if ( sUri.length == 0 )
			{
				alert( FCKLang.DlnLnkMsgNoUrl ) ;
				return false ;
			}

			sUri = GetE('cmbLinkProtocol').value + sUri ;
		break;


		case 'email' :
			sUri = GetE('txtEMailAddress').value ;

			if ( sUri.length == 0 )
			{
				alert( FCKLang.DlnLnkMsgNoEMail ) ;
				return false ;
			}

			sUri = oParser.CreateEMailUri(
				sUri,
				GetE('txtEMailSubject').value,
				GetE('txtEMailBody').value ) ;
			break ;

		case 'anchor' :
			var sAnchor = GetE('cmbAnchorName').value ;
			if ( sAnchor.length == 0 ) sAnchor = GetE('cmbAnchorId').value ;

			if ( sAnchor.length == 0 )
			{
				alert( FCKLang.DlnLnkMsgNoAnchor ) ;
				return false ;
			}

			sUri = '#' + sAnchor ;
			break ;
	}

	// If no link is selected, create a new one (it may result in more than one link creation - #220).
	var aLinks = oLink ? [ oLink ] : oEditor.FCK.CreateLink( sUri, true ) ;

	// If no selection, no links are created, so use the uri as the link text (by dom, 2006-05-26)
	var aHasSelection = ( aLinks.length > 0 ) ;
	if ( !aHasSelection )
	{
		sInnerHtml = sUri;

		// Built a better text for empty links.
		switch ( GetE('cmbLinkType').value )
		{
			// url: try to get path
			case 'internal' :
			case 'external' :
			case 'url':
				var oLinkPathRegEx = new RegExp("//?([^?\"']+)([?].*)?$") ;
				var asLinkPath = oLinkPathRegEx.exec( sUri ) ;
				if (asLinkPath != null)
					sInnerHtml = asLinkPath[1];  // use matched path
				break ;

			// mailto: try to get email address
			case 'email':
				sInnerHtml = GetE('txtEMailAddress').value ;
				break ;
		}

		// Create a new (empty) anchor.
		aLinks = [ oEditor.FCK.InsertElement( 'a' ) ] ;
	}

	for ( var i = 0 ; i < aLinks.length ; i++ )
	{
		oLink = aLinks[i] ;

		if ( aHasSelection )
			sInnerHtml = oLink.innerHTML ;		// Save the innerHTML (IE changes it if it is like an URL).

		oLink.href = sUri ;
		SetAttribute( oLink, '_fcksavedurl', sUri ) ;

		var onclick;
		// Accessible popups
		if( GetE('cmbTarget').value == 'popup' )
		{
			onclick = BuildOnClickPopup() ;
			// Encode the attribute
			onclick = encodeURIComponent( " onclick=\"" + onclick + "\"" )  ;
			SetAttribute( oLink, 'onclick_fckprotectedatt', onclick ) ;
		}
		else
		{
			// Check if the previous onclick was for a popup:
			// In that case remove the onclick handler.
			onclick = oLink.getAttribute( 'onclick_fckprotectedatt' ) ;
			if ( onclick )
			{
				// Decode the protected string
				onclick = decodeURIComponent( onclick ) ;

				if( oRegex.OnClickPopup.test( onclick ) )
					SetAttribute( oLink, 'onclick_fckprotectedatt', '' ) ;
			}
		}

		oLink.innerHTML = sInnerHtml ;		// Set (or restore) the innerHTML

		// Target
		if( GetE('cmbTarget').value != 'popup' )
			SetAttribute( oLink, 'target', GetE('txtTargetFrame').value ) ;
		else
			SetAttribute( oLink, 'target', null ) ;

		// Advances Attributes
		if (GetE('txtAlt')) {
			SetAttribute( oLink, 'alt', GetE('txtAlt').value) ;
			SetAttribute( oLink, 'title', GetE('txtAlt').value) ;
		}
		if ( i == 0 && GetE('cmbLinkType').value == 'Doc') {
			if (GetE('txtAttId').value == '') {
				GetE('txtAttId').value = 'Doc_|_' + Math.round((99977562 - 10016486) * Math.random());
			}
			SetAttribute( oLink, 'id',  GetE('txtAttId').value) ;
		}
	}
	// Select the (first) link.
	oEditor.FCKSelection.SelectNode( aLinks[0] );

	return true ;

}


//#### The OK button was hit.
function Ok()
{
	var sUri, sInnerHtml ;
	oEditor.FCKUndo.SaveUndoStep() ;


	if (window.location.search.substr(1) == 'from') {
		// updateDataArray();
		//	window.location.href = '../editor/plugins/MyImage/fck_image.html?create';
		// return ;
	}

	return BuildUrlByType();
}

function BrowseServer()
{
	OpenFileBrowser( FCKConfig.DocumentsBrowserURL, FCKConfig.DocumentsBrowserWindowWidth, FCKConfig.DocumentsBrowserWindowHeight ) ;
}

function SetUrl( url )
{
	GetE('fileUrl').value = url ;
	GetE('txtUrl').value = url ;
	OnUrlChange() ;
	//dialog.SetSelectedTab( 'Info' ) ;
}

function OnUploadCompleted( errorNumber, fileUrl, fileName, customMsg )
{
	// Remove animation
	window.parent.Throbber.Hide() ;
	GetE( 'divUpload' ).style.display  = '' ;

	switch ( errorNumber )
	{
		case 0 :	// No errors
			alert( 'Your file has been successfully uploaded' ) ;
			break ;
		case 1 :	// Custom error
			alert( customMsg ) ;
			return ;
		case 101 :	// Custom warning
			alert( customMsg ) ;
			break ;
		case 201 :
			alert( 'A file with the same name is already available. The uploaded file has been renamed to "' + fileName + '"' ) ;
			break ;
		case 202 :
			alert( 'Invalid file type' ) ;
			return ;
		case 203 :
			alert( "Security error. You probably don't have enough permissions to upload. Please check your server." ) ;
			return ;
		case 500 :
			alert( 'The connector is disabled' ) ;
			break ;
		default :
			alert( 'Error on file upload. Error number: ' + errorNumber ) ;
			return ;
	}

	SetUrl( fileUrl ) ;
	//GetE('frmUpload').reset() ;
}

var oUploadAllowedExtRegex	= new RegExp( FCKConfig.LinkUploadAllowedExtensions, 'i' ) ;
var oUploadDeniedExtRegex	= new RegExp( FCKConfig.LinkUploadDeniedExtensions, 'i' ) ;

function CheckUpload()
{
	var sFile = GetE('txtUploadFile').value ;

	if ( sFile.length == 0 )
	{
		alert( 'Please select a file to upload' ) ;
		return false ;
	}

	if ( ( FCKConfig.LinkUploadAllowedExtensions.length > 0 && !oUploadAllowedExtRegex.test( sFile ) ) ||
		( FCKConfig.LinkUploadDeniedExtensions.length > 0 && oUploadDeniedExtRegex.test( sFile ) ) )
	{
		OnUploadCompleted( 202 ) ;
		return false ;
	}

	// Show animation
	window.parent.Throbber.Show( 100 ) ;
	GetE( 'divUpload' ).style.display  = 'none' ;

	return true ;
}

function SetDefaultTarget()
{
	var target = FCKConfig.DefaultLinkTarget || '' ;

	if ( oLink || target.length == 0 )
		return ;

	switch ( target )
	{
		case '_blank' :
		case '_self' :
		case '_parent' :
		case '_top' :
			GetE('cmbTarget').value = target ;
			break ;
		default :
			GetE('cmbTarget').value = 'frame' ;
			break ;
	}

	GetE('txtTargetFrame').value = target ;
}
