/// #----------------------------------------------------------------
/// # ▼検索エンジンからの来訪者用（keyword.js）
/// #----------------------------------------------------------------
// Configuration:
Keyword = {
  hilite: true,
  index: false,
  refill1: true,
  refill2: false,
  element1: 'search01',
  element2: 'w',
  style_name: 'hilite',
  style_name_suffix: true,
  debug_referrer: '',
  debug_meta: ''
};

Keyword.decodeReferrer = function(referrer) {
  try {
    // to decode the url of utf-8.
    referrer = decodeURIComponent(referrer);
  } catch (e) {
    // to decode the url of gb2312.
    referrer = Keyword.decodeGBURI(referrer);
  }
  var query = null;

  if (referrer.match(/^http:\/\/(www\.)?alltheweb.*/i)) {
  // AllTheWeb
    referrer = decodeURIComponent(referrer);
    if (referrer.match(/q=/))
      if (referrer.match(/^.*q=([^&]+)&?.*$/i))
        query = RegExp.$1;
  } else if (referrer.match(/^http:\/\/(?:seek|cns)\.3721.*/i)) {
  // 3721 GB
    referrer = Keyword.decodeGBURI(referrer);
    if (referrer.match(/p=/))
      if (referrer.match(/^.*p=([^&]+)&?.*$/i))
        query = RegExp.$1;
  } else if (referrer.match(/^http:\/\/(?:www|image|cache)?\.baidu.*/i)) {
  // Baidu GB
    referrer = Keyword.decodeGBURI(referrer);
    if (referrer.match(/(w|wd|word)=/))
      if (referrer.match(/^.*(w|wd|word)=([^&]+)&?.*$/i))
        query = RegExp.$2;
  } else if (referrer.match(/^http:\/\/(www|image)?\.?google.*/i)) {
  // Google
    referrer = decodeURIComponent(referrer);
    if (referrer.match(/q=/))
      if (referrer.match(/^.*q=([^&]+)&?.*$/i))
        query = RegExp.$1;
  } else if (referrer.match(/^http:\/\/search\.lycos.*/i)) {
  // Lycos
    referrer = decodeURIComponent(referrer);
    if (referrer.match(/query=/))
      if (referrer.match(/^.*query=([^&]+)&?.*$/i))
        query = RegExp.$1;
  } else if (referrer.match(/^http:\/\/search\.msn.*/i)) {
  // MSN
    referrer = decodeURIComponent(referrer);
    if (referrer.match(/q=/))
      if (referrer.match(/^.*q=([^&]+)&?.*$/i))
        query = RegExp.$1;
  } else if (referrer.match(/^http:\/\/search\.tom.*/i)) {
  // TOM GB
    referrer = Keyword.decodeGBURI(referrer);
    if (referrer.match(/word=/))
      if (referrer.match(/^.*word=([^&]+)&?.*$/i))
        query = RegExp.$1;
  } else if (referrer.match(/^http:\/\/(search|so)\.qq.*/i)) {
  // QQ GB
    referrer = Keyword.decodeGBURI(referrer);
    if (referrer.match(/word=/))
      if (referrer.match(/^.*word=([^&]+)&?.*$/i))
        query = RegExp.$1;
  } else if (referrer.match(/^http:\/\/search\.yahoo.*/i)) {
  // Yahoo
    referrer = decodeURIComponent(referrer);
    if (referrer.match(/p=/))
      if (referrer.match(/^.*p=([^&]+)&?.*$/i))
        query = RegExp.$1;
  } else if (referrer.match(/^http:\/\/page\.zhongsou.*/i)) {
  // Zhongsou GB
    referrer = Keyword.decodeGBURI(referrer);
     if (referrer.match(/word=/))
      if (referrer.match(/^.*word=([^&]+)&?.*$/i))
        query = RegExp.$1;
  } else if (referrer.match(/^http:\/\/www\.yisou.*/i)) {
  // Yisou GB
    referrer = Keyword.decodeGBURI(referrer);
    if (referrer.match(/p=/))
      if (referrer.match(/^.*p=([^&]+)&?.*$/i))
        query = RegExp.$1;
  } else if (referrer.match(/^http:\/\/www\.aiview.*/i)) {
  // Aiview.com
    referrer = decodeURIComponent(referrer);
    if (referrer.match(/search=/))
      if (referrer.match(/^.*search=([^&]+)&?.*$/i))
        query = RegExp.$1;
  }

  if (query) {
    query = query.replace(/\'|"/, '');
    query = query.split(/[\s,\+\.]+/);
  }

  return query;
};

Keyword.hiliteHTML = function(html, query) {
  var re = new Array();
  for (var i = 0; i < query.length; i ++) {
    if (query[i]) {
      var classname = Keyword.style_name;
      if (Keyword.style_name_suffix)
        classname += (re.length==0?'':re.length);
      re.push([new RegExp('('+query[i]+')', "gi"), classname]);
    }
  }

  var last = 0;
  var tag = '<';
  var skip = false;
  var skipre = new RegExp('^(script|style|textarea)', 'gi');
  var part = null;
  var result = '';

  while (last >= 0) {
    var pos = html.indexOf(tag, last);
    if (pos < 0) {
      part = html.substring(last);
      last = -1;
    } else {
      part = html.substring(last, pos);
      last = pos+1;
    }

    if (tag == '<') {
      if (!skip) {
        for (var j = 0; j < re.length; j ++)
          part = part.replace(re[j][0], '<span class="' + re[j][1] +
                    '">$1</span>');
      } else
        skip = false;
    } else if (part.match(skipre)) {
      skip = true;
    }

    result += part + (pos < 0 ? '' : tag);
    tag = tag == '<' ? '>' : '<';
  }
  return result;
};

Keyword.indexHTML = function(html, query) {
  var re = new Array();
  var q = 'Your keywords (link to the first macthing)：';
  for (var i = 0; i < query.length; i ++) {
    if (query[i]) {
      var classname = Keyword.style_name;
      if (Keyword.style_name_suffix)
        classname += (re.length==0?'':re.length);
      re.push([new RegExp('('+query[i]+')', "gi"), classname]);
      q += '<span class="' + classname + '">' + (query[i]).link('#kIdx' + i) + ' </span>';
    }
  }

  var last = 0;
  var tag = '<';
  var skip = false;
  var skipre = new RegExp('^(script|style|textarea)', 'gi');
  var part = null;
  var result = '';

  while (last >= 0) {
    var pos = html.indexOf(tag, last);
    if (pos < 0) {
      part = html.substring(last);
      last = -1;
    } else {
      part = html.substring(last, pos);
      last = pos+1;
    }

    if (tag == '<') {
      if (!skip) {
        for (var j = 0; j < re.length; j ++) {
          part = part.replace(re[j][0], ''.anchor('kIdx' + j) + '$1');
        }
      } else
        skip = false;
    } else if (part.match(skipre)) {
      skip = true;
    }

    result += part + (pos < 0 ? '' : tag);
    tag = tag == '<' ? '>' : '<';
  }
  result = q + '<p>' + result;
  return result;
};

Keyword.hiliteElement = function(elm, query) {
  if (!query)
    return;

  elm.innerHTML = Keyword.hiliteHTML(elm.innerHTML, query);
};

Keyword.indexElement = function(elm, query) {
  if (!query)
    return;

  elm.innerHTML = Keyword.indexHTML(elm.innerHTML, query);
};

Keyword.refillElement = function(elm, query) {
  if (document.getElementById(elm) && query)
    document.getElementById(elm).value = query;
}

Keyword.run = function() {
  var q1 = Keyword.debug_referrer ? Keyword.debug_referrer : document.referrer;
  if (document.getElementById('keywords'))
    var q2 = Keyword.debug_meta ? Keyword.debug_meta : document.getElementById('keywords').content;
  q1 = Keyword.decodeReferrer(q1);
  if (q2)
    q2 = q2.split(',', 2);

  if (q1) {
    if (Keyword.hilite) {
      var e = null;
      if (((e = document.getElementById('container')) ||
        (e = document.body)))
      {
        Keyword.hiliteElement(e, q1);
        if (Keyword.index) {
          Keyword.indexElement(e, q1);
        }
      }
    }

    if (Keyword.refill1) {
      var query = q1.join(' ');
      Keyword.refillElement(Keyword.element1, query);
    }
  }

  if (q2) {
    if (Keyword.refill2) {
      var query = q2[0] + (q2[1] ? (' ' + q2[1]) : '');
      if (query)
        Keyword.refillElement(Keyword.element2, query);
    }
  }
  Keyword.other();
};

Keyword.decodeGBURI = function(strcode) {
  try {
    var result = '';
    for ( var i = 0; i < strcode.length; i ++) {
      var thischr = strcode.substr(i,1);

      if (thischr == '%') { //  HEX encoded
        var ascii = eval('0x' + strcode.substr(i+1,2)); // Convert 2 bytes in HEX to Ascii in DEC

        if ((ascii > 0x20 && ascii < 0x30) ||
          (ascii > 0x39 && ascii < 0x41) ||
          (ascii > 0x5a && ascii < 0x61) ||
          (ascii > 0x7a && ascii < 0x91)) { // !"#$%&'()*+,-./ :;<=>?@ [\]^_;` {|}~
          try {
            result = result + String.fromCharCodeAt(ascii); //  Double-bytes to single-byte
          } catch (e)  { // ie6 will trap here and skip above process
            i = i + 2;
            continue;
          }

          i = i + 2;
        } else { // Wide-Character
          ascii = eval('0x' + strcode.substr(i+1,2) + strcode.substr(i+4,2)); // Convert 4 bytes in HEX to Ascii in DEC
          try  {
            result = result + chrval(ascii); // Revers to double char, call vb func to process gb2312 encoded char
          } catch (e) { // non-ie browser don't support vb script, then skip this wide-char, go next
            i = i + 5;
            continue;
          }
          i = i + 5;
        }
      } else if (thischr == '+')
          result = result + ' '; // Convert '+' to space

      else // Ascii char, no need process
          result = result + thischr;
    }
  } catch(e) { return false; };

  return result;
};

Keyword.other = function() {
  try {
    if (document.baidu.word)
      document.baidu.word.select();
  }
  catch (e) {}
};

// Only for Mozila/Firefox Browser
if (document.addEventListener) {
  document.addEventListener("DOMContentLoaded", Keyword.run, false);
}

// Only for IE
   /*@cc_on @*/
   /*@if (@_win32)
     document.write("<script defer src=/ie_onload.js><"+"/script>");
   /*@end @*/

// For all other Browsers
if (window.onload) {
  Keyword._old_onload = window.onload;
  window.onload = function(ev) {
    Keyword._old_onload(ev);
    Keyword.run();
  };
} else {
  window.onload = function() {
    Keyword.run();
  };
}