/**居中打开窗口。*/
function openWindow(url, title, width, height, attrs)
{
  var wh = getWindowSize();
  window.open(url, title, 
    'left=' + (wh.w - width) / 2 + ',top=' + (wh.h - height) / 2
      + ',height=' + height + ',width=' + width + (attrs ? "," + attrs : ""));
}

function getWindowSize()
{
  var winWidth = 0;
  var winHeight = 0;
  if (document.documentElement.clientWidth) 
  {
    winWidth = document.documentElement.clientWidth;
    winHeight = document.documentElement.clientHeight;
    if (winHeight < document.body.clientHeight)
    {
      winWidth = document.body.clientWidth;
      winHeight = document.body.clientHeight;
    }
  } 
  else if (document.body.clientWidth)
  {
    winWidth = document.body.clientWidth;
    winHeight = document.body.clientHeight;
    if (winHeight < document.documentElement.clientHeight)
    {
      winWidth = document.documentElement.clientWidth;
      winHeight = document.documentElement.clientHeight;
     }
  }
  else if(window.innerWidth)
  {
    winWidth = window.innerWidth;
    winHeight = window.innerHeight;
  }

  return {"w": winWidth, "h": winHeight};
}


function getStartXY(event, dWidth, dHeight, preoffset)
{
  var wh = getWindowSize();
  
  var x = event.clientX+5;
  if (null != preoffset)
  {
    x += preoffset.w;
  }
  if ((x + parseInt(dWidth)) > wh.w)
  {
     x -= dWidth;
  }
  var y = event.clientY;
  if (null != preoffset)
  {
    y += preoffset.h;
  }
  if ((y + parseInt(dHeight)) > wh.h)
  {
     y -= dHeight;
  }
  
  return {"x" : x, "y" : y};
}

function getOffset(obj)
{
   var opl = 0;
   var opt = 0;
   var pObj = obj.offsetParent;//检索并获取当前触发事件的对象的父对象
   while(pObj!=null && pObj != document.body)      
   {
       opl +=parseInt(pObj.offsetLeft) || 0;
       opt +=parseInt(pObj.offsetTop) || 0;   
       
       pObj = pObj.offsetParent;
   } 
   var oLeft = parseInt((obj.offsetLeft + opl) || 0);//检索与触发事件的对象相关的鼠标位置的水平坐标
   var oTop = parseInt((obj.offsetTop + opt) || 0);//检索与触发事件的对象相关的鼠标位置的垂直坐标 
  
   return {"l" : oLeft, "h" : oTop};  
}


/**
  下拉列表关联对象，按数组顺序逐级联动显示。
 objs：关联对象数组。格式为：{"对象ID":"关联对象当前值",...}。
*/
function onChangeSelectObj(objs, reset, keyName)
{ 
  var keyName = keyName || "default";
  var startOId = null; //标记开始关联的对象ID。
  var objArrs = selectObjs[keyName];
  for (var oId in objArrs)
  {
    var pValue = objs[oId];
    if (null == startOId && null == pValue)
    {
      continue;
    }
    startOId = oId;
    
    var pOptions = document.getElementById(oId).options;
    for (var j = pOptions.length; j > 0; j--)
    {
      pOptions[j] = null;
    }
    pOptions[0].selected = true;
    
    if (null != pValue)
    {
      var arrObj = objArrs[oId][pValue];
  
      if (null != arrObj)
      {
        for (var i = 0, j = 1; i < arrObj.length; i++, j++)
        {
          pOptions[j] = arrObj[i];
          pOptions[j].selected = 0 < arrObj[i].attributes["initSelected"].value.length;
        }
        
        if (null == reset || reset)
        {
          pOptions[0].selected = true;
        }
      }
    }
  }
}

var selectObjs = new Array();
function setSelectObjs(objIds, keyName)
{
  var keyName = keyName || "default";
  if (null == selectObjs[keyName])
  {
    selectObjs[keyName] = new Array();
  }
  
  var objArr = selectObjs[keyName];
  for (var i = 0; i < objIds.length; i++)
  {
    objArr[objIds[i]] = new Array();
  }
}

function addSelectOptions(arrName, pValue, dValue, dText, selected, keyName)
{
  var keyName = keyName || "default";
  if (null == selectObjs[keyName])
  {
    alert("请先通过setSelectObjs()绑定关联对象顺序数组。");
    return;
  }
  
  var arrObjs = selectObjs[keyName][arrName];
  if (null == arrObjs[pValue])
  {
    arrObjs[pValue] = new Array();
  }
  var o = document.createElement("option");
  o.value = dValue;
  o.text = dText;

  o.setAttribute("initSelected", selected || "");
  arrObjs[pValue][arrObjs[pValue].length] = o;
}

/**
 * 获取年月日格式的联动下拉列表。
 * required：是否必须。
 * privacy：是否有隐私控制。
 * privacyValue：隐私的控制值。
 */
function getDateSelect(dayObjId, required, privacy, privacyValue,isBack)
{  
  
  var date2 = document.getElementById(dayObjId).value;
  
  var date = (null != date2 && '' != date2) ? date2.split("-") : null;
  
  var year = null != date ? date[0] : null;
  var month = null != date ? date[1] : null;
  var day = null != date ? date[2] : null;
  if(month!=null){
    if(month.substring(0,1)=='0'){
      month=month.substring(1,2);
    }  
  }
  if(day!=null){
    if(day.substring(0,1)=='0'){
      day=day.substring(1,2);
    }
  }
  
  var endYear = new Date().getFullYear()-10;
  var startYear = endYear-50;
  var str = "<ul><li><select size='1' targetObj='" + dayObjId
    + "' id='yearSelect' name='yearSelect' onchange='verifyDaySelect();'>";
  for (var i = endYear-50; i < endYear; i++)
  {
    
   str += "<option value='" + i+"'";
   if(i==year){
     str +=" selected ";
   }
    str +=">" + i + "</option>";
  }
  str += "</select></li><li class='date_name'>&nbsp;&nbsp;年&nbsp;&nbsp;</li><li class='li1'><ul><li>";
  str += "<select size='1' id='monthSelect' name='monthSelect' onchange='verifyDaySelect();'>";
  for (var i = 1; i <= 12; i++)
  {
    str += "<option value='" + i + "'";
       if(i==month){
         str +=" selected ";
       }
           str +=">" + i + "</option>";
  }
  str += "</select></li><li class='date_name'>&nbsp;&nbsp;月&nbsp;&nbsp;</li><li class='li1'><ul><li>";
  str += "<select size='1' id='daySelect' name='daySelect' onchange='verifyDaySelect();'>";
  for (var i = 1; i <= 31; i++)
  {
    str += "<option value='" + i + "'";
    if(i==day){
     str +=" selected ";
   }  
         str += ">" + i + "</option>";
  
  }
  str += "</select></li><li class='date_name'>&nbsp;&nbsp;日" + (required ? "<span>*</span>" : "") + "</li>"
  + (privacy ? "<li>&nbsp;&nbsp;公开<input type='checkbox' id='privacyDate' name='privacySelect'"+(isBack ? "checked='checked'" : "")+ " value='" + privacyValue + "'>" : "")
  + "</li></ul>";
  return str;
}
function getUserDateSelect(dayObjId, privacy, privacyValue,isBack)
{  
  
  var date2 = document.getElementById(dayObjId).value;
  
  var date = (null != date2 && '' != date2) ? date2.split("-") : null;
  
  var year = null != date ? date[0] : null;
  var month = null != date ? date[1] : null;
  var day = null != date ? date[2] : null;
  if(month!=null){
    if(month.substring(0,1)=='0'){
      month=month.substring(1,2);
    }  
  }
  if(day!=null){
    if(day.substring(0,1)=='0'){
      day=day.substring(1,2);
    }
  }
  
  var endYear = new Date().getFullYear()-10;
  var startYear = endYear-50;
  var str = "<select size='1' targetObj='" + dayObjId
    + "' id='yearSelect' name='yearSelect' onchange='verifyDaySelect();'>";
  for (var i = endYear-50; i < endYear; i++)
  {
    
   str += "<option value='" + i+"'";
   if(i==year){
     str +=" selected ";
   }
    str +=">" + i + "</option>";
  }
  str += "</select>年";
  str += "<select size='1' id='monthSelect' name='monthSelect' onchange='verifyDaySelect();'>";
  for (var i = 1; i <= 12; i++)
  {
    str += "<option value='" + i + "'";
       if(i==month){
         str +=" selected ";
       }
           str +=">" + i + "</option>";
  }
  str += "</select>月";
  str += "<select size='1' id='daySelect' name='daySelect' onchange='verifyDaySelect();'>";
  for (var i = 1; i <= 31; i++)
  {
    str += "<option value='" + i + "'";
    if(i==day){
     str +=" selected ";
   }  
         str += ">" + i + "</option>";
  
  }
  str += "</select>日";
  str +=  (privacy ? "&nbsp;&nbsp;公开<input type='checkbox' id='privacyDate' name='privacySelect'"+(isBack ? "checked='checked'" : "")+ " value='" + privacyValue + "'>" : "");
  return str;
}

function verifyDaySelect()
{
  var year = document.getElementById('yearSelect').value;
  var month = document.getElementById('monthSelect').value - 1;
  var day = document.getElementById('daySelect').value;
  var date = new Date(year, month, day);
  while (date.getFullYear != year && 
      date.getMonth() != month && date.getDay() != day)
  {
    date = new Date(year, month, --day);
  }
  
  document.getElementById('daySelect').options[day-1].selected = true;
  
  changeSelectDate();
}

function changeSelectDate()
{
  var targetObj = document.getElementById('yearSelect').attributes["targetObj"].value;
  var year = document.getElementById('yearSelect').value;
  var month = document.getElementById('monthSelect').value;
  var day = document.getElementById('daySelect').value;
  
  document.getElementById(targetObj).value = year + "-" + month + "-" + day;
}

function addSelectOption(selectObjId, optionValue, optionText, defaultData)
{
    var selectObj = document.getElementById(selectObjId);
    if (null == selectObj)
    {
        return null;
    }
    
    var optionObj = document.createElement("option");
    optionObj.value = optionValue;
    optionObj.text = optionText;
    selectObj.options[selectObj.options.length] = optionObj;
    optionObj.selected = (optionValue == defaultData);
    return optionObj.toString();
}

/**
 * 是否为空
 */
function isBlack(obj) {
  if(obj==null || obj.length<=0) {
    return true;
  }else {
    return false;
  }
}
/**
 * 是否是规范的数字
 */
function isValidNum(obj) {
  if(!isBlack(obj)) {
    if(!isNaN(obj)) {
      return true
    }
  }
  return false;
}
/**
 *iframe高度自增
*/
function iframeAutoFit()   
{   
    try  
    {   
        if(window!=parent)   
        {   
            var a = parent.document.getElementsByTagName("IFRAME");   
            for(var i=0; i<a.length; i++) //author:meizz   
            {   
                if(a[i].contentWindow==window)   
                {   
                    var h1=0,w1=0, h2=0,w2=0, d=document, dd=d.documentElement;   
                    a[i].parentNode.style.height = a[i].offsetHeight +"px";    
                    a[i].style.height = "10px";    
                    if(dd && dd.scrollHeight) h1=dd.scrollHeight;   
                    if(dd && dd.scrollWidthHeight) h2=dd.scrollWidth;   
                    if(d.body) h2=d.body.scrollHeight;   
                    if(d.body) w2=d.body.scrollWidth;   
                    var h=Math.max(h1, h2);   
                    var w = Math.max(w1,w2);   
                    if(document.all) {h += 4;}   
                    if(window.opera) {h += 1;}   
                    a[i].style.height = a[i].parentNode.style.height = h +"px";     
                }   
            }   
        }   
    }   
    catch (ex){}   
    if(typeof(_iTimeoutId)=="undefined" || !_iTimeoutId){
      return;
    }
  //有的iframe里面用了setTimeout 定时功能 定义ID _iTimeoutId 所以如果存在则清除
    clearTimeout(_iTimeoutId);
} 
/**
服务端返回消息提示
*/
function showTip(msg){   
  var _width=890;
  var tip_msg="<div id=\"tip_prompt1\" style=\"width:"+_width+"px;border:1px solid #FFBA43; background:#FDFFCE;";
  tip_msg+="padding:3px;margin-bottom:0px;margin-left:auto;margin-right:auto;\">";
  tip_msg+="<div style=\"font-size:14px;margin-bottom:2px;\">";
  tip_msg+="<img src=\"/images/tip_ok.gif\" align=\"absmiddle\" />";
  tip_msg+="&nbsp;"+msg+"</div>";
  tip_msg+="</div>";
 document.write(tip_msg);
 var divObj=document.getElementById("tip_prompt1");
 var tipInterval=setInterval(function(){
  divObj.parentNode.removeChild(divObj);
  clearInterval(tipInterval);
 },4000);
}
/**
 *在页面创建div ，然后附加到指定对象上 
 */
function createDivShow(obj,msg,iframe,id){
  var pdiv=document.createElement("DIV");
  pdiv.id="tip_prompt1_+"+id+"";
  if(document.all) {
    pdiv.style.width="796px";
  }else {
    pdiv.style.width="788px";
  }
  pdiv.style.border="1px solid #FFBA43";
  pdiv.style.background="#FDFFCE";
  pdiv.style.padding="5px";
  pdiv.style.marginBottom="2px";
  var ndiv=document.createElement("DIV");
  ndiv.style.fontSize="14px";
  ndiv.style.marginBottom="2px";
  ndiv.style.textAlign="left";
  ndiv.innerHTML="<img src=\"/images/tip_ok.gif\" align=\"absmiddle\" />&nbsp;"+msg+"";
  pdiv.appendChild(ndiv);
  obj.appendChild(pdiv);
  id=setInterval(function(){
   pdiv.parentNode.removeChild(pdiv);
   clearInterval(id);
   if(iframe) {
     iframeAutoFit();
   }
  },4000);
}
function showTopMsg(bandTblId, msg, oked)
{
  if (null == document.getElementById("topMsgs"))
  {
    var et = document.getElementById(bandTblId).insertRow(0);
    var ed = et.insertCell(-1);
    ed.colSpan = "2";
    ed.className = null == oked ? "errorTips" : oked ? "okMsg" : "noMsg";
    ed.width = "100%";
    ed.innerHTML = "<span id='topMsgs' class='errorMsg'></span>";
  }
  document.getElementById("topMsgs").innerHTML = msg;
}
 
function hiddenTopMsg(bandTblId)
{
  if (null == document.getElementById("topMsgs"))
  {
    return;
  }
  
  document.getElementById(bandTblId).deleteRow(0);
}

/**
 * 定时算输入字数的控制类
 * @param objText  内容框ID
 * @param showSpan 显示字数元素 ID
 * @param innerHtml 提示内容
 * @return
 */
var msgContent=function(objText,showSpan,innerHtml){
  this._obj=document.getElementById(objText);
  this._showObj=document.getElementById(showSpan);
  this._innerHtml=innerHtml;
}
msgContent.prototype={
  update:function(){
    if(this._obj == null || this._showObj== null){
      return ;
    }
    if(this._last==this._obj.value) return;
    this._last=this._obj.value;
    var length=this._obj.value.length;
    if(this._innerHtml == null || this._innerHtml.length == 0) {
      return ;
    }
    this._showObj.innerHTML=this._innerHtml.replace("{0}",length).replace("{1}",(200-length));
  }
}

/**
 * 解决thickbox 在IE和firefox下不同宽高的问题
 */
function buildHref(href,width,height) {
  href=href+"&width="+width+"&height="+height+"";
  return href;
}

function _login() {
  var url=buildHref("/user/login.htm?keepThis=true&TB_iframe=true&modal=true",360,230);
  self.tb_show("速比登录",url,"thickbox");
}
function _params_login(type,value) {
  var url=buildHref("/user/login.htm?returnType="+type+"&returnValue="+value+"&keepThis=true&TB_iframe=true&modal=true",360,230);
  self.tb_show("速比登录",url,"thickbox");
}
function _register() {
  var url=buildHref("/user/register.htm?keepThis=true&TB_iframe=true&modal=true",400,330);//320
  self.tb_show("用户注册",url,"thickbox");
}
/**公共*/
function showGgMessage(message){
  var url=buildHref("/twitter/toAnnounce.htm?number="+message+"&modal=true",400,200);
  tb_show("公告",url,"thickbox");  
}
/**货盘竞价*/
function _pallet_bit(consSeq){
  var url=buildHref("/admin/crm/toBit.htm?consSeq="+consSeq+"&keepThis=true&TB_iframe=true&modal=true",650,228)
  self.tb_show('',url, "thickbox"); 
}
/**发布上传小广播 运件表 船期**/
function _showTwitter() {
  var url=buildHref("/admin/twitter/toTwitter.htm?act=twitter&keepThis=true&TB_iframe=true&modal=true",612,233);
  self.tb_show("我要广播",url,"thickbox");
}
function _SailingDate(source) {
  var url=buildHref("/admin/twitter/toTwitter.htm?act=cq&source="+source+"&keepThis=true&TB_iframe=true&modal=true",525,225);
  self.tb_show("上传船期",url,"thickbox");
}
function _FreightPrice(source) {
  var url=buildHref("/admin/twitter/toTwitter.htm?act=yj&source="+source+"&keepThis=true&TB_iframe=true&modal=true",525,250);
  self.tb_show("上传运价表",url,"thickbox");
}
/**
 * 显示货盘
 */
function _lookTrayDiv(consSeq) {
  _pallet_bit(consSeq);
}
/**区域选择开始*/
function removeUserSelectOption(selectObjId,text)
{
  document.getElementById(selectObjId).options.length=0;     
  addSelectOption(selectObjId,'',text)
} 

function getSelectUserCity()
{
  document.getElementById("usercity").onclick=null;
  removeUserSelectOption('usercounty','请选择');
  if(document.getElementById("userprovince").value!="")
  {
    getCityInfo.getCityInfoAll(document.getElementById("userprovince").value,getUserCityDataHander);
  }
  
}

 function getUserCityDataHander(data)
 {
   for(var i=0;i<data.length;i++)
   {
    addSelectOptions("usercity", data[i].provinceId, data[i].id, data[i].name, false);

    }
   onChangeSelectObj({
     "usercity": document.getElementById("userprovince").value,
     "usercounty":document.getElementById("usercity").value}, false);
  }

 function onChangeSelectUserCity()
 {
     removeUserSelectOption('usercity','请选择');
     removeUserSelectOption('usercounty','请选择');
   
   if(document.getElementById("userprovince").value!="")
   {
     getCityInfo.getCityInfoAll(document.getElementById("userprovince").value,userCityDataHander);
   }
 
  }

 function onChangeSelectUSerCounty(params)
 {
   if("Y"==params)
   {
     document.getElementById("usercounty").onclick=null;
   }
   if(document.getElementById("usercity").value!="")
   {
     getCityInfo.getCountyInfoAll(document.getElementById("usercity").value,userCountyDataHander);
   }
  }
/**区域选择结束*/
 
/**关键字高亮显示 多个DIV 的话用  "div1,div2,div3,divn"**/
function keyWordLight(showId,keyWord) {
  var arr=new Array();
  if(showId.indexOf(",") != -1){
    arr=showId.split(",");
  }else{
    arr.push(showId);
  }
  for(var i=0;i<arr.length;i++){  
    $('#'+arr[i]+'').highlight(keyWord); 
  }
}

/**限制非数字的输入**/
function clearNoNum(obj)
{
   //先把非数字的都替换掉，除了数字和.
   obj.value = obj.value.replace(/[^\d.]/g,"");
   //必须保证第一个为数字而不是.
   obj.value = obj.value.replace(/^\./g,"");
   //保证只有出现一个.而没有多个.
   obj.value = obj.value.replace(/\.{2,}/g,".");
   //保证.只出现一次，而不能出现两次以上
   obj.value = obj.value.replace(".","$#$").replace(/\./g,"").replace("$#$",".");
}

/**js 时间解析**/
sunbJsonDate={
	getNormalDate:function(time){
		var _tmp_date=new Date(time);
		return _tmp_date.getFullYear()+"-"+((_tmp_date.getMonth()+1)>9?(_tmp_date.getMonth()+1):"0"+(_tmp_date.getMonth()+1))+"-"+(_tmp_date.getDate()>9?_tmp_date.getDate():"0"+_tmp_date.getDate())+" "+(_tmp_date.getHours()>9?_tmp_date.getHours():"0"+_tmp_date.getHours())+":"+(_tmp_date.getMinutes()>9?_tmp_date.getMinutes():"0"+_tmp_date.getMinutes());
	},
	getFullNormalDate:function(time){
    var _tmp_date=new Date(time);
    return _tmp_date.getFullYear()+"-"+((_tmp_date.getMonth()+1)>9?(_tmp_date.getMonth()+1):"0"+(_tmp_date.getMonth()+1))+"-"+(_tmp_date.getDate()>9?_tmp_date.getDate():"0"+_tmp_date.getDate())+" "+(_tmp_date.getHours()>9?_tmp_date.getHours():"0"+_tmp_date.getHours())+":"+(_tmp_date.getMinutes()>9?_tmp_date.getMinutes():"0"+_tmp_date.getMinutes())+":"+(_tmp_date.getSeconds()>9?_tmp_date.getSeconds():"0"+_tmp_date.getSeconds());
  },
  getClickStatus:function(time){
  	if(time==null){
       return;
    }
     var _c_time=new Date().getTime();
     var _hours=parseInt(parseInt(_c_time-time)/1000/60);
     if (0 > _hours)
	   {
	      return "S";
	   }
	   if (1 > _hours / 60)
	   {
	      return "M";
	   }
	   _hours = _hours / 60;
	   if (1 > _hours / 24)
	   {
	      return "H";
	   }
    return "D";
  },
  getClick:function(time){
  	if(time==null){
       return;
    }
     var _c_time=new Date().getTime();
     var _hours=parseInt(parseInt(_c_time-time)/1000/60);
     if (0 > _hours)
     {
        return "0";
     }
     if (1 > _hours / 60)
     {
        return _hours + 1;
     }
     _hours = parseInt(_hours / 60);
     if (1 > _hours / 24)
     {
        return _hours + 1;
     }
  },
  getBroadcastTime:function(time){
  	 var _status=sunbJsonDate.getClickStatus(time);
  	 var _click=sunbJsonDate.getClick(time);
  	 var _timeInfo=sunbJsonDate.getNormalDate(time);
  	 if("S" == _status){
  	 	 _timeInfo = "刚刚发送的";
  	 }else if("M" == _status){
  	 	 _timeInfo = "约 "+_click+" 分钟前";
  	 }else if("H" == _status){
  	 	 _timeInfo = "约 "+_click+" 小时前";
  	 }
  	 return _timeInfo;
  }
}