//============= global =============
function jumpTo(src) {
  window.location = src;
}

function defaultInputVal(targetId, defaultVal, defaultClass) {
  $("#" + targetId).bind({
    focus: function() {
      var keyVal = $.trim($("#" + targetId).val());
      if (keyVal == defaultVal) {
        $("#" + targetId).val("");
      }
      $("#" + targetId).removeClass(defaultClass);
    },
    blur: function() {
      var keyVal = $.trim($("#" + targetId).val());
      if (keyVal == "" || keyVal == defaultVal) {
        $("#" + targetId).val(defaultVal);
        $("#" + targetId).addClass(defaultClass);
      }
      if (!keywordPopupFocus) {
        clearNames();
      }
    }
  });
}

var _showActivityRemainTimeD = null;
function showActivityRemainTime(endMS, nowMS, countMsgId) {
  var showHtml = "<strong  id=\"" + countMsgId + "RemainD\">?</strong>天<strong id=\"" + countMsgId
      + "RemainH\">?</strong>时<strong id=\"" + countMsgId + "RemainM\">?</strong>分<strong id=\""
      + countMsgId + "RemainS\">?</strong>秒";
  var now = new Date();
  if (_showActivityRemainTimeD == null) {
    _showActivityRemainTimeD = now.getTime() - nowMS;
  }
  document.getElementById(countMsgId).innerHTML=showHtml;
  var nMS= endMS - now.getTime() + _showActivityRemainTimeD;
  var nD=Math.floor(nMS/(1000 * 60 * 60 * 24));
  var nH=Math.floor(nMS/(1000*60*60)) % 24;
  var nM=Math.floor(nMS/(1000*60)) % 60;
  var nS=Math.floor(nMS/1000) % 60;
  var nMS=Math.floor(nMS/100) % 10;
  if(nD>= 0){
    document.getElementById(countMsgId + "RemainD").innerHTML=nD;
    document.getElementById(countMsgId + "RemainH").innerHTML=nH;
    document.getElementById(countMsgId + "RemainM").innerHTML=nM;
    document.getElementById(countMsgId + "RemainS").innerHTML=nS + "." + nMS;
  } else {
    document.getElementById(countMsgId).innerHTML="已结束";
  }
  setTimeout("showActivityRemainTime("+endMS+", "+nowMS+", '"+countMsgId+"')",100);
}

//============= shoppingcart =============
function changeCartAmount(cid, cnt) {
  
  var pattern = /^[0-9]*[1-9][0-9]*$/;
  var amountStr = $.trim(cnt);
  var amount;
  
  if (pattern.exec(amountStr) == null) {
    showAlert("商品数量修改失败.商品数量只能为数字而且必须大于0.", 0);
    return false;
  } else {
    amount = parseInt(amountStr);
  }

  if (amountStr <= 0 || amountStr>999) {
    showAlert("一次购买数量介于0-999之间！", 0);
    return false;
  } 

  $.ajax({
    url: "/shoppingCart.do?m=addOrUpdateItem&type=1",
    type : "POST",
    data : {"id":cid, "amount":amount},
    success : function(m) {
      if (m.flag == 0 || m.flag == 1) {
        refreshMiniShopCart();
        showAlert("商品成功添加到购物车！\n 购物车共有" + m._cartInfo.sumCount + "种商品，合计：" + m._cartInfo.sumPriceText + "元");
      } else {
        showAlert(m.msg, 0);
     }
    },
    error : function() {
      showAlert("服务器错误.", 0);
    }
  });
  return true;
}
//============= header =============
function writeRandomHeaderBackRight() {
  var html = "<img width=\"178\" height=\"65\" src=\"/static/public_content/header/header_back_right_";
  html += Math.floor(Math.random()*4) + 1;
  html += ".jpg\"/>";
  document.write(html);
}

function jumpToLogin() {
  var url = "";
  var loc = "" + window.location;
  var reg=new RegExp("&","g");
  loc = loc.replace(reg,"@");
  if (loc.indexOf("login") < 0 && loc.indexOf("reg") < 0) {
    url = "?tourl='" + loc + "'";
  }
	setTimeout(function(){window.location.href="/login.jsp" + url;},10);
	return true;
}

function jumpToReg() {
  var url = "";
  var loc = "" + window.location;
  var reg=new RegExp("&","g");
  loc = loc.replace(reg,"@");
  if (loc.indexOf("login") < 0 && loc.indexOf("reg") < 0) {
    url = "?tourl='" + loc + "'";
  }
	setTimeout(function(){window.location.href="/reg.jsp" + url;},10);
}

function jumpToIndex() {
  window.location="/";
}

function logout(){
  showConfirm("您确定要注销吗？", function(flag){
    if (flag) {
      window.location.href = "/member/memberCenter.do?m=removeMember";
    }
  });
}

var searchTypeArray = new Array();
searchTypeArray[2] = new Array("孕妇","儿童","易上火者","健身一族","高血压患者","宅一族","瘦身一族","便秘人群","熬夜人群");
searchTypeArray[3] = ["温性","平性","凉性","寒性","热性"];
searchTypeArray[4] = ["50元以下","50~100","100~200","200~500","500~1000","1000以上"];
var hotArray = new Array("礼盒","零食","大唐西域");
var searchDefaultWords = "请输入关键字";
var keyCode = 0;
var keywordPopupFocus = false;

function changeSearchType(typeId,keyword) {
  var html = "";
  if (typeId == 1) {
    html = "<input id=\"searchKeyword\" class=\"box\"  maxlength=\"10\" type=\"text\" value=\"";
    if (keyword == null) {
      html += searchDefaultWords;
    } else {
      html += keyword;
    }
    html += "\"/>";
    $("#searchType").val(typeId);
  } else if (typeId == 2) {
    html = makeSearchKeywordOption(2, keyword);
    $("#searchType").val(typeId);
  } else if (typeId == 3) {
    html = makeSearchKeywordOption(3, keyword);
    $("#searchType").val(typeId);
  } else if (typeId == 4) {
    html = makeSearchKeywordOption(4, keyword);
    $("#searchType").val(typeId);
  }
  $("#keyword_span").html(html);
  //填热搜词
  var ram = parseInt(Math.random()*3);
  var keyValue = $.trim($("#searchKeyword").val());
  if (keyValue == null || keyValue==searchDefaultWords) {
    $("#searchKeyword").val(hotArray[ram]);
    $("#searchKeyword").attr("class", "box defaultKey");
  }
  
  $("#searchKeyword").bind({
    focus: function() {
      var searchKeywordVal = $.trim($("#searchKeyword").val());
      //如果是热搜及默认就清空
      for (var k = 0; k<hotArray.length; k++) {
        if (searchKeywordVal == hotArray[k]) {
          $("#searchKeyword").val("");
        }
      }
      if (searchKeywordVal == searchDefaultWords) {
        $("#searchKeyword").val("");
      }
      $("#searchKeyword").attr("class", "box");
    },
    blur: function() {
      var searchKeywordVal = $.trim($("#searchKeyword").val());
      if (searchKeywordVal == "" || searchKeywordVal == searchDefaultWords) {
        //$("#searchKeyword").val(searchDefaultWords);  //如果不要热搜了就把这个换回来
        $("#searchKeyword").val(hotArray[ram]);
      }
      $("#searchKeyword").attr("class", "box defaultKey");
      if (!keywordPopupFocus) {
        clearNames();
      }
    },
    keydown: function(e) {
      if (e.keyCode == 13) {
        searchCommodity();
      }
    },
    keyup: function() {
      showKeyword();
    }
  });
  
}

function makeSearchKeywordOption(typeId, selectedOption){
  var html = "";
  html += "<select id=\"searchKeyword\" class=\"type\">";
  for(var i = 0; i<searchTypeArray[typeId].length; ++i) {
    var value;
    if (typeId == 4) {//价格
      value = i + 1;
    } else {
      value = searchTypeArray[typeId][i] ;
    }
    html += "<option value=\"" + value + "\"";
    if (value == selectedOption) {
      html += "selected=\"selected\"";
    }
    html += ">" + searchTypeArray[typeId][i] + "</option>";
  }
  html += "</select>";
  return html;
}

function searchCommodity(typeId, keyword) {
  if (typeId == null) {
    typeId = $("#searchType").val();
  }
  if (keyword == null) {
    keyword = $.trim($("#searchKeyword").val());
  }
  window.location="/list.do?type=" + typeId + "&searchKeyword=" + encodeURI(encodeURI(keyword));
}

document.onkeydown = function (e) {
  var focusId = document.activeElement.id;
   e = window.event || e;
  keyCode = e.keyCode ? e.keyCode : e.which ? e.which : e.charCode;
  if (focusId == "searchKeyword") {
    switch(keyCode) {
      case 38:
        currentLine--;
        changeItem();
        break;
      case 40:
        currentLine++;
        changeItem();
        break;
      default :
        break;
    }
  } else if (keyCode == 13 &&  (focusId == "pwd" || focusId== "auto")){//登录监听
		  //dologin(); //回车键与弹出层冲突
	}
};

function searchCreateHttp() {
  if (window.ActiveXObject)
    return new ActiveXObject("Microsoft.XMLHTTP");
  else if(window.XMLHttpRequest)
    return new XMLHttpRequest();
  else if(Msxml2.XMLHttp)
    return new ActiveXObject("Msxml2.XMLHttp");
  else {
    showAlert("对不起，本系统不支持您的浏览器。建议使用IE、FireFox等主流浏览器。", 0);
  }
}
function showKeyword() {
  if(keyCode!=38 && keyCode!=40) {
    inputField = document.getElementById("searchKeyword");
    completeTable = document.getElementById("keyword_popup_table");
    completeDiv = document.getElementById("keyword_popup");
    completeBody = document.getElementById("keyword_popup_body");
    var key=inputField.value;
    key = encodeURI(encodeURI(key));
    if(key == "") return;
    var xmlrequest = searchCreateHttp();
    xmlrequest.open("post","/list.do?m=querykey&key="+key);
    xmlrequest.onreadystatechange=function() {
      if(xmlrequest.readyState == 4) {
        if (xmlrequest.status == 200) {
          var root = xmlrequest.responseXML.documentElement;
          setNames(root);
        } else {
          showAlert("与后台服务器连接失败。错误代码：" + xmlrequest.status + ".", 0);
          return false;
        }
      }
    }
    xmlrequest.send(null);
  }
}
//生成与输入内容匹配行
function setNames(root) {
  if(root == null) {
    clearNames();
    return;
  }
  clearNames();
  setOffsets();
  var tr, td, value;
  // 解析xml结构，遍找出keyword节点数用来代替s
  var keywordRows = root.childNodes;
  for (var i = 0; i < keywordRows.length; i++) {
    var nextNode = keywordRows[i];
    // 如果节点是element类型
    if(nextNode.nodeType === 1) {
      tr = document.createElement("tr");
      td = document.createElement("td");
      td.style.fontSize='12px';
      td.onmouseout = function() {this.style.backgroundColor='';this.style.fontSize='12px';this.style.color='#171717';};
      td.onmouseover = function() {this.style.backgroundColor='#ddefff';this.style.fontSize='12px';this.style.color='#666666';};
      td.onclick = function() {
        completeField(this);
      };
      td.pop="T";
      var name = nextNode.getAttribute("name");
      value = document.createTextNode(name);
      td.appendChild(value);
      tr.appendChild(td);
      document.getElementById("keyword_popup_body").appendChild(tr);
    }
  }
}

//填写输入框
function completeField(cell) {
  inputField.value = cell.firstChild.nodeValue;
  clearNames();
}
//清除自动完成行
function clearNames() {
  completeBody = document.getElementById("keyword_popup_body");
  var ind = completeBody.childNodes.length;
  for (var i = ind - 1; i >= 0 ; i--) {
    completeBody.removeChild(completeBody.childNodes[i]);
  }
  completeDiv = document.getElementById("keyword_popup");
  completeDiv.style.border = "none";
  document.getElementById("searchKeyword").disabled=false;
  currentLine = -1;
}
//设置显示位置
function setOffsets() {
  completeTable.style.width = inputField.offsetWidth - 3; + "px";
  var left = 0;
  var top = 24;
  completeDiv.style.border = "1px solid #797979";
  completeDiv.style.left = left + "px";
  completeDiv.style.top = top + "px";

  if(!window.event){
    completeTable.style.width = "224px";
    completeDiv.style.posLeft = left;
    completeDiv.style.posTop = top;
  }
}
function calculateOffset(field, attr) {
  var offset = 0;
  while(field) {
    offset += field[attr];
    field = field.offsetParent;
  }
  return offset;
}
//改变选择项目
function changeItem() {
  var it;
  if(document.all) {
    it = document.getElementById("keyword_popup_table").children[0];
  }
  else {
    it = document.getElementById("keyword_popup_table");
  }
  for (i=0; i<it.rows.length; i++) {
   it.rows[i].childNodes[0].style.background = "";
  }
  if (currentLine < 0) {
    currentLine = it.rows.length-1;
  }
  if (currentLine == it.rows.length) {
    currentLine = 0;
  }
   it.rows[currentLine].childNodes[0].style.background = "#ddefff";
   document.getElementById("searchKeyword").value=it.rows[currentLine].childNodes[0].innerHTML;
}
//============= sort_menu =============
function jumpTo(e) {
  window.location = e;0
}
//热搜跳转
function hot_Search(keyword) {
  keyword = encodeURI(encodeURI(keyword));
  window.location.href = "/list.do?type=1&searchKeyword="+keyword;
}

