/*
* @name grabword.js
* @desc firefox getword plugin
* @author wangwenwu
* @date 2013-07-15
*/
var eventRangeParent = null;
var eventTarget = null;
var eventRangeOffset = null;
var clientX = 0;
var clientY = 0;
var consoleService = Components.classes["@mozilla.org/consoleservice;1"].getService(Components.interfaces.nsIConsoleService);

var SetGrabWord;
var lib;

var KCB = {};
KCB.regObj = null;
KCB.regType = 0;

var word;

var currentDoc = null, startOffset = 0;

function IsAlnum(a)
{
	return/[a-zA-Z0-9']+/.test(a);
}

function IsChinese(a)
{
    if(/[^\u4e00-\u9fa5]/.test(a))
        return false;
    return true;
}

// 创建注册表对象
function createRegObj()
{
	if(KCB.regObj)
		return true;
	if ("@mozilla.org/windows-registry-key;1" in Components.classes)
	{
		KCB.regObj = Components.classes["@mozilla.org/windows-registry-key;1"].createInstance(Components.interfaces.nsIWindowsRegKey);
		KCB.regType = 2;
	}
	else if("@mozilla.org/winhooks;1" in Components.classes)
	{
		KCB.regObj = Components.classes["@mozilla.org/winhooks;1"].getService(Components.interfaces.nsIWindowsRegistry);
		KCB.regType = 1;
	}
	else if("@mozilla.org/browser/shell-service;1" in Components.classes)
	{
		KCB.regObj = Components.classes["@mozilla.org/browser/shell-service;1"].getService(Components.interfaces.nsIWindowsShellService);
		KCB.regType = 1;
	}
	else
	{
		KCB.regObj = null;
		KCB.regType = 0;
	}
	
	if(KCB.regType == 0)
		return false;
	return true;
}

//获取注册表的信息
function getRegInfo(strPath, strName)
{
	if(!createRegObj()){
		return false;
	}
	
	if(KCB.regType == 1){
		return KCB.regObj.getRegistryEntry(3, strPath, strName);
	}
	else if(KCB.regType == 2){
        try{
            KCB.regObj.open(Components.interfaces.nsIWindowsRegKey.ROOT_KEY_LOCAL_MACHINE,
                               strPath, Components.interfaces.nsIWindowsRegKey.ACCESS_READ);
            return  KCB.regObj.readStringValue(strName);
        }
        catch(err){
            
            KCB.regObj.open(Components.interfaces.nsIWindowsRegKey.ROOT_KEY_CURRENT_USER,
						   strPath, Components.interfaces.nsIWindowsRegKey.ACCESS_READ);
            return  KCB.regObj.readStringValue(strName);
        }
         
	}
}

//获取插件dll的地址
function getDllPath()
{
    createRegObj();
	var p = getRegInfo("SOFTWARE\\kingsoft\\PowerWordDict", "Location") + "\\plugin\\firefox\\lsGrabWord.dll";
	return p;
}

//所有初始化都放进try里
function init()
{
		try{
            path = getDllPath()
            Components.utils.import("resource://gre/modules/ctypes.jsm"); 
            lib = ctypes.open(path);
            SetGrabWord = lib.declare("SetGrabWord",
                                     ctypes.default_abi,
                                     ctypes.int32_t,
                                     ctypes.jschar.ptr
                                    );
       }catch(err){
			//alert(err);
			return;
       }
}
init();

function mouse_move(event)
{
    var eventDoc = null;
    var doc = event.target.ownerDocument;
    if (String(doc).indexOf("[object HTMLDocument]") != -1)
    {
        eventDoc = doc;
    }
    if (eventDoc != null)
    {
        if (currentDoc != eventDoc)
        {
            currentDoc = eventDoc;
        }
        eventTarget = event.target;
        if (eventTarget.tagName != "TEXTAREA" || eventTarget.tagName != "INPUT"  || eventTarget.tagName != "SELECT")
        {
            eventRangeParent = event.rangeParent;
            eventRangeOffset = event.rangeOffset;
            clientX = event.clientX;
            clientY = event.clientY;   
        }
    }
};

function get_word() {

  word = GetGrabWord(eventRangeParent, eventRangeOffset, eventTarget);
  if (word != null)
  {
	  return word;
  }
  return '';
}

var GB2312UnicodeConverter = { 
	ToUnicode: function(str){ 
		return escape(str).toLocaleLowerCase().replace(/%u/gi, '\\u'); 
    },
	ToGB2312: function(str){ 
		return unescape(str.replace(/\\u/gi, '%u')); 
    } 
};

//监控鼠标动作，获取字符串
function mouse_moniter()
{
	word = get_word();
	if (word != '')
	{
		//alert(word);
		//var lastStr = GB2312UnicodeConverter.ToUnicode(word + ":" + startOffset);
		//alert(lastStr);
		var flag = SetGrabWord(word + ":" + startOffset);
	}
	window.setTimeout(arguments.callee, 50);
}
mouse_moniter();

//取词主流程
function GetGrabWord(parent, offset, target)
{
	try
	{
		if (parent.parentNode != target)
			return "";
		if (parent.nodeType != 3)
			return "";
	}
	catch (e)
	{
		return "";
	}
	if (parent.parentNode) 
	{
		var foundNode = false;
		for (var c = parent.parentNode.firstChild; c !== null; c = c.nextSibling) 
		{
			if (c == parent)
			{
				foundNode = true;
				break;
			}
		}
		if (!foundNode)
			return "";
	}
	//
	var textRange = parent.ownerDocument.createRange();
	textRange.selectNode(parent);
	var wordRange = textRange.cloneRange();
	
	var start = offset, end = offset;
	startOffset = start;
	var frontNum = 0, backNum = 0; // 前面和后面的字符个数
	var c1 = 0, c2 = 0;
	var word = "";

	if(!textRange.startContainer.textContent)
		return "";
	
	var textNode = textRange.startContainer.childNodes[textRange.startOffset];
	for(; start > 0;)
	{// 向前添加字符
		wordRange.setStart(textNode, --start);
		word = wordRange.toString();
		if(!IsAlnum(word.charAt(0)))
		{
			if (IsChinese(word.charAt(0)))
				c1++;
			if (word.charAt(0) == " ")
				c2++;
				
			if((c1==0 && c2==0) || (c2==3) || (c1==5))
			{
				wordRange.setStart(textNode, ++start);
				break;
			}
		}
		frontNum++;
	}

	startOffset -= start;

	c1 = c2 = 0;
	for(; end < textNode.textContent.length;)
	{// 向后添加字符
		wordRange.setEnd(textNode, ++end);
		word = wordRange.toString();
		if(!IsAlnum(word.charAt(word.length - 1)))
		{
			if (IsChinese(word.charAt(word.length - 1)))
				c1++;
			if (word.charAt(word.length - 1) == " ")
				c2++;
			
			if((c1==0 && c2==0) || (c2==3) || (c1==5))
			{
				wordRange.setEnd(textNode, end - 1);
				break;
			}
		}
		backNum++;
	}
	
	word = "";
	if(frontNum + backNum > 0)
	{
		word = wordRange.toString();
		if (startOffset > word.length - 1)
			startOffset = word.length - 1;
	}
	
	return word;
}

