/* *
 * 处理会员登录的反馈信息
 */
function signInResponse(result)
{
  toggleLoader(false);

  var done    = result.substr(0, 1);
  var content = result.substr(2);

  if (done == 1)
  {
    document.getElementById('member-zone').innerHTML = content;
  }
  else
  {
    alert(content);
  }
}

function validate_id(obj)
{
  /*if (obj.error > 0)
    {
      $('ecs_citizen_id').innerHTML = obj.message.replace("%s", $("citizen_id").value);
      $('ecs_citizen_id').style.color = "red";
    }
    else
    {*/
     setNotice("ecs_citizen_id", citizen_id + input_ok);
     document.getElementById('ecs_citizen_id').style.color = "#009900";
     error = false;    
   // }
}


/* *
 * 截取小数位数
 */
function advFormatNumber(value, num) // 四舍五入
{
  var a_str = formatNumber(value, num);
  var a_int = parseFloat(a_str);
  if (value.toString().length > a_str.length)
  {
    var b_str = value.toString().substring(a_str.length, a_str.length + 1);
    var b_int = parseFloat(b_str);
    if (b_int < 5)
    {
      return a_str;
    }
    else
    {
      var bonus_str, bonus_int;
      if (num == 0)
      {
        bonus_int = 1;
      }
      else
      {
        bonus_str = "0."
        for (var i = 1; i < num; i ++ )
        bonus_str += "0";
        bonus_str += "1";
        bonus_int = parseFloat(bonus_str);
      }
      a_str = formatNumber(a_int + bonus_int, num)
    }
  }
  return a_str;
}

function formatNumber(value, num) // 直接去尾
{
  var a, b, c, i;
  a = value.toString();
  b = a.indexOf('.');
  c = a.length;
  if (num == 0)
  {
    if (b != - 1)
    {
      a = a.substring(0, b);
    }
  }
  else
  {
    if (b == - 1)
    {
      a = a + ".";
      for (i = 1; i <= num; i ++ )
      {
        a = a + "0";
      }
    }
    else
    {
      a = a.substring(0, b + num + 1);
      for (i = c; i <= b + num; i ++ )
      {
        a = a + "0";
      }
    }
  }
  return a;
}

function hash(string, length)
{
  var length = length ? length : 32;
  var start = 0;
  var i = 0;
  var result = '';
  filllen = length - string.length % length;
  for(i = 0; i < filllen; i++)
  {
    string += "0";
  }
  while(start < string.length)
  {
    result = stringxor(result, string.substr(start, length));
    start += length;
  }
  return result;
}

function stringxor(s1, s2)
{
  var s = '';
  var hash = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
  var max = Math.max(s1.length, s2.length);
  for(var i=0; i<max; i++) 
  {
    var k = s1.charCodeAt(i) ^ s2.charCodeAt(i);
    s += hash.charAt(k % 52);
  }
  return s;
}

var evalscripts = new Array();
function evalscript(s)
{
  if(s.indexOf('<script') == -1) return s;
  var p = /<script[^\>]*?src=\"([^\>]*?)\"[^\>]*?(reload=\"1\")?(?:charset=\"([\w\-]+?)\")?><\/script>/ig;
  var arr = new Array();
  while(arr = p.exec(s)) appendscript(arr[1], '', arr[2], arr[3]);
  return s;
}

function $(id)
{
    return document.getElementById(id);
}

function appendscript(src, text, reload, charset) 
{
  var id = hash(src + text);
  if(!reload && in_array(id, evalscripts)) return;
  if(reload && $(id))
  {
    $(id).parentNode.removeChild($(id));
  }
  evalscripts.push(id);
  var scriptNode = document.createElement("script");
  scriptNode.type = "text/javascript";
  scriptNode.id = id;
  //scriptNode.charset = charset;
  try 
  {
    if(src) 
    {
      scriptNode.src = src;
    }
    else if(text)
    {
      scriptNode.text = text;
    }
    $('append_parent').appendChild(scriptNode);
  } 
  catch(e)
  {}
}

function in_array(needle, haystack)
{
  if(typeof needle == 'string' || typeof needle == 'number')
  {
    for(var i in haystack)
    {
      if(haystack[i] == needle)
      {
        return true;
      }
    }
  }
  return false;
}

function doane(event)
{
  e = event ? event : window.event;
  if(is_ie)
  {
    e.returnValue = false;
    e.cancelBubble = true;
  } 
  else if(e)
  {
    e.stopPropagation();
    e.preventDefault();
  }
}

/* *
 * 处理会员登录的反馈信息
 */
var isbbsuser = false;
function signInResponse(result)
{
  toggleLoader(false);

  var done    = result.substr(0, 1);
  var content = result.substr(2);

  if (done == 1)
  {
    document.getElementById('member-zone').innerHTML = content;
  }
  else
  {
    alert(content);
  }
}

function autoComplete(obj, hidden, url, callback)
{
  this.borderStyle = '1px solid #000';
  this.highlight = '#000080';
  this.highlightText = '#FFF';
  this.background = '#FFF';
  this.params = '';

  var textbox = obj;
  var hidden = hidden;
  var oldValue = '';
  var flag = false;
  var url = url;

  this.call = function()
  {
    if (flag)
    {
      flag = false;
      return;
    }

    if (url == '')
    {
      return;
    }

    if (oldValue != '' && oldValue == textbox.value)
    {
      return;
    }
    else
    {
      oldValue = textbox.value;
    }

    if (textbox.value != '')
    {
      Transport.run(url, "arg=" + textbox.value, this.show, 'get', 'json');
    }
    else
    {
      var layer = document.getElementById('AC_layer');

      if (layer)
      {
        layer.style.display = 'none';
      }
    }
  }

  var _ac = this;

  this.show = function(result)
  {
    var obj = result;
    var layer = null;

    if (document.getElementById('AC_layer'))
    {
      layer = document.getElementById('AC_layer');
      layer.innerHTML = '';
      layer.style.display = 'block';
    }
    else
    {
      layer = document.createElement('DIV');
      layer.id = 'AC_layer';
      document.body.appendChild(layer);
    }

    pos = getPosition();

    layer.style.left = pos.x + 'px';
    layer.style.top = pos.y + 'px';
    layer.style.width = textbox.clientWidth + 'px';
    layer.style.position = 'absolute';
    layer.style.border = _ac.borderStyle;
    layer.style.background = _ac.background;

    createMenuItem(obj, layer);
    textbox.onkeyup = function(e)
    {
      var evt = fixEvent(e);

      if (evt.keyCode == '38')
      {
        highlightItem('prev');
      }

      if (evt.keyCode == '40')
      {
        highlightItem('next');
      }
    }

    textbox.onblur = function()
    {
      var layer = document.getElementById('AC_layer');

      if (layer)
      {
        layer.style.display = 'none';
      }
    }
  }

  var createMenuItem = function(obj, layer)
  {
    var lst = document.createElement('UL');

    lst.style.listStyle = 'none';
    lst.style.margin = '0';
    lst.style.padding = '1px';
    lst.style.display = 'block';

    for (i = 0; i < obj.length; i ++ )
    {
      if (typeof(obj[i].key) === "undefined" || typeof(obj[i].val) === "undefined")
      {
        throw new Error('Error data.');
        break;
      }
      else
      {
        var listItem = document.createElement('LI');

        listItem.id = obj[i].key;
        listItem.innerHTML = obj[i].val;
        listItem.title = obj[i].val;
        listItem.style.cursor = "default";
        listItem.style.pointer = "default";
        listItem.style.margin = '0px';
        listItem.style.padding = '0px';
        listItem.style.display = 'block';
        listItem.style.width = '100%';
        listItem.style.height = '16px';
        listItem.style.overflow = 'hidden';

        listItem.onmouseover = function(e)
        {
          for (i = 0; i < this.parentNode.childNodes.length;
          i ++ )
          {
            this.parentNode.childNodes[i].style.backgroundColor = '';
            this.parentNode.childNodes[i].style.color = '';
          }
          this.style.backgroundColor = _ac.highlight;
          this.style.color = _ac.highlightText;

          assign(this);
        }
        ;
        listItem.onmouseout = function(e)
        {
          this.style.backgroundColor = '';
          this.style.color = '';
        }
        ;

        lst.appendChild(listItem);
      }
    }

    layer.appendChild(lst);
  }

  var getPosition = function()
  {
    var obj = textbox;
    var pos =
    {
      "x" : 0, "y" : 0
    }

    pos.x = document.body.offsetLeft;
    pos.y = document.body.offsetTop + textbox.clientHeight + 3;

    do
    {
      pos.x += obj.offsetLeft;
      pos.y += obj.offsetTop;

      obj = obj.offsetParent;
    }
    while (obj.tagName.toUpperCase() != 'BODY')

    return pos;
  }

  var fixEvent = function(e)
  {
    return (typeof e == "undefined") ? window.event : e;
  }

  var highlightItem = function(direction)
  {
    var layer = document.getElementById('AC_layer');
    var list = null;
    var item = null;

    if (layer)
    {
      list = layer.childNodes[0];
    }

    if (list)
    {
      for (i = 0; i < list.childNodes.length; i ++ )
      {
        if (list.childNodes[i].style.backgroundColor == _ac.highlight)
        {
          if (direction == 'prev')
          {
            item = (i > 0) ? list.childNodes[i - 1] : list.lastChild;
          }
          else
          {
            item = (i < list.childNodes.length) ? list.childNodes[i + 1] : list.childNodes[0];
          }
        }

        list.childNodes[i].style.backgroundColor = '';
        list.childNodes[i].style.color = '';
      }
    }

    if ( ! item)
    {
      item = (direction == 'prev') ? list.lastChild : list.childNodes[0];
    }

    item.style.backgroundColor = _ac.highlight;
    item.style.color = _ac.highlightText

    assign(item);
  }

  var assign = function(item)
  {
    flag = true;
    textbox.value = item.innerHTML;

    if (typeof hidden == 'object')
    {
      hidden.value = item.id;
    }

    if (typeof callback == 'function')
    {
      callback.call(_ac, item.id, textbox.value);
    }
  }

  var debug = function()
  {
    // document.getElementById('foo').innerHTML = textbox.value;
  }
}

/*
 * 会员修改密码
 */
function editPassword()
{
  var frm              = document.forms['formPassword'];
  var old_password     = frm.elements['old_password'].value;
  var new_password     = frm.elements['new_password'].value;
  var confirm_password = frm.elements['comfirm_password'].value;

  var msg = '';
  var reg = null;

  if (old_password.length == 0)
  {
    msg += old_password_empty + '\n';
  }

  if (new_password.length == 0)
  {
    msg += new_password_empty + '\n';
  }

  if (confirm_password.length == 0)
  {
    msg += confirm_password_empty + '\n';
  }

  if (new_password.length > 0 && confirm_password.length > 0)
  {
    if (new_password != confirm_password)
    {
      msg += both_password_error + '\n';
    }
  }

  if (msg.length > 0)
  {
    alert(msg);
    return false;
  }
  else
  {
    return true;
  }
}

/* *
 * 会员找回密码时，对输入作处理
 */
function submitPwdInfo()
{
  var frm = document.forms['getPassword'];
  var user_name = frm.elements['user_name'].value;
  var email     = frm.elements['email'].value;

  var errorMsg = '';
  if (user_name.length == 0)
  {
    errorMsg += user_name_empty + '\n';
  }

  if (email.length == 0)
  {
    errorMsg += email_address_empty + '\n';
  }
  else
  {
    if ( ! (Utils.isEmail(email)))
    {
      errorMsg += email_address_error + '\n';
    }
  }

  if (errorMsg.length > 0)
  {
    alert(errorMsg);
    return false;
  }

  return true;
}

/* *
 * 会员找回密码时，对输入作处理
 */
function submitPwd()
{
  var frm = document.forms['getPassword2'];
  var password = frm.elements['new_password'].value;
  var confirm_password = frm.elements['confirm_password'].value;

  var errorMsg = '';
  if (password.length == 0)
  {
    errorMsg += new_password_empty + '\n';
  }

  if (confirm_password.length == 0)
  {
    errorMsg += confirm_password_empty + '\n';
  }

  if (confirm_password != password)
  {
    errorMsg += both_password_error + '\n';
  }

  if (errorMsg.length > 0)
  {
    alert(errorMsg);
    return false;
  }
  else
  {
    return true;
  }
}

/* *
 * 会员登录
 */
function userLogin()
{
  var frm      = document.forms['formLogin'];
  var username = frm.elements['username'].value;
  var password = frm.elements['password'].value;
  var msg = '';

  if (username.length == 0)
  {
    msg += username_empty + '\n';
  }

  if (password.length == 0)
  {
    msg += password_empty + '\n';
  }

  if (msg.length > 0)
  {
    alert(msg);
    return false;
  }
  else
  {
    return true;
  }
}   

function changeDomain(val)
{
  var regExp = /^[A-Za-z0-9][A-Za-z0-9_-]*$/;
  if(!regExp.test(val))
  {
    $('ecs_domain_notice').innerHTML =  "格式不正确";
    $('ecs_domain_notice').style.color = "red";
    return false;
  }
  Ajax.call('register.php?act=change_domain', 'domain=' + val, changeDomainResponse, 'GET', 'JSON');
}

function changeDomainResponse(obj)
{
  if (obj.error > 0)
  {
    $('ecs_domain_notice').innerHTML = obj.message.replace("%s", $("ecs_domain").value);
    $('ecs_domain_notice').style.color = "red";
  }
  else
  {
    $('ecs_domain_notice').innerHTML = obj.message;
    $('ecs_domain').value = obj.content;
    $('ecs_domain_notice').style.color = "#009900";
  }
}

function changeAdmin(val)
{
  if (val == "")
  {
    $('admin_username_notice').innerHTML = "帐号不能为空";
    $('admin_username_notice').style.color = "red";
  }
  else
  {
    Ajax.call('register.php?act=change_admin', 'username=' + val, changeAdminResponse, 'GET', 'JSON');
  }
}

function checkUserName(val, elements)
{
  if (val == "")
  {
    $(elements).innerHTML = username_empty;
    $(elements).style.color = "red";
    return false;
  }
  var regExp = /^[A-Za-z0-9][A-Za-z0-9_-]*$/;
  if (regExp.test(val) && val.length > 3 && val.length <= 32)
  {
    $(elements).innerHTML = '填写正确';
    $(elements).style.color = "#009900";
    return true;
  }
  else
  {
    $(elements).innerHTML = username_invalid;
    $(elements).style.color = "red";
  }
}

function changeAdminResponse(obj)
{
  if (obj.error > 0)
  {
    $('admin_username_notice').innerHTML = obj.message.replace("%s", $('admin_username').value);
    $('admin_username_notice').style.color = "red";
    isbbsuser = false;
  }
  else
  {
    $('admin_username_notice').innerHTML = obj.message;
    if (obj.content == "isbbsuser")
    {
      if ($('confpwddt'))
      {
        $('confpwddt').style.display = "none";
        $('confpwddd').style.display = "none";
      }
      isbbsuser = true;
    }
    else
    {
      if ($('confpwddt'))
      {
        $('confpwddt').style.display = "";
        $('confpwddd').style.display = "";
      }
      isbbsuser = false;
      
    }
    $('admin_username_notice').style.color = "#009900";
  }
}

function changeEmail(val)
{
  if (val == "")
  {
    $("ecs_email_notice").innerHTML = email + input_null;
    $('ecs_email_notice').style.color = "red";
    return false;
  }
  if (!Utils.isEmail(val)) 
  {
    $('ecs_email_notice').innerHTML = email + format_err;
    $('ecs_email_notice').style.color = "red";
    return ;
  } 
  Ajax.call('register.php?act=change_email', 'email=' + val, changeEmailResponse, 'GET', 'JSON');
}
function changeEmailResponse(obj)
{
  if (obj.error > 0)
  {
    try
    {
      $('ecs_email_notice').innerHTML = obj.message;
      $('ecs_email_notice').style.color = "red";
    }
    catch (ex) { }
  }
  else
  {
    $('ecs_email_notice').innerHTML = obj.message;
    $('ecs_email_notice').style.color = "#009900";
    
    $('ecs_email').value = obj.content;
  }
}

function changePassword(val, elements)
{
  if (val == "") 
  {
    $(elements).innerHTML = "密码不能为空";
    $(elements).style.color = "red";
    return false;
  }
  if (val.length < 6 || val.length > 20)
  {
    $(elements).innerHTML = password_notice;
    $(elements).style.color = "red";
    return false;
  }
  else
  {
    if(!isbbsuser)
    {
        $(elements).innerHTML = '填写正确';
        $(elements).style.color = "#009900";
    }
    return true;
  }
}

function validatePassword(val, elements, conf_elements)
{
  if (isbbsuser)
  {
    $(conf_elements).innerHTML = '';
    return true;
  }
  if (val == "") 
  {
    $(conf_elements).innerHTML = "确认密码不能为空";
    $(conf_elements).style.color = "red";
    return false;
  }
  if (val != $(elements).value) 
  {
    $(conf_elements).innerHTML = confirm_password_notice;
    $(conf_elements).style.color = "red";
    return false;
  }
  $(conf_elements).innerHTML = '填写正确';
  $(conf_elements).style.color = "#009900";
  return true;
}

function changeShopname(val)
{
  if (val == "")
  {
    $("ecs_shopname_notice").innerHTML = shop_name_empty;
    $('ecs_shopname_notice').style.color = "red";
    return;
  }
  Ajax.call('register.php?act=change_shopname', 'shop_name=' + val, changeShopnameResponse, 'GET', 'JSON');
}

function changeShopnameResponse(obj)
{
  if (obj.error > 0)
  {
    try
    {
      $('ecs_shopname_notice').innerHTML = obj.message;
      $('ecs_shopname_notice').style.color = "red";
    }
    catch (ex) { }
  }
  else
  {
    try
    {
      $('ecs_shopname_notice').innerHTML = obj.message;
      $('ecs_shopname_notice').style.color = "#009900";
    }
    catch (ex) { }
  }
}

function changeCaptcha(val)
{
  if (val == "")
  {
    setNotice("ecs_captcha_notice", captcha + input_null);
    return;
  }
  Ajax.call('register.php?act=change_captcha', 'captcha=' + val, changeCaptchaResponse, 'GET', 'JSON');
}

function changeCaptchaResponse(obj)
{
  if (obj.error > 0)
  {
      $('ecs_captcha_notice').innerHTML = obj.message;
      $('ecs_captcha_notice').style.color = "red";
  }
  else
  {
      $('ecs_captcha_notice').innerHTML = "";
  }
}

function checkValue(val, id, notice, right)
{
  if(val != ''){
    $(id).innerHTML = right ? right : '填写正确';
    $(id).style.color='#009900';
  } else {
    $(id).innerHTML = notice;
    $(id).style.color = "red";
  }
}

function checkRegion()
{
  var frm = document.forms['formUser'];

   if (frm.elements['shop_province'].value == 0 && frm.elements['shop_province'].length > 1)
   {
     setNotice("region_notice", province + select_null);
     frm.elements['shop_province'].focus();
   }
   else if (frm.elements['shop_city'].value == 0 && frm.elements['shop_city'].length > 1)
   {
     setNotice("region_notice", city + select_null);
     frm.elements['shop_city'].focus();
   }
   else
   {
     setNotice("region_notice", '');
   }
}

function setNotice(id, notice)
{
  var obj = $(id);
  obj.style.color = "red";
  obj.innerHTML = notice;
}


