// yahoo
function fxsearch(data) {
  var sugg = data[1];
  if (sugg.length < 1) {
    cleartable("yahoo", "Yahoo") ;
    return;
  }
  addscript("http://nameninja.com/search/multidoms/yahoo/Yahoo/?doms=" + sugg);

}

// google
window.google = new Object();
window.google.ac = new Object();
window.google.ac.h = function(data) {
  var s1 = data[1];
  var l = s1.length;

  if (l < 1) {
    cleartable("google", "Google") ;
    return;
  }
 
  var res = [];
  for (var i= 0; i< l; i++) {
    a = s1[i][0];
    res.push(a);
  }
  var q = encodeURIComponent(res.join(",").replace(/\'/g, "\\'"));
  //  alert(res.join(","));
  addscript("http://nameninja.com/search/multidoms/google/Google/?doms=" + q);
  //  resultEl.innerHTML += "<pre>G:" + res.join(",") + "</pre>";
};

//bing
sa_inst = new Object();
sa_inst.setData = function(data){
  a = data
  
  if (!a.AS.Results || !a.AS.Results[0].Suggests || !a.AS.Results[0].Suggests[1]) {
    return;
  }

  b =  a.AS.Results[0].Suggests[1].Txt;
  //  resultEl.innerHTML += "<pre>B:" + b + data + "</pre>";
}
  
//amazon
  function updateCompletion() {
    //  resultEl.innerHTML += "<pre>A:" + completion + "</pre>";
    }



var d        = document;
var w        = window;
var selIndex = -1;
var  appId, inputEl, resultEl, self, ua;
var domres = get("domres");


//domain
var domresults = {};

/*
if (domresults.hasOwnProperty(query)) {
  domresults[query]();
  return;
}
*/
function lookupdomain(str) {
  addscript("http://nameninja.com/search/lu/" + str);
}
var BM = [1,2,4,32];
var numtlds = BM.length;
var COLS = ['Terms','COM','NET','ORG','JP'];

//BM = {'com' => 1,  'net' => 2, 'org' => 4, 'biz' => 8, 'info' => 16 }
var com = get("com");
var net = get("net");
var org = get("org");
var biz = get("biz");
var info = get("info");
var jp = get("jp");

function cleartable(id,title) {
  var tab = "<table class='st' id ='" + id + "'><th colspan=6>" + title + "</th></tr>";
  tab += "<tr><td colspan=6>No matches</td></tr></table>";
  replaceHtml(get(id),tab);
}


function sendRequest(url,callback,postData) {
  var req = createXMLHTTPObject();
  if (!req) return;
  var method = (postData) ? "POST" : "GET";
  req.open(method,url,true);
  if (postData)
    req.setRequestHeader('Content-type','application/x-www-form-urlencoded');
  req.onreadystatechange = function () {
    if (req.readyState != 4) return;
    if (req.status != 200 && req.status != 304) {
      //alert('HTTP error ' + req.status);
      return;
    }
    callback(req);
  }
  if (req.readyState == 4) return;
  req.send(postData);
}

var XMLHttpFactories = [
  function () {return new XMLHttpRequest()},
  function () {return new ActiveXObject("Msxml2.XMLHTTP")},
  function () {return new ActiveXObject("Msxml3.XMLHTTP")},
  function () {return new ActiveXObject("Microsoft.XMLHTTP")}
];

function createXMLHTTPObject() {
  var xmlhttp = false;
  for (var i=0;i<XMLHttpFactories.length;i++) {
    try {
      xmlhttp = XMLHttpFactories[i]();
    }
    catch (e) {
      continue;
    }
    break;
  }
  return xmlhttp;
}




function displaylisteddomains(req) {
  console.log(get("listeddomainsbox"));
  console.log(req.responseText);
  get("listeddomainsbox").value = req.responseText;
  }

function showlisteddomains() {
  // find div "domainlist" and replace it with
  // a textarea.
  // make ajax call to get data
  // make textarea.value that data
  replaceHtml(get("listeddomains"),"<textarea style='width:500px;height:300px;' readonly='readonly' id='listeddomainsbox'></textarea>");

  sendRequest("/manage/domains/list",displaylisteddomains);

  }


NNtabcnt = 0;
function buildtablecombined(id,title,domstr,res) {
  var doms = domstr.split(",");
  var l = doms.length;

  if(NNtabcnt==0) {  // first set of results
    NNtabcnt = 1;
    var tab = "<table class='st' id ='nnterms'><th colspan=6>人気のある検索条件</th></tr>";
    tab += "<tr><th class=terms>Terms</th><th>COM</th><th>NET</th><th>ORG</th><th>JP</th></tr><tbody id='nntbody'>"

    // clear NNdomhash
    NNdomhash = {};
    for (var i=0; i< l; i++) {
      NNdomhash[doms[i]] = i+1;
      tab += "<tr><td class='terms'>" + doms[i] + "</td>";
      for (var j=0; j< numtlds; j++) {
        tab += maketd(res[i][0],BM[j],res[i][1]);
      }
      tab += "</tr>";
    }
    tab += "</tbody></table>";
    replaceHtml(get("nnterms"),tab);
  } else { // second set of results
    var tab = "";
    for (var i=0; i< l; i++) {
      if(!NNdomhash[doms[i]]) {
        tab += "<tr><td class='terms'>" + doms[i] + "</td>";
        for (var j=0; j< numtlds; j++) {
          tab += maketd(res[i][0],BM[j],res[i][1]);
        }
        tab += "</tr>";
      }
    }
    // now append tab to tbody
    document.getElementById("nntbody").innerHTML += tab;
    NNtabcnt = 0;
  }
}

function buildtable(id,title,domstr,res) {
  var tab = "<table cellspacing=5 cellpadding=5 class='st' id ='" + id + "'><th colspan=6>" + "人気のある検索条件" + "</th></tr>";
  tab += "<tr><th class=terms>キーワード</th><th>COM</th><th>NET</th><th>ORG</th><th>JP</th></tr>"
  doms = domstr.split(",");
  var l = doms.length;
  for (var i=0; i< l; i++) {
    tab += "<tr><td class='terms'>" + doms[i] + "</td>";
    for (var j=0; j< numtlds; j++) {
      tab += maketd(res[i][0],BM[j],res[i][2]);

      // tab += "["+ res[i][0] + "]<br />";
      // tab += "["+ BM[j] + "]<br />";
      // tab += "["+ res[i][2] + "]<br />";

    }
    tab += "</tr>";
  }
  tab += "</table>";
  replaceHtml(get(id),tab);
  //  cache[id]
}

      
function domainset(dom,b) {

  replaceHtml("surname", "<div id='surname'></div>")
  var tab = "<table cellspacing=5 cellpadding=5 id=domtable>";
  tab += "<tr><th>Domain</th><th>COM</th><th>NET</th><th>ORG</th><th>JP</th></tr>"
  var bits = b[0];
  var am = b[2];
  tab += "<tr><th class='terms' >" + dom + "</td>";
  for (var j=0; j< numtlds; j++) {
    tab += maketd(bits,BM[j],am);
  }
  tab += "</tr></table>";
  replaceHtml("domtable",tab);
}



function replaceHtml(el, html) {
  var oldEl = typeof el === "string" ? document.getElementById(el) : el;
  /*@cc_on // Pure innerHTML is slightly faster in IE
    oldEl.innerHTML = html;
    return oldEl;
    @*/
  var newEl = oldEl.cloneNode(false);
  newEl.innerHTML = html;
  oldEl.parentNode.replaceChild(newEl, oldEl);
  /* Since we just removed the old element from the DOM, return a reference
     to the new element, which can be used to restore variable references. */
  return newEl;
};

function maketd(bits,mask,am) {
  var forsale = false;
  var l = am.length;
  for(var i=0; i< l; i++){
    if(am[i][2] == mask) {
      forsale = true;
      price = am[i][1];
      if (price == 0) {
        price = "buy"; 
      } else {
        price = "<font color=green>$</font>" + price;
      }
      break;
    }
  }
  
  if(bits & mask) {
    return "<td title='取得済み' class='taken'>取得済み</td>";
  }
  else {
    //return "<td title='取得可能' class='avail'>取得可能</td>";
    return "<td title='取得可能' class='joinup'><a href='http://www.joinup.jp/' target='_blank'>取得可能</a></td>";
  } 
}  

// http://www.joinup.jp/spincheck.php?action=check&ttld=jp,com,net,info,org&cSSld=housaku.net

// http://www.joinup.jp/spincheck.php?Submit=Check&action=check&ttld=jp%2Ccom%2Cnet%2Cinfo%2Corg&cSSld=housaku.net




/*
function taken(el) {
  el.innerHTML = "taken";
  setClass(el,"taken");
}

function avail(el) {
  el.innerHTML = "avail";
  setClass(el,"avail");
}
*/

function setClass(el,class_name) {
  el.className = class_name;
  return el;
}


function get(el) {
  if (el && (el.nodeType || el.item)) {
    return el;
  }

  return d.getElementById(el);
}

function preventDefault(e) {
  if (e.preventDefault) {
    e.preventDefault();
  } else if (e.returnValue) {
    e.returnValue = false;
  }
}

var  results = {};

function surname(firstname,lastname,domain) {
  return;
  //  console.log(firstname,lastname,domain);
  if (firstname == "") { firstname = "you"; }
  var str = '<p id="surname" class="surname"><b>' + domain + '</b> is part of an exclusive collection of "shared" personal names \
    that allows multiple users to have simple, memorable email addresses,  \
     such as <b>' + firstname + '@' + domain + '</b>, all sharing the same domain name.</p> \
     <form class="quickf" id="email_search" method="post" action="https://www.hover.com/register/personal"> \
      <input type="hidden" name="first" id="first" value="' + firstname + '" name="search_email" /> \
      <input type="hidden" value="' + domain + '" name="last" id="last"> \
      <center><input type=submit value="Order ' + firstname + '@' + domain + '" class="button blue"></form></center>'

    // console.log(str);
  replaceHtml("surname", str)
}


function addscript(url) {
  var el = d.createElement('script');
  el.src = url;
  d.body.appendChild(el);
}


function ytopAssist(data) {
  var sugg = data[1];
  if (sugg.length < 1) {
    cleartable("yahoo", "Yahoo") ;
    return;
  }
  addscript("/multidoms/yahoo/Yahoo/?doms=" + sugg);

}

function search (query) {
  //  query = query.replace(/^\s+|\s+$/g, ''); // trim the query
  query = query.replace(/^\s+/g, ''); // trim the query
  
  if (!query) {
    // clear out search boxes
    replaceHtml("domtable", "<div id='domtable'></div>")
    replaceHtml("google", "<div id='google'></div>")
    
    return;
  }
  NNtabcnt = 0;
  var q = encodeURIComponent(query.replace(/\'/g, "\\'"));
  // Create a scriptlet to perform the request.
   addscript("http://nameninja.com/search/lu/" + q);

   //  addscript("http://asprov.search.yahoo.co.jp/AssistSearchService/V2/webassistSearch?p=" + q + "&output=iejson&callback=ytopAssist");
  addscript("http://clients1.google.co.jp/complete/search?hl=en&client=hp&q=" + q + "&cp=8");
    
  //   addscript("http://sugg.search.yahoo.com/sg/?nresults=10&queryfirst=2&output=fxjsonp&version=&command=" + q);
  //  addscript("http://clients1.google.com/complete/search?hl=en&client=hp&q=" + q + "&cp=8");
  //  addscript("http://api.bing.com/qsonhs.aspx?FORM=ASAPIH&mkt=en-US&opt=ehl&type=cb&cb=sa_inst.setData&q=" + q);
  // addscript("http://completion.amazon.com/search/complete?method=completion&q=" + q + "&search-alias=aps&client=amazon-search-ui&mkt=1&x=updateCompletion&noCacheIE=1255974338307");

  
}


function init(myInputEl, myResultEl) {
  var match;
  
  var inputEl  = get(myInputEl);
   resultEl = get(myResultEl);

  // If the search input field is empty and this page has a query string in
  // the URL, populate the search field with that query.
   /*  if (!inputEl.value) {
     console.log("start " + location.href); */
    if (match = w.location.href.match(/#([^&]+)/)) {
      // console.log("hit");
      inputEl.value = decodeURIComponent(match[1].replace(/\+/g, ' '));
    }

    if (match = w.location.href.match(/nameninja.com\/q\/([^&]+)/i)) {
      // console.log("hit");
      inputEl.value = decodeURIComponent(match[1].replace(/\+/g, ' '));
    }


    /*  } */

  // If the search input field already contains something, that means that
  // either the query string contained a search query (see above) or this
  // page was loaded from the browser's cache after a back button click. We
  // need to refresh the results.
  if (inputEl.value) {
    search(inputEl.value);
  }


  NW.Event.delegate( ".avail", "click", function() {
    var a = this.parentNode.firstChild.firstChild.nodeValue.
      replace(/[^a-zA-Z0-9\- ]/g,"").capitalize().replace(/ /g,"");

    var dom = a.replace(/[^a-zA-Z0-9\-]/g,"") + "." + COLS[this.cellIndex];
    window.open("http://px.a8.net/svt/ejp?a8mat=1TM4QH+3SCAB6+1WTI+BZ8OY", "_blank")
  });

  NW.Event.delegate( ".taken", "click", function() {
    var v = this.parentNode.firstChild.firstChild.nodeValue;
    var a = v.replace(/[^a-zA-Z0-9\- ]/g,"").capitalize().replace(/ /g,"");

    var dom = a.replace(/[^a-zA-Z0-9\-]/g,"") + "." + COLS[this.cellIndex];
    createCookie("lastsearch",inputEl.value);
    //document.location = "http://nameninja.com/#" + inputEl.value;
    window.open("http://" + dom, "_blank")
      //window.location = "http://" + dom;
  });

  NW.Event.delegate( ".terms", "click", function() {
    var a = this.parentNode.firstChild.firstChild.nodeValue;
    inputEl.value = a;
    search(inputEl.value);
    //    document.location = "http://nameninja.com/#" + a;
  });


  NW.Event.delegate( ".forsale", "click", function() {
    var a = this.parentNode.firstChild.firstChild.nodeValue.
      replace(/[^a-zA-Z0-9\- ]/g,"").capitalize().replace(/ /g,"");

    var dom = a.replace(/[^a-zA-Z0-9\-]/g,"") + "." + COLS[this.cellIndex];
    window.open("https://www.snapnames.com/store/basic.action?dom=" + dom + "&auctionsearchSubmit.x=19&auctionsearchSubmit.y=19#store;storeName=basic" + dom, "_blank")

  });





  NW.Event.appendHandler( inputEl, "keyup", function() {
    search(inputEl.value);

  });

  NW.Event.appendHandler(inputEl,"focus", function() {
    selIndex = -1;
  });

}

function createCookie(name,value,days) {
  if (days) {
    var date = new Date();
    date.setTime(date.getTime()+(days*24*60*60*1000));
    var expires = "; expires="+date.toGMTString();
  }
  else var expires = "";
  document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
  var nameEQ = name + "=";
  var ca = document.cookie.split(';');
  for(var i=0;i < ca.length;i++) {
    var c = ca[i];
    while (c.charAt(0)==' ') c = c.substring(1,c.length);
    if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
  }
  return null;
}

function eraseCookie(name) {
  createCookie(name,"",-1);
}


String.prototype.capitalize = function(){
  return this.replace(/\S+/g, function(a){
    return a.charAt(0).toUpperCase() + a.slice(1).toLowerCase();
  });
};


