// JavaScript Document

function makeProperty(o, name, getpredicate, setpredicate){
    var value;
	if (G_Parent == null)
		G_Parent = getParent(window);
		
    o["get"+name] = function(){
		if (G_Parent != window)
		{
			return G_Parent.GLOBAL_VARIABLES["get"+name].call(this);
		}
		else
		{
			if (getpredicate != null)
			{
				return getpredicate(value);
			}
			else
			{
				return value;
			}
		}
	};// 这里有两个scope对象call object(谁调用makeProperty), global


    o["set"+name] = function(v){// 这里有两个scope对象call object(谁调用makeProperty),
								// global
		if (G_Parent != window)
		{
			return G_Parent.GLOBAL_VARIABLES["set"+name].call(this,v);
		}
		else
		{
			if (setpredicate && !setpredicate(v))
			{
				throw "set error";
			}
			else
			{
				value = v;
			}
		}
	};
}

// 全局的对象
var GLOBAL_VARIABLES = {};

$(function(){
	makeProperty(GLOBAL_VARIABLES, "Attach", null,null);
	GLOBAL_VARIABLES.setAttach("");
	makeProperty(GLOBAL_VARIABLES, "Seq", null,null);
	GLOBAL_VARIABLES.setSeq("");
	makeProperty(GLOBAL_VARIABLES, "CurrWin", null,null);
	GLOBAL_VARIABLES.setCurrWin(window);
	makeProperty(GLOBAL_VARIABLES, "CurrCtl", null,null);
	GLOBAL_VARIABLES.setCurrCtl("");
	makeProperty(GLOBAL_VARIABLES, "Change", null,null);
	GLOBAL_VARIABLES.setChange("True");
	makeProperty(GLOBAL_VARIABLES, "Loading", null,null);
	GLOBAL_VARIABLES.setLoading("False");
});

// 获取账户信息
function getAccount()
{
	var data = f_client_call(
		"G_SYS_UserName");
	var OAccount = new Object();
	if (data != null)
	{
		var datas = data.split("\r\n");
		OAccount["account"] = datas[0];
		OAccount["name"] = datas[1];
	}
	else
	{
		OAccount["account"] = "";
		OAccount["name"] = "";
	}
	return OAccount;
}

// 新邮件
function NewMail()
{
	var data = f_client_call(
		"S_MSG_NEW"); 
	return data;
}

// 设置邮件属性
function SetAttrib(attrib)
{
	var data = f_client_call(
		"S_MSG_SETATTRIB",attrib); 
	return data;
}


// 保存邮件
function SaveMail(xml)
{
	var data = f_client_call(
		"S_MSG_SAVE",xml);
	return data;
}

// 获取邮件
function GetMail(seq)
{
	var data = f_client_call(
		"G_MSG_GET",seq); 
	return data;
}

// 发送邮件
function SendMail(seq)
{
	var data = f_client_call(
		"S_MSG_SEND",seq); 
	return data;
}

// 彻底删除邮件
function DeleteMail(seqs)
{
	var data = f_client_call(
		"S_MSG_DELETE",seqs); 
	return data;

}

// 删除附件
function DeleteAttach(seq,nid)
{
	var data = f_client_call(
		"S_MSG_DEL_ATTACH",seq + "\r\n" + nid); 
	return data;
}

//添加附件
function AddMailAttach(seq,ntype)
{
	var data = f_client_call(
		"S_MSG_ADD_ATTACH",seq + "\r\n" + ntype); 
	return data;
}

//转发邮件
function ForwordMail(seq)
{
	var data = f_client_call(
		"S_MSG_FORWARD",seq); 
	return data;
}

// 新建联系人组
function NewGroup(sName,sDesc)
{
	var data = f_client_call(
		"S_MSG_GROUP_ADD",sName + "|" + sDesc);
	// if (data != 0)
	// {
	// g_gid = data;
	// }
	return data;
}

// 编辑联系人组
function EditGroup(gid,sName,sDesc)
{
	var data = f_client_call(
		"S_MSG_GROUP_MODIFY",gid + "|" + sName + "|" + sDesc);
	// if (data != 0)
	// {
	// g_gid = data;
	// }
	return data;
}

// 获取联系人列表
function GetContactList()
{
	var data = f_client_call(
		"G_MSG_CONTACT_LIST");
	var datas = data.split("\r\n");
	var aContact = new Array();
	if (data == "")
	{
		return aContact;
	}
	for( i=0 ; datas!=null && i<datas.length ; i++ )
	{
		var fields = datas[i].split("|");
		var object = new Object();
		object["account"] = fields[0];
		object["name"] = fields[1];
		object["desc"] = fields[2];
		object["gid"] = fields[3];
		/*
		 * if (IsNum(object["gid"])) { object["gid"] = toGIDs(fields[3]); } else {
		 * object["gid"] = new Array('0'); }
		 */
		object["glive"] = false;
		aContact.push(object);
	}
	return aContact;
}

// 获取联系人组列表
function GetGroupList(aContact)
{
	if (aContact == null)
		aContact = GetContactList();
	var data = f_client_call(
		"G_MSG_GROUP_LIST");
	var datas;
	if (data == "")
		datas = null;
	else
		datas = data.split("\r\n");
	var aGroup = new Array();
	var object = new Object();
	object["gid"] = "0";
	object["name"] = "未分组";
	object["desc"] = "未分组联系人";
	object["Contacts"] = $.grep(aContact,function(cur,j){return checkGrp("0",cur["gid"]);});
	aGroup.push(object);
	for( i=0 ; datas!=null && i<datas.length ; i++ )
	{
		var fields = datas[i].split("|");
		var object = new Object();
		object["gid"] = fields[0];
		object["name"] = fields[1];
		object["desc"] = fields[2];
		object["Contacts"] = $.grep(aContact,function(cur,j){return checkGrp(fields[0],cur["gid"]);});
		aGroup.push(object);
	}
	return aGroup;
}

// 新建联系人
function NewContact(account,name,desc,gid)
{
	var str = account + "|" + name + "|" + desc + "|" + gid;
	var data = f_client_call(
		"S_MSG_CONTACT_ADD",str);
		return data;
}

// 删除联系人组
function DeleteGroup(gid)
{
	var data = f_client_call(
		"S_MSG_ GROUP_DELETE",gid);
		return data;
}

// 删除联系人
function DeleteContact(accounts)
{
	var data = f_client_call(
		"S_MSG_CONTACT_DEL",accounts);
		return data;
}

// 取消息中心版本
function ShowVersion()
{
	var data = f_client_call(
		"G_MSG_VERSION");
	return data;
}

// 编辑联系人
function EditContact(account,name,desc,gid)
{
	var data = f_client_call(
		"S_MSG_CONTACT_MODIFY",account + "|" + name + "|" + desc + "|" + gid);
		return data;
}

function ReceiveMail()
{
	var data = f_client_call("S_MSG_RECV");
	if (data == "-1")
	{
		hidLoading();
	}
}

function getMailLists()
{
	var data = f_client_call("G_MSG_LIST");
	var datas = data.split("\r\n");
	datas = datas.reverse();
	var OReturn = new Object();
	OReturn["iSent"] = 0;
	OReturn["iTrashUnRead"] = 0;
	OReturn["iindexUnRead"] = 0;
	OReturn["iInbox"] = 0;
	OReturn["iTrash"] = 0;
	OReturn["iDrafts"] = 0;
	OReturn["aInbox"] = new Array;
	OReturn["aDrafts"] = new Array;
	OReturn["aSent"] = new Array;
	OReturn["aTrash"] = new Array;
	for( i=0 ; datas!=null && i<datas.length ; i++ )
	{
		if (datas[i] == "")
		{
			continue;
		}
		var mail = datas[i].split("|");
		var object = new Object();
		object["seq"] = mail[0];
		object["time"] = mail[1];
		object["attrib"] = "000000" + parseFloat(mail[2]).toString(16);	
		object["mailsource"] == "";
		object["unread"] = 0;//已读
		var sattr = object["attrib"].substring(object["attrib"].length-6,object["attrib"].length);
		object["from"] = mail[3];
		var s2 = parseFloat(sattr.substring(1,2)).toString(2);
		if (s2.substring(s2.length -2,s2.length -1) == "1")
		{
			OReturn["iTrash"] = OReturn["iTrash"] + 1;
			if (s2.substring(s2.length -1) == "0")
			{
				OReturn["iTrashUnRead"] = OReturn["iTrashUnRead"] + 1;
				object["unread"] = 1;//未读
			}
			OReturn["aTrash"].push(object);
			continue;
		}
		switch(sattr.substring(3,6)) 
		{
			case "001":
				OReturn["iSent"] = OReturn["iSent"] + 1;
				OReturn["aSent"].push(object);
				break;
			case "002":
				OReturn["iInbox"] = OReturn["iInbox"] + 1;
				if (s2.substring(s2.length -1) == "0")
				{
					OReturn["iindexUnRead"] = OReturn["iindexUnRead"] + 1;
					object["unread"] = 1;//未读
				}
				OReturn["aInbox"].push(object);
				break;
			case "000":
				OReturn["iDrafts"] = OReturn["iDrafts"] + 1;
				OReturn["aDrafts"].push(object);
				break;
		}
	}
	return OReturn;
}


// 获取消息中心版本
function GetVersion()
{
	var data = f_client_call(
		"G_MSG_VERSION",""); 
	return data;
}

// 获取组信息
function GetGroup(gid,aGroup)
{
	var Groups;
	if (aGroup == null)
	{
		Groups = GetGroupList();
	}
	else
	{
		Groups = aGroup;
	}
	var alist = $.grep(Groups,function(cur,j){return cur["gid"] == gid;});
	if (alist.length > 0)
	{
		return alist[0];
	}
	else
	{
		return null;
	}
}

function obj2str(o){

  var r = [];

  if(typeof o == "string" || o == null) {

    return o;

  }

  if(typeof o == "object"){

    if(!o.sort){

      r[0]="{"

      for(var i in o){

        r[r.length]=i;

        r[r.length]=":";

        r[r.length]=obj2str(o[i]);

        r[r.length]=",";

      }

      r[r.length-1]="}"

    }else{

      r[0]="["

      for(var i =0;i<o.length;i++){

        r[r.length]=obj2str(o[i]);

        r[r.length]=",";

      }

      r[r.length-1]="]"

    }

    return r.join("");

  }

  return o.toString();

}

function ExpContact()
{
	var data = f_client_call(
	"S_MSG_CONTACT_EXPORT");
	alert("导出成功！");
}

function ImpContact()
{
	var data = f_client_call(
	"S_MSG_CONTACT_IMPORT");
	alert("导入成功！");
}

function getAttach(sSeq)
{
	var data = f_client_call(
		"G_MSG_ATTACH",sSeq);
	var iFirstAttach = data.indexOf("<attach");
	var iLastAttach = data.lastIndexOf("</attach>");
	var sAttach = ""
	if (iFirstAttach != -1 && iLastAttach != -1)
	{
		var sAttach = data.substring(iFirstAttach,iLastAttach + 9);
	}
	GLOBAL_VARIABLES.setAttach(sAttach);
}


function preclose()
{
	if (GLOBAL_VARIABLES.getChange() =="True")
	{
		return "True";
	}
	else
	{
		if (GLOBAL_VARIABLES.getCurrWin().chkSave())
		{
			return "True";
		}
		else
		{
			return "False";
		}
	}
}


//去除相同Array数组元素
function myArray_Unique(myArray){
　　for(var i=0;i<myArray.length-1;i++){
　　　　var temp=myArray[i];
　　　　for(var j=i+1;j<myArray.length;j++){
　　　　　　if(temp==myArray[j]){
　　　　　　myArray.splice(j--,1);
　　　　　　}
　　　　}
　　}
　　return myArray;
}


var KEYCODE_TAB = "9" ; //TAB的键值
var KEYCODE_DEL = "46" ; //DEL的键值
var KEYCODE_ENTER = "13"; //ENTER的键值

//客户端主动调用接口
function OnCltKeyPress(KeyCode)
{
    switch (KeyCode)
    {
		case KEYCODE_ENTER:
			if (typeof(window.searchTXT) != "undefined")
			{
				switch (GLOBAL_VARIABLES.getCurrCtl())
				{
				case "Inbox_search":
					searchTXT("Inbox");
					break;
				case "Sent_search":
					searchTXT("Sent");
					break;
				}
			};
			return "1";
		break;
    }
    return "0" ;
}

function notice(params)
{
	var datas = params.split("\r\n");
	switch (datas[0])
	{
		case "1":
			log.info("发送邮件通知的结果:" + datas[1]);
			notice_receive(datas[1]);
			return;
		break;
		case "2":
			log.info("接收邮件通知的结果:" + datas[1]);
			notice_receive(datas[1]);
			return;
		break;
		case "3":
			log.info("删除邮件通知的结果:" + datas[1]);
			return;
		break;
		case "4":
			log.info("转到邮件列表的结果:" + datas[1]);
			notice_receive(datas[1]);
		break;
		case "5":
			log.info("转到指定邮件的结果:" + datas[1]);
			notice_read(datas[1]);
			return;
		break;
		case "6":
			log.info("增加附件通知的结果:" + datas[1]);
			notice_attach(datas[1]);
		break;
		case "7":
			log.info("邮件列表变化通知:" + datas[1]);
		break;
		case "8":
			log.info("邮件属性变化通知:" + datas[1]);
		break;
	}
}

function notice_sendreturn(data)
{
	if (data == "1|0")
	{
		notice_list(data);
	}
}

function notice_receive(data)
{
	if (GLOBAL_VARIABLES.getLoading() == "True")
	{
		GLOBAL_VARIABLES.getCurrWin().hidLoading();
	}
	if ((data != "0"))
	{
		GLOBAL_VARIABLES.getCurrWin().showReceiveMail();
	}
}

function notice_read(data)
{
	OpenPOPMail("page=qlmail.htm?seq=" + data);
}

function notice_list(data)
{
	switch(data)
	{
		case "0":
			GLOBAL_VARIABLES.getCurrWin().location = sTagPage + GLOBAL_VARIABLES.getIndex() + "?tab=index";
		break;
		case "1":
			GLOBAL_VARIABLES.getCurrWin().location = sTagPage + GLOBAL_VARIABLES.getIndex() + "?tab=sent";
		break;
		case "2":
			GLOBAL_VARIABLES.getCurrWin().location = sTagPage + GLOBAL_VARIABLES.getIndex() + "?tab=drafts";
		break;
	}
}

function notice_attach(data)
{
	var sTagPage= GLOBAL_VARIABLES.getWrite();
	var p = new Poly9.URLParser(GLOBAL_VARIABLES.getCurrWin().location.href);
	var sPage = p.getPathname().toLowerCase();
	sPage = sPage.substring(sPage.lastIndexOf("/") + 1,sPage.length + 1);
	if (sPage != sTagPage)
	{
		GLOBAL_VARIABLES.getCurrWin().location=sTagPage + "?newseq=" + data;
	}
	else
	{
		GLOBAL_VARIABLES.setSeq(data);
		getAttach(data);
		GLOBAL_VARIABLES.getCurrWin().ShowAttach();
	}
}

function showCommodity(sCommodity)
{
	var aCommoditys = sCommodity.split(",");
	var rCommodity = "";
	for(var i =0; aCommoditys != null && i < aCommoditys.length; i ++)
	{
		if (aCommoditys[i].indexOf(":") >= 0)
		{
			rCommodity += aCommoditys[i].substring(aCommoditys[i].indexOf(":") + 1) + ",";
		}
	}
	if (rCommodity.length > 0 )
	{
		rCommodity = rCommodity.substring(0,rCommodity.length - 1);
	};
	return rCommodity;
}

function op(seq,id,opcode)
{
	f_client_call("S_MSG_OP",seq + "\r\n" + id + "|" + opcode);
}

function stopBubble(e) {  
    var e = e ? e : window.event;  
    if (window.event) { // IE
        e.cancelBubble = true;   
    } else { // FF
        // e.preventDefault();
        e.stopPropagation();   
    }   
}  

function addSenderlist(groups,gids,account,accountname)
{
	var gid = "";
	var acountid = "";
	if ($.grep(OContact,function(cur,j){return cur["account"]== account}).length > 0)
	{
		EditContact(account,accountname,"",gids);
	}
	else
	{
		NewContact(account,account,accountname,gids);
	}
}

function IsNum(s)
{
    if(s!=null){
        var r,re;
        re = /\d*/i; // \d表示数字,*表示匹配多个数字
        r = s.match(re);
        return (r==s)?true:false;
    }
    return false;
}

//将二进制分组列表转换成分组数组
function toGIDs(s)
{
	var gids = s.toString(2);
	var agid = new Array();
	if (s == "0" || s == "")
	{
		agid.push("0");
	}
	else
	{
		var gid2 = "";
		for(var i=gids.length;i>=0;i--) 
		{
			gid2=gid2+gids.charAt(i);
		}
		gids = gid2;
		for (var i=gids.length - 1;i >=0; i--)
		{
			if (gids.substring(i,i + 1) == "1")
			{
				agid.push((i + 1).toString());
			}
		}
	}
	return agid;
}

//将分组数组转换成二进制分组值
function Array2gid(arr)
{
	if ($.inArray("0",arr) > -1)
	{
		return 0;
	}
	var tmpGid = 0;
	for (var i = 0; i < arr.length ; i++ )
	{
		var gid2 = (1 << parseInt(arr[i]) - 1);
		tmpGid = tmpGid | gid2;
	}
	return tmpGid;	
}

//检查是否在分组列表中存在该分组
function checkGrp(gid,gids)
{
	if (gids == "" || gids == null || gids == "0")
	{
		if (gid == "0")
			return true;
		else
			return false;
	}
	
	if (gid == "0")
	{
		if (gids == "" || gids == null || gids == "0")
			return ture;
		else
			return false;
	}
	var gids2 = parseInt(gids);
	var gid2 = (1 << parseInt(gid) - 1);
	return (gids2 | gid2) == gids2;
}

function joinGroup(gid,gids)
{
	if (gids=="0" || gids == "")
	{
		if (gid == "0")
			return "0";
		else
			return (1 << parseInt(gid) - 1);
	}
	var gids2 = parseInt(gids);
	var gid2 = (1 << parseInt(gid) - 1);
	return gids2 | gid2;
}
//gids 原先组;gid 需删除组
function delGroup(gid,gids)
{
	var arrGroup = toGIDs(parseInt(gids));
	var tmpGroup = $.grep(arrGroup,function(g,i){ return g != gid });
	if ( tmpGroup.length == 0 )
	{
		return 0;
	}
	var tmpGid = 0;
	for (var i = 0; i < tmpGroup.length ; i++ )
	{
		var gid2 = (1 << parseInt(tmpGroup[i]) - 1);
		tmpGid = tmpGid | gid2;
	}
	return tmpGid;	
}

function gotoManager(URL)
{
	var data = f_client_call(
	"G_MSG_CONTACT_MANAGER",URL);
}


function isEmail(strEmail)
{
	var regEx = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((\.[a-zA-Z0-9_-]{2,3}){1,2})$/;
	return regEx.test(strEmail);
}

function isMobileNum(n)
{
	var regEx = /^13[0-9]{9}$/;
	return regEx.test(n);
}

function isZipcode(n)
{
	var regEx = /^[1-9][0-9]{5}$/;
	return regEx.test(n);
}

function OpenMailCenter(param)
{
	var data = f_client_call(
	"S_MSG_OPENMAINWND",param);
}

function OpenPOPMail(param)
{
	var data = f_client_call(
	"S_MSG_OPEN",param);
}
/*已废弃
// 取所有经纪人信息
function ShowAllBroker()
{
	var data = f_client_call(
	"G_MSG_BROKER");
	return data;
}
// 添加经纪人信息
function AddBroker(param)
{	
	var data = f_client_call(
	"S_MSG_CHGBROKER",param);	
}
*/
//回执
function WriteReceipt(param)
{
	var data = f_client_call(
	"S_MSG_RECEIPT",param);
}
//获取当前视图对应商品信息
function getCurrStock()
{
	var data=f_client_call("G_View_PrevNextStock","O");
	return data;
}

function html_encode(str)     
{     
	var s = "";     
	if (str.length == 0) return "";     
	s = str.replace(/&/g, "&amp;");     
	s = s.replace(/</g, "&lt;");     
	s = s.replace(/>/g, "&gt;");     
	s = s.replace(/ /g, "&nbsp;");     
	s = s.replace(/\'/g, "&#39;");     
	s = s.replace(/\"/g, "&quot;");     
	s = s.replace(/\n/g, "<br>");     
	return s;     
}     

function html_decode(str)     
{     
	var s = "";     
	if (str.length == 0) return "";     
	s = str.replace(/&amp;/g, "&");     
	s = s.replace(/&lt;/g, "<");     
	s = s.replace(/&gt;/g, ">");     
	s = s.replace(/&nbsp;/g, " ");     
	s = s.replace(/&#39;/g, "\'");     
	s = s.replace(/&quot;/g, "\"");     
	s = s.replace(/<br>/g, "\n");     
	return s;     
} 



//字符串编码接口
function encodeString(str)
{
	var data = f_client_call(
	"S_SYS_Encode","0\n0\n" + str);
	return data;
}

//字符串解码接口
function decodeString(str)
{
	var data = f_client_call(
	"S_SYS_Encode","0\n1\n" + str);
	return data;
}

//打开邮件列表窗口
function openMailList(url)
{
	f_client_call(
	"S_MSG_OPENMSGLISTWND",url);
}