/*
 * 	 FileName:  __init__.js
 *   Author: JimmyXiong
 *   E-mail: w3cgod@gmail.com
 *   Created Date:	2009-09-11
 *   Last Update:	2009-09-21
 *   Version:  1.2_Beta
 *   	V1.1b	添加input事件监听实现输入框自动缩放宽度
 *   	V1.2b	添加textarea事件监听实现输入框自动缩放宽度和高度
 *   	V1.3b
 *   	修改事件监听添加方式，提高程序执行效率。修改checkbox宽度增长bug
 *   	v1.4	添加$check$.GPs分组功能，实现同分组checkbox状态同步
 *   			增加input Focus变色功能
 *
 *   Meta:
 *	 	测试兼容IE5.5-8,Firefox 3.5.3,Chorme 2.0,Safari 4.0
 *	 	其它浏览器未测。
 *
 *	 InsertInput:
 *   该脚本自动判断页面中的元素并替换。
 *
 *   判断span有下划线，替换成input
 *   	具有获得span内容转换成input后填入
 *   	具有合并相邻元素的input以及内容功能，
 *
 *   判断框框字符，替换成checkbox
 *   	□ 空心,■ 实心
 *   	判断框框字符是实心还是空心，生成的checkbox与之对应
 *   例子：var insert = new InsertInput();

 *
 *   ClearSameClass:
 *   让相同名称的空class变成一个。合并之后并增加相应高度，
 *   使之样式与以前一致
 *   例子：var clear1 = new ClearSameClass(".dash6b63_6587");
 *	 
 *	 $(): 此功能由mootools代替，此功能可正常使用。
 *   编写Dom选择器，以$(oE)方式选择DOM对象，.为Class，@为name,
 *   #为ID,直接写字符串的话返回相应tagName集合。
 *   例子：$('tagname');$('#id');$('.class');$('@name')
 *
 *   其他：
 *   增加Firefox等非IE浏览器下面outerHTML功能的实现
 *   增加Firefox等非IE浏览器下面的innerText功能的实现
*/

//页面程序是否加载和运行完
var pageComplete = 0;

//dom选择器
//oE = .[str] 选择class返回Elements
//oE = #[str] 选择一个dom对象返回Element
//oE = [str]  选择tagName返回Elements
//oE = @[str]  选择name返回Elements
var $ = function(oE)
{
	if(typeof(oE) === "string")
	{
		oEle = oE.split(" ");
		result = document;
		var oEDom = function(oE){
			if(oE.indexOf(".") === 0)
			{
				oE = oE.substring(1);
				//兼容IE浏览器
				if(!document.getElementsByClassName)
				{
					//输出目标结果为数组对象
					result.getElementsByClassName = function(oE)
					{
						var getEleClass = [];
						var myclass = new RegExp("\\b"+ oE +"\\b");
						var elem = this.getElementsByTagName("*");
						for(var h=0;h<elem.length;h++)
						{
							var classes = elem[h].className;
							if (myclass.test(classes))
							{
								getEleClass.push(elem[h]);
							}
						}
						return getEleClass;
					}
					return result.getElementsByClassName(oE)
				}
				else{
					return result.getElementsByClassName(oE)
				}
			 }
			 else if(oE.indexOf("#") === 0)
			 {
				oE = oE.substring(1);
				return document.getElementById(oE);
			}
			else if(oE.indexOf("@") === 0)
			 {
				oE = oE.substring(1);
				return document.getElementsByName(oE);
			 }
			 else
				return document.getElementsByTagName(oE);
		}
		
		for(i=0; i<oEle.length; i++)
		{
			oE = oEle[i]
			result = oEDom(oE);
		}
		return result
	}
	else
		return null;
}

//自动生成input id初始值
var iIid = 1;
//自动生成checkbox id初始值		//	已经统一为input 2009-12-2 @xiongtao
//var iCid = 0;

//让FF,支持outerHTML
if(window.HTMLElement)
{
	//判断标签是否能包含子标签
	HTMLElement.prototype.__defineGetter__("canHaveChildren",function(){
					switch(this.tagName.toLowerCase()){
							case "area":
							case "base":
							case "basefont":
							case "col":
							case "frame":
							case "hr":
							case "img":
							case "br":
							case "input":
							case "isindex":
							case "link":
							case "meta":
							case "param":
									return false;
							}
					return true;
	});
	HTMLElement.prototype.__defineSetter__("outerHTML",function(sHTML){
		var r=this.ownerDocument.createRange();
		r.setStartBefore(this);
		var df=r.createContextualFragment(sHTML);
		this.parentNode.replaceChild(df,this);
		return sHTML;
		});
	HTMLElement.prototype.__defineGetter__("outerHTML",function(){
		var attr;
		var attrs=this.attributes;
		var str="<"+this.tagName;
		for(var i=0;i<attrs.length;i++){
			attr=attrs[i];
			if(attr.specified)
				str+=" "+attr.name+'="'+attr.value+'"';
			}
		if(!this.canHaveChildren)
			return str+" />";
		return str+">"+this.innerHTML+"</"+this.tagName+">";
		});

	//让FF支持innerText
    function setInnerText(o, s) {
        while (o.childNodes.length != 0) {
            o.removeChild(o.childNodes[0]);
        }

        o.appendChild(document.createTextNode(s));
    }

    function getInnerText(o) {
        var sRet = "";

        for (var i = 0; i < o.childNodes.length; i ++) {
            if (o.childNodes[i].childNodes.length != 0) {
                sRet += getInnerText(o.childNodes[i]);
            }

            if (o.childNodes[i].nodeValue) {
                if (o.currentStyle.display == "block") {
                    sRet += o.childNodes[i].nodeValue + "\n";
                } else {
                    sRet += o.childNodes[i].nodeValue;
                }
            }
        }

        return sRet;
    }
	HTMLElement.prototype.__defineGetter__("currentStyle", function () {
		return this.ownerDocument.defaultView.getComputedStyle(this, null);
	});

	HTMLElement.prototype.__defineGetter__("innerText", function () {
		return getInnerText(this);
	})

	HTMLElement.prototype.__defineSetter__("innerText", function(s) {
		setInnerText(this, s);
	})
}

//简化节点让相同名称的空class变成一个
//sName = className
var ClearSameClass = function(sName)
{
	this.top = this;
	this.oMark = [];
	this.sName = sName;
	this.__init__();
}
//把符合要求的目标加入到oMark数组中
ClearSameClass.prototype.DrawMark = function()
{
	for(var i=0; i<$('.'+this.sName).length; i++)
	{
		//目标Class的节点只有一个属性且没有子节点的时候加入到oMark
		if($('.'+this.sName)[i].nodeType !== 3 && $('.'+this.sName)[i].children.length === 0)
		{
			this.oMark.push(i);
			var oNextClass = $('.'+this.sName)[i].nextSibling;
			var sCount = 1;
			var top = this;
			//确定相邻只有一个属性的节点的数目
			function CheckSibling(top)
			{
				var oMarkLen = top.oMark.length;
				if(oNextClass.nodeType !== 3 && oNextClass.children.length === 0)
				{
					sCount++;
					nextOne();
				}
				else if(oNextClass.nodeType === 3)
				{
					nextOne();
				}
				else
				{
					top.oMark.push(sCount);
				}

				function nextOne()
				{
					if(oNextClass.nextSibling)
					{
						oNextClass = oNextClass.nextSibling;
						CheckSibling(top);
					}
					else
						top.oMark.push(sCount);
				}
			}
			CheckSibling(top);
			this.OperateNode();
			this.oMark = [];
			i += sCount;
		}
	}
}

//合并重复节点
ClearSameClass.prototype.OperateNode = function()
{
	var oMarkLen = this.oMark.length;
	if(oMarkLen > 0)
	{
		var sCount = this.oMark[0];
		var sCount_child = this.oMark[1];
		$('.'+this.sName)[sCount].style.height = 16 * sCount_child + "px";
		//删除重复节点
		for(var _i=1; _i<sCount_child; _i++)
		{
			$('.'+this.sName)[sCount+1].parentNode.removeChild($('.'+this.sName)[sCount+1])
		}
	}
}
//初始化调用函数
ClearSameClass.prototype.__init__ = function()
{
	this.DrawMark();
}

//在有下划线的span处插入Input
var InsertInput = function()
{
	this.oP = $('p');
	//是否初始化
	this.init = document.body.rel;
	this.__init__();
}
InsertInput.prototype.__init__ = function()
{
	if(!this.init)
	{
		//轮询P标签执行标签转换
		for(var i=0; i<this.oP.length; i++)
		{
			//span转换为input
			var oSpan = this.oP[i].getElementsByTagName('span');
			if(oSpan)
				this.parseInput(oSpan);
			
			//把input转换细分为textarea，和不可输入并添加事件和id
			var oInput = this.oP[i].getElementsByTagName('input');
			if(oInput)
			{
				//把不可输入部分的input转换成span
				this.parseSpan(oInput);
				//把部分input转换为textarea
				this.parseTextarea(oInput);
				//匹配input中的内容满足条件的添加className
				this.addClassName(this.oP[i].getElementsByTagName('input'));
				//添加事件监听函数并添加id
				Listen(this.oP[i].getElementsByTagName('input'));
				//匹配textarea中的内容，满足条件的添加className
				if(this.oP[i].getElementsByTagName('textarea').length > 0)
				{
					this.addClassName(this.oP[i].getElementsByTagName('textarea'));
					Listen(this.oP[i].getElementsByTagName('textarea'));
				}
			}
		}
	}

	//添加事件监听和id
	else
	{
		for(var i=0; i<this.oP.length; i++)
		{
			//添加事件监听函数并添加id
			Listen(this.oP[i].getElementsByTagName('input'));
			//匹配textarea中的内容，满足条件的添加className
			if(this.oP[i].getElementsByTagName('textarea').length > 0)
			{
				this.addClassName(this.oP[i].getElementsByTagName('textarea'));
				Listen(this.oP[i].getElementsByTagName('textarea'));
			}
		}
	}
}


//把input转换成Span
InsertInput.prototype.parseSpan = function(oInput)
{
	var iInputLength = oInput.length;
	for(var i=0; i<iInputLength; i++)
	{	
		var sR = /\$不填/;
		var sValue = oInput[0].value;
		if(sR.exec(sValue))
		{	
			var sHeight = oInput[0].style.height;
			var sWidth = oInput[0].style.width;
			var sFontSize = oInput[0].style.fontSize;
			oInput[0].outerHTML = "<span class='underlineSpan' style='height:"
			+sHeight+"; padding-left:"+sWidth+"; font-size:"+sFontSize+";'"
			+">&nbsp;<\/span>"
		}
	}
}


//把下划线转换为Input
InsertInput.prototype.parseInput = function(oSpan)
{
	var iMark = [];
	for(var i=0; i<oSpan.length; i++)
	{
		//替换Checkbox
		var sText = oSpan[i].innerText;
		var sRe = /□+/,sRf = /■+/;
		//s是否包含在o目标之内
		function Isin(o,s)
		{
			return s.exec(sText);
		}
		if(Isin(sText,sRe))
		{
			oSpan[i].innerHTML = oSpan[i].innerHTML.replace(sRe,"<input type='checkbox' class='checkbox' \/>")
		}
		if(Isin(sText,sRf))
		{
			oSpan[i].innerHTML = oSpan[i].innerHTML.replace(sRf,"<input type='checkbox' class='checkbox' checked='checked' \/>")
		}
		//确定插入点为带下划线的节点并插入input
		var sDecoration = oSpan[i].style.textDecoration;
		if(sDecoration === "underline" || (oSpan[i].rel === "contact"))
		{
			iMark.push(i)
			var iHeight = oSpan[i].offsetHeight;
			var iWidth = oSpan[i].offsetWidth;
			var iFont = oSpan[i].style.fontSize;
			if(oSpan[i].rel === "contact" && oSpan[i].getElementsByTagName('input')[0])
			{
				var sValue = oSpan[i].getElementsByTagName('input')[0].value;
			}
			else
			{
				var sValue = oSpan[i].innerText;
				var sA = /\s+/;
				if(sA.exec(sValue))
				{sValue = sValue.replace(sA,'')}
				//var sValue = oSpan[i].getElementsByTagName['input'][0].value ?
				//	oSpan[i].rel === "contact":
				//	oSpan[i].innerText;
			}
			var oInput = document.createElement('input');
			oInput.className = "input";
			oInput.name = "input";
			oInput.type = "text";
			oInput.style.height = iHeight + 2 + "px";
			oInput.style.width = iWidth + "px";
			oInput.style.fontSize = iFont;
			oInput.style.lineHeight = iHeight + 2 + "px";
			oInput.value = sValue;
			oSpan[i].innerHTML = "";
			oSpan[i].style.textDecoration = "none";
			oSpan[i].appendChild(oInput);
			//当相邻的两个span都为input时将其合并为一个
			var iL = iMark.length;
			if(iL > 1)
			{
				var b = parseInt(iMark[iL-1]) - 1;
				var a = parseInt(iMark[iL-2]);
				if(a === b)
				{
					try{
					oSpanWidth = oSpan[i-1].getElementsByTagName('input')[0].style.width;
					oSpan[i-1].getElementsByTagName('input')[0].style.width = 
						parseInt(oSpanWidth) + iWidth +"px";
					oSpan[i-1].getElementsByTagName('input')[0].value += sValue;
					oSpan[i-1].rel = "contact";
					oSpan[i].parentNode.removeChild(oSpan[i]);
					}catch(err){}
					arguments.callee(oSpan);
				}
			}
		}
	}
}


//把input中内容为“换行”的转换为textarea
InsertInput.prototype.parseTextarea = function(oInput)
{
	for(var i=0; i<oInput.length; i++)
	{
		var sR = /\$换行/;
		if(oInput[i].type === "text" && sR.exec(oInput[i].value))
		{
			var sHeight = oInput[i].style.height;
			var sWidth = oInput[i].style.width;
			var sFontSize = oInput[i].style.fontSize;
			oInput[i].outerHTML = "<textarea class='textarea' style='height:"
			+sHeight+"; width:"+sWidth+"; font-size:"+sFontSize+";'"
			+">"+oInput[i].value.replace(sR,'')+"<\/textarea>"
		}
	}
}


//把input中特殊标签转换为class和name以及id
InsertInput.prototype.addClassName = function(oInput)
{
	for(var i=0; i<oInput.length; i++)
	{
		var sValue = oInput[i].value;
		var sRc = /\$check\$\.Gp([A-Za-z0-9]+)/;
		var sRs = /\$check\$\.SGp([A-Za-z0-9]+)/;
		var sRid = /\$mark([A-Za-z0-9]+)/g;
		var sR = /\$\.Gp([A-Za-z0-9]+)/g;
		var result,res;
		//当匹配到sRc时给上input添加class并删除本身
		if(sValue.match(sRc))
		{	
			result = sRc.exec(sValue);
			if(result === null)
				result = sRc.exec(sValue);
			oInput[i-1].className += " gp" + result[1];
			oInput[i-1].name = "gp" + result[1];
			//添加点击事件监听，激活排斥程序
			//addEvent(oInput[i-1],'click',function(){Gprun(this, Gpsw)});
			oInput[i].parentNode.removeChild(oInput[i]);
		}
		else if(sValue.match(sRs))
		{	
			result = sRs.exec(sValue);
			if(result === null)
				result = sRs.exec(sValue);
			oInput[i-1].className += " sgp" + result[1];
			oInput[i-1].name = "sgp" + result[1];
			//添加点击事件监听，激活排斥程序
			//addEvent(oInput[i-1],'click',function(){Gprun(this, Gpsw)});
			oInput[i].parentNode.removeChild(oInput[i]);
		}
		//当匹配到sRid时把input转换为span并添加id
		else if(sValue.match(sRid))
		{	
			result = sRid.exec(sValue);
			if(result === null)
				result = sRid.exec(sValue);
			var sId = 'mark' + result[1];
			oInput[i].outerHTML = "<span id="+sId+"><\/span>"
		}
		else if(sValue.match(sR))
		{
			result = sR.exec(sValue);
			if(result === null)
				result = sR.exec(sValue);
			//当匹配到Gp规则时将结果添加到className
			oInput[i].className += " gp" + result[1];
			oInput[i].name = "gp" + result[1];
			oInput[i].value = oInput[i].value.replace(result[0],'');
		}
	}
}


//分组延时开关
var Gpsw = 0;
var Gorun;
//分组同步数据
var Gprun = function(which)
{
	hasChange = 1;
	this.init = function(which)
	{
		var sValue = which.value;
		var sClass = which.className;
		//把对应节点class转换为数组
		var result = sClass.split(" ");
		//轮询相同class对象
		if(result.length >1)
		{
			for(var i=1; i<result.length; i++)
			{
				var sR = /sgp/;

				//当前对象为checkbox且class为sgp开头时checkbox同时选中
				if(which.type === "checkbox" && sR.exec(result[i]))
				{
					for(var _i=0; _i<$("@"+result[i]).length; _i++)
					{
						$("@"+result[i])[_i].checked = which.checked;
					}
				}

				//当当前对象为checkbox时相同name中checkbox为单选
				else if(which.type === "checkbox")
				{
					if(which.checked === true)
					{
						for(var _i=0; _i<$("@"+result[i]).length; _i++)
						{
							$("@"+result[i])[_i].checked = false;
						}
						which.checked = true;
					}
					else
						which.checked = false;
				}
				//当前对象为非checkbox时相同name中数据值相同
				else
				{
					for(var _i=0; _i<$("@"+result[i]).length; _i++)
					{
						$("@"+result[i])[_i].value = which.value;
						$("@"+result[i])[_i].click();
					}
				}
			}
		}
		Gpsw = 0;
	}
	//分组数据处理延时1000ms执行
	//当目标是非checkbox时进行执行延时
	if(!Gpsw && (which.type !== "checkbox"))
	{
		Gpsw = 1;
		try{
		Gorun = setTimeout(function(){(this.init(which))},800);
		}catch(err){alert(err)}
	}
	else if(which.type === "checkbox")
	{
		this.init(which);
	}
	else
	{
		clearTimeout(Gorun);
		Gorun = setTimeout(function(){(this.init(which))},800)
	}
}


//统一事件监听方法
//addEvent||removeEvent(obj,type,fn)
//obj为对象，type为事件类型，fn为回调函数
function addEvent( obj, type, fn ) { 
   if ( obj.attachEvent ) { 
     obj['e'+type+fn] = fn; 
     obj[type+fn] = function(){obj['e'+type+fn]( window.event );} 
     obj.attachEvent( 'on'+type, obj[type+fn] ); 
   } else 
     obj.addEventListener( type, fn, false ); 
} 
function removeEvent( obj, type, fn ) { 
   if ( obj.detachEvent ) { 
     obj.detachEvent( 'on'+type, obj[type+fn] ); 
     obj[type+fn] = null; 
   } else 
     obj.removeEventListener( type, fn, false ); 
} 


//添加监听事件
var Listen = function(oE)
{
	var iLength = oE.length;
	for(var i=0; i<iLength; i++)
	{
		if(oE[i].type === "text" || oE[i].tagName === "TEXTAREA" || oE[i].type === "checkbox")
		{
			if(oE[i].type === "checkbox")
			{
				addEvent(oE[i], 'focus', function(){GetFocus(this)});
				addEvent(oE[i], 'click', function(){Gprun(this)});
			}
			else
			{
				addEvent(oE[i], 'focus', function(){GetFocus(this)});
				addEvent(oE[i], 'click', function(event){checkLength(this, event)});
				addEvent(oE[i], 'keyup', function(event){checkLength(this, event);Gprun(this)});
				addEvent(oE[i], 'paste', function(event){checkLength(this, event);Gprun(this)});
			}
			if(!oE[i].id)
			{
				if(document.body.rel)
				{
					iIid = parseInt(document.body.rel);
				}
				oE[i].id = "input"+iIid;
				iIid++;
			}
		}
	}
}
window.onload = function()
{
	//var clear1 = new ClearSameClass(".dash6b63_6587");
	//var clear2 = new ClearSameClass(".dash7eaf_6587_672c_002c_666e_901a_6587_5b57");
	var insert = new InsertInput();
	if(!document.body.rel)
		document.body.rel = iIid;
	addEvent(document,'mouseup',rightMenu);
	function parseHTML()
	{
		alert(document.body.rel)
		var pre = document.createElement('pre');
		var body_text = document.getElementsByTagName('html')[0].outerHTML; 
		pre.innerText = body_text;
		document.body.innerHTML = "";
		document.body.appendChild(pre)
	}
	//parseHTML();

	pageComplete = 1;
}


