//********************************
//** Load the language file | 加载语言文件
//********************************
tinyMCEPopup.requireLangPack();

//********************************
//** The actions in plugin dialogue   |    该插件对话框中的行为
//********************************
var BGImageDialog = {

	//--------------------------------
	//-- Initialization (what happen when this plugin button clicked)   |   初始化 （该插件按钮被按下之后）
	//--------------------------------
	init : function() 
	{	
		//--------------------------------
		//-- The form object on current dialogue window    |    当前对话框上的 form 对象
		//--------------------------------
		var oForm = document.forms[0];	
	
		//--------------------------------
		//-- get all parent nodes passed by windows argument  |   获取传递来的，当前选中 Node 的全部父 Node
		//--------------------------------
		var parentNodes = tinyMCEPopup.getWindowArg('parent_nodes');
		
		if (parentNodes != undefined && parentNodes != null)
		{
			for (var i=0; i<=parentNodes.length-1; i++)
			{
				var targetOption=document.createElement("option");
				targetOption.value=parentNodes[i].tagName.toLowerCase();
				targetOption.text=parentNodes[i].tagName.toLowerCase();
				
				try
				{
					//--------------------------------
					//-- For IE earlier than version 8
					//--------------------------------
					oForm.bgimage_background_target.add(targetOption,oForm.bgimage_background_target.options[null]);
				}
				catch (e)
				{
					//--------------------------------
					//-- For others
					//--------------------------------
					oForm.bgimage_background_target.add(targetOption,null);
				}  
			}
		}
		
		//--------------------------------
		//-- Style entry initialization on dialog window for the selected node  |  在对话框窗口上初始化选中的节点的 style entry
		//--------------------------------
		StyleEntryPopulate();

		//--------------------------------
		//-- Show style effect in preview  |  在 preview 那里显示效果
		//--------------------------------
		BackgroundStylePreview();
	},

	insert : function() 
	{
		//--------------------------------
		//-- Collect background style and insert (or replace) to current selected node  |   收集 background style 并插入（或替换给）当前选中节点
		//--------------------------------
		StyleEntryInsert();
		
		//--------------------------------
		//-- Close popup window   |   结束
		//--------------------------------
		tinyMCEPopup.close();
	}
};

//********************************
//** Initialization  |  初始化
//********************************
tinyMCEPopup.onInit.add(BGImageDialog.init, BGImageDialog);

//********************************
//** Style entry initialization on dialog window for the selected node  |  在对话框窗口上初始化选中的节点的 style entry
//********************************
function StyleEntryPopulate()
{	
	//--------------------------------
	//-- The form object on current dialogue window    |    当前对话框上的 form 对象
	//--------------------------------
	var oForm = document.forms[0];	

	//--------------------------------
	//-- get all parent nodes passed by windows argument  |   获取传递来的，当前选中 Node 的全部父 Node
	//--------------------------------
	var parentNodes = tinyMCEPopup.getWindowArg('parent_nodes');

	//--------------------------------
	//-- current selected node & style |   当前选中的 Node 及其 style
	//--------------------------------
	var currentNode = parentNodes[oForm.bgimage_background_target.selectedIndex];	
	
	var currentNodeBackgroundColor = '';
	var currentNodeBackgroundImage = '';
	var currentNodeBackgroundRepeat = '';
	var currentNodeBackgroundAttachment = '';
	var currentNodeBackgroundPosition = '';
	
	if (GetStyle(currentNode,'background-color') != undefined)
	{
		currentNodeBackgroundColor = Trim(BackgroundColorConvert(GetStyle(currentNode,'background-color')));
	}
	
	if (GetStyle(currentNode,'background-image') != undefined)
	{
		currentNodeBackgroundImage = Trim(GetStyle(currentNode,'background-image'));
	}
	
	if (GetStyle(currentNode,'background-repeat') != undefined)
	{
		currentNodeBackgroundRepeat = Trim(GetStyle(currentNode,'background-repeat'));
	}
	
	if (GetStyle(currentNode,'background-attachment') != undefined)
	{
		currentNodeBackgroundAttachment = Trim(GetStyle(currentNode,'background-attachment'));
	}
	
	if (GetStyle(currentNode,'background-position') != undefined)
	{
		currentNodeBackgroundPosition = Trim(BackgroundPositionConvert(GetStyle(currentNode,'background-position')));
	}
	
	//--------------------------------
	//-- IE doesn't seem to understand backgroundPosition (background-position)  |  IE 似乎不理解 backgroundPosition (background-position)
	//--------------------------------
	if (currentNodeBackgroundPosition == '' || currentNodeBackgroundPosition == undefined)
	{
		currentNodeBackgroundPosition = Trim(BackgroundPositionConvert(GetStyle(currentNode,'background-position-x') + ' ' + GetStyle(currentNode,'background-position-y')));
	}

	//var currentNodeStyle = 'background:' + currentNodeBackgroundColor + ' ' + currentNodeBackgroundImage + ' ' + currentNodeBackgroundRepeat + ' ' + currentNodeBackgroundAttachment + ' ' + currentNodeBackgroundPosition;
	
	//--------------------------------
	//-- Populate style value to each input control   |   将各个 style 的值放入输入控件
	//--------------------------------
	//if(currentNodeStyle != undefined) 
	//{
		//--------------------------------
		//-- Resolve background color, url, position, attached, repeat parameters from current_node_style |   从当前选中节点的 style 属性中解析背景颜色，背景图片 url, 位置，滚动，重复等参数
		//--------------------------------
		/*
		var BackgroundColor=ResolveBackgroundColor(currentNodeStyle);
		var BackgroundImage=ResolveBackgroundImage(currentNodeStyle).replace(/['"]/gi,'');
		var BackgroundRepeat=ResolveBackgroundRepeat(currentNodeStyle);
		var BackgroundAttachment=ResolveBackgroundAttachment(currentNodeStyle);
		var BackgroundHorizontalPosition=ResolveBackgroundHorizontalPosition(currentNodeStyle);
		var BackgroundVerticalPosition=ResolveBackgroundVerticalPosition(currentNodeStyle);
		*/
	
		//--------------------------------
		//-- put resolved color value to form controls   |   将解析出来的 color 值放进 form 中的 control
		//--------------------------------
		document.getElementById("bgimage_background_color").value = currentNodeBackgroundColor;

		//--------------------------------
		//-- put resolved image value to form controls   |   将解析出来的 image 值放进 form 中的 control
		//--------------------------------
		document.getElementById("bgimage_background_image").value=ResolveBackgroundImage(currentNodeBackgroundImage).replace(/['"]/gi,'');
		
		//--------------------------------
		//-- put resolved repeat value to form controls  |   将解析出来的 repeat 值放进 form 中的 control
		//--------------------------------
		var oBackgroundRepeat=document.getElementById("bgimage_background_repeat");
		
		if(oBackgroundRepeat!=undefined) 
		{
			for(var i = 0; i <= oBackgroundRepeat.options.length-1; i++) 
			{
				if(Trim(oBackgroundRepeat.options[i].value.toLowerCase()) == currentNodeBackgroundRepeat.toLowerCase()) 
				{
					oBackgroundRepeat.selectedIndex = i;
					break;
				}
			}
		}

		//--------------------------------
		//-- put resolved vertical position value to form controls  |   将解析出来的垂直位置值放进 form 中的 control
		//--------------------------------
		var oBackgroundAttachment=document.getElementById("bgimage_background_attachment");
		
		if(oBackgroundAttachment!=undefined) 
		{
			for(var i = 0; i <= oBackgroundAttachment.options.length-1; i++) 
			{
				if(Trim(oBackgroundAttachment.options[i].value.toLowerCase()) == currentNodeBackgroundAttachment.toLowerCase()) 
				{
					oBackgroundAttachment.selectedIndex = i;
					break;
				}
			}
		}

		//--------------------------------
		//-- put resolved horizontal position value to form controls  |   将解析出来的水平位置值放进 form 中的 control
		//--------------------------------
		document.getElementById("bgimage_background_horizontal_position").value=ResolveBackgroundHorizontalPosition(currentNodeBackgroundPosition);			

		//--------------------------------
		//-- put resolved vertical position value to form controls  |   将解析出来的垂直位置值放进 form 中的 control
		//--------------------------------
		document.getElementById("bgimage_background_vertical_position").value=ResolveBackgroundVerticalPosition(currentNodeBackgroundPosition);			
	//}
}

//********************************
//** Style entry insert to current selected node  |  将收集的 background style 插入当前选中的节点
//********************************
function StyleEntryInsert()
{	
	//--------------------------------
	//-- The form object on current dialogue window    |    当前对话框上的 form 对象
	//--------------------------------
	var oForm = document.forms[0];

	//--------------------------------
	//-- Get current selected node.  |   获取传递过来的当前选中节点
	//--------------------------------
	var parentNodes = tinyMCEPopup.getWindowArg('parent_nodes');
	var currentNode = parentNodes[oForm.bgimage_background_target.selectedIndex] ;		

	//--------------------------------
	//-- Get the style string of current selected node.  |   获取传递过来的当前选中节点的 style 字符串
	//--------------------------------
	var currentNodeStyle = tinyMCEPopup.editor.dom.getAttrib(currentNode, 'style');
	
	//--------------------------------
	//-- The composed background style    |    将要构造的 background 式样
	//--------------------------------
	var backgroundStyle="";

	//--------------------------------
	//-- Get background color parameter    |    背景颜色
	//--------------------------------
	backgroundStyle += "background:" + Trim(oForm.bgimage_background_color.value);

	//--------------------------------
	//-- Get background image url parameter    |    背景图 url
	//--------------------------------
	backgroundStyle += " url(" + Trim(oForm.bgimage_background_image.value) + ")";
	
	//--------------------------------
	//-- Get background repeat parameter    |    背景图 Repeat 参数
	//--------------------------------
	backgroundStyle += " " + oForm.bgimage_background_repeat.options[oForm.bgimage_background_repeat.selectedIndex].value;

	//--------------------------------
	//-- Get background attachment parameter    |    背景图 Attchment 参数
	//--------------------------------
	backgroundStyle += " " + oForm.bgimage_background_attachment.options[oForm.bgimage_background_attachment.selectedIndex].value;

	//--------------------------------
	//-- Get background horizontal position parameter    |    背景图水平位置参数
	//--------------------------------
	backgroundStyle += " " + Trim(oForm.bgimage_background_horizontal_position.value);

	//--------------------------------
	//-- Get background vertical position parameter    |    背景图垂直位置参数
	//--------------------------------
	backgroundStyle += " " + Trim(oForm.bgimage_background_vertical_position.value);

	//--------------------------------
	//-- rebuild current node style with above generated background style   |    重新构造当前节点的 style （删除所有非 shorthand background style, 用上面生成的 background style 替换旧的 background style）
	//--------------------------------
	currentNodeStyle = RemoveNonShorthandBackgroundColor(currentNodeStyle);
	currentNodeStyle = RemoveNonShorthandBackgroundImage(currentNodeStyle);
	currentNodeStyle = RemoveNonShorthandBackgroundRepeat(currentNodeStyle);
	currentNodeStyle = RemoveNonShorthandBackgroundAttachment(currentNodeStyle);
	currentNodeStyle = RemoveNonShorthandBackgroundPosition(currentNodeStyle);	

	if (Trim(currentNodeStyle).length>0)
	{
		if (/background\:[^;]*/gi.test(currentNodeStyle)==true)
		{
			currentNodeStyle=currentNodeStyle.replace(/background\:[^;]*/gi,backgroundStyle);
		}
		else
		{
			currentNodeStyle = backgroundStyle + ";" + currentNodeStyle;
		}
	}
	else
	{
		currentNodeStyle = backgroundStyle;
	}

	//--------------------------------
	//-- replace old style with new   |    用新构造好的当前节点的 html 源代码替换旧的
	//--------------------------------
	tinyMCEPopup.editor.dom.setAttrib(currentNode, 'style', currentNodeStyle);
}


//****************************************
//** Preview |  修改了 background style entry 实时在 preview 那里预览
//****************************************
function BackgroundStylePreview()
{
	//--------------------------------
	//-- Compose the background style     |    构造 background style 
	//--------------------------------
	var oForm = document.forms[0];
	
	var backgroundStyle="";
	backgroundStyle += "background:" + oForm.bgimage_background_color.value;
	backgroundStyle += " url(" + oForm.bgimage_background_image.value + ")";
	backgroundStyle += " " + oForm.bgimage_background_repeat.options[oForm.bgimage_background_repeat.selectedIndex].value;
	backgroundStyle += " " + oForm.bgimage_background_attachment.options[oForm.bgimage_background_attachment.selectedIndex].value;
	backgroundStyle += " " + oForm.bgimage_background_horizontal_position.value;
	backgroundStyle += " " + oForm.bgimage_background_vertical_position.value;	

	//--------------------------------
	//-- display the style defination string    |    显示 style 定义字符串
	//--------------------------------
	document.getElementById('bgimage_style_value').value = backgroundStyle;			

	//--------------------------------
	//-- Assign to preview object    |    分配给 preview 对象
	//--------------------------------
	tinyMCEPopup.editor.dom.setAttrib(document.getElementById('bgimage_preview_panel'), 'style', backgroundStyle);			
}
		

//********************************
//**Helper (to resolve background css properties)  |  帮助函数 （用来解析 background css  中的属性）
//********************************
/*
function ResolveBackgroundColor(StyleValue)
{	
	var myRegex=/background\:\s*([#a-z0-9]+)\s+/gi;
		
	if (myRegex.test(StyleValue)==true)
	{
		myRegex.exec(StyleValue);
		return RegExp.$1;
	}
	else
	{
		return '';
	}
}
*/

function ResolveBackgroundImage(StyleValue)
{
	//var myRegex=/background\:\s*[#a-z0-9]+\s+url\s*\(([^\)]*)\)\s+/gi;
	var myRegex=/^url\s*\(([^\)]*)\)$/gi;
	
	if (myRegex.test(StyleValue)==true)
	{
		myRegex.exec(StyleValue);
		return RegExp.$1;
	}
	else
	{
		return '';
	}
}

/*
function ResolveBackgroundRepeat(StyleValue)
{
	var myRegex=/background\:[\s\S]*\s+(repeat\-x|repeat\-y|no\-repeat|repeat)+\s+/gi;
	
	if (myRegex.test(StyleValue)==true)
	{
		myRegex.exec(StyleValue);
		return RegExp.$1;
	}
	else
	{
		return '';
	}
}	
*/

/*
function ResolveBackgroundAttachment(StyleValue)
{
	var myRegex=/background\:[\s\S]*\s+(scroll|fixed)+\s+/gi;

	if (myRegex.test(StyleValue)==true)
	{
		myRegex.exec(StyleValue);
		return RegExp.$1;
	}
	else
	{
		return '';
	}
}
*/		

function ResolveBackgroundHorizontalPosition(StyleValue)
{
	//var myRegex=/background\:[\s\S]*\s+(left|right|top|bottom|center|\d+[%incmeptx]+)\s+(left|right|top|bottom|center|\d+[%incmeptx]+)$/gi;
	var myRegex=/^(left|right|top|bottom|center|\d+[%incmeptx]+)\s+(left|right|top|bottom|center|\d+[%incmeptx]+)$/gi;
	
	if (myRegex.test(StyleValue)==true)
	{
		myRegex.exec(StyleValue);
		return RegExp.$1;
	}
	else
	{
		return '';
	}
}

function ResolveBackgroundVerticalPosition(StyleValue)
{
	//var myRegex=/background\:[\s\S]*\s+(left|right|top|bottom|center|\d+[%incmeptx]+)\s+(left|right|top|bottom|center|\d+[%incmeptx]+)$/gi;
	var myRegex=/^(left|right|top|bottom|center|\d+[%incmeptx]+)\s+(left|right|top|bottom|center|\d+[%incmeptx]+)$/gi;
	
	if (myRegex.test(StyleValue)==true)
	{
		myRegex.exec(StyleValue);
		return RegExp.$2;
	}
	else
	{
		return '';
	}
}

//********************************
//** Remove non shorthand background style entries from whole style string    |    从 style 字符串中去掉非  shorthand background style
//********************************
function RemoveNonShorthandBackgroundColor(StyleValue)
{
	var ColorRegex=/background\-color\:[^;]*/gi;
	return StyleValue.replace(ColorRegex,"");
}		

function RemoveNonShorthandBackgroundImage(StyleValue)
{
	var ColorRegex=/background\-image\:[^;]*/gi;
	return StyleValue.replace(ColorRegex,"");
}		

function RemoveNonShorthandBackgroundRepeat(StyleValue)
{
	var ColorRegex=/background\-repeat\:[^;]*/gi;
	return StyleValue.replace(ColorRegex,"");
}		

function RemoveNonShorthandBackgroundAttachment(StyleValue)
{
	var ColorRegex=/background\-attachment\:[^;]*/gi;
	return StyleValue.replace(ColorRegex,"");
}		

function RemoveNonShorthandBackgroundPosition(StyleValue)
{
	var ColorRegex=/background\-position\:[^;]*/gi;
	return StyleValue.replace(ColorRegex,"");
}		

//********************************
//** Return hex value for given rgb value   |    根据 rgb 值获取 hex 值
//********************************
function Convert2Hex(x) 
{
	var hexDigits = new Array("0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"); 
	return isNaN(x) ? "00" : hexDigits[(x - x % 16) / 16] + hexDigits[x % 16];
}

//********************************
//** Convert rgb color expression to hex color expression    |    将 rgb 颜色表达换成 hex 表达
//********************************
function BackgroundColorConvert(BackgroundColorExpression) 
{
	var rgbRegExp=new RegExp('^rgb\\(\\d+,\\s*\\d+,\\s*\\d+\\)$','gi');

	if (rgbRegExp.test(BackgroundColorExpression)==true)
	{	
		var rgb = BackgroundColorExpression.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
		return "#" + Convert2Hex(rgb[1]) + Convert2Hex(rgb[2]) + Convert2Hex(rgb[3]);
	}
	//else if (Trim(BackgroundColorExpression).toLowerCase()=='transparent')
	//{
	//	return ' ';
	//}
	else
	{
		return BackgroundColorExpression;
	}
}

//********************************
//** Convert % position expression to left / center / right  and  top / center / bottom    |    将百分比表达的位置转换为 left / center / right  与 top / center / bottom 
//********************************
function BackgroundPositionConvert(BackgroundPosition)
{
	return BackgroundPosition.replace(/^0%\s+/gi,'left ').replace(/^50%\s+/gi,'center ').replace(/^100%\s+/gi,'right ').replace(/\s+0%$/gi,' top').replace(/\s+50%$/gi,' center').replace(/\s+100%$/gi,' bottom');;	
}

//********************************
//** Trim leading and trailing space    |    去掉字符串开始和结尾处的空格
//********************************
function Trim(InputString)
{
	return   InputString.replace(/(?:^\s*)|(?:\s*$)/gi,"");
}

//********************************
//** Get calculated style value (instead of inline style value by expressions like element.style.color)   |    获取计算出的 style 值 （Element.style.color 一类的表达只会获得 inline style 的值，但我们需要通过 css class defination  以及 inline style 结合计算出的值）
//********************************
function GetStyle(Element, StyleName)
{	
	if(document.defaultView && document.defaultView.getComputedStyle)
	{		
		return document.defaultView.getComputedStyle(Element, "").getPropertyValue(StyleName);
	}
	else if(Element.currentStyle)
	{
		StyleName = StyleName.replace(/\-(\w)/g, function (strMatch, p1){return p1.toUpperCase();});		
		return Element.currentStyle[StyleName];
	}
}