/************************init global var and init menu system**********************************/
var request = null;
var adDiv;
var resultDiv;

onload=init;
function init(){
  adDiv=document.getElementById("ad");        //to get a global ad div
  resultDiv=document.getElementById("result");//to get a global result div
  request=getRequest();                       //to get a global object request
  preLoadAd();
  setEnter2Tab("searchForm");
  initMenuEventHandler();
}

/************************common functions**********************************/
function getRequest(){
  var request = new XMLHttpRequest()||new ActiveXObject("Msxml2.XMLHTTP")||new ActiveXObject("Microsoft.XMLHTTP");
  if (request == null){
    alert("Error creating request object!");
  }
  return request;
}

/*****Object fileRequest is used to get a file and show it in result.Div******/
function fileRequest(file){
  getfile();
  
  function getfile(){
    showAdDiv();
    if(request!=null){
      request.open("get", file, true);
      request.onreadystatechange = writefile;
      request.send(null);
    }
  }
  
  function writefile(){
    if (request.readyState == 4) {
      if (request.status == 200 || request.status == 304) {
        if(file=="ad.php"){
          targetName="ad";
        }else{
          targetName="result";
          showResultDiv();
        }
        var target=document.getElementById(targetName);
        target.innerHTML=request.responseText;
        if(document.forms.length==2){
          var formName=document.forms[1].id;
          setEnter2Tab(formName);
        }
      } else {
        var message = request.getResponseHeader("Status");
        if ((message.length == null) || (message.length <= 0)) {
          alert("Error! Request status is " + request.status);
        } else {
          alert(message);
        }
      }
    }
  }
}

function showResultDiv(){
  adDiv.style.display="none";
  resultDiv.innerHTML="";
  resultDiv.style.display="block";
}
function showAdDiv(){
  resultDiv.style.display="none";
  adDiv.style.display="block";
}

/************************init menu system**********************************/
function preLoadAd(){  
  adDiv.innerHTML="<h1>Loading......</h1>";//shown before the Ad is load
  new fileRequest("ad.php");//loading Ad asynchronously in background but doesn't show Ad now
}
function initMenuEventHandler(){
  var menu=document.getElementById("menu");
  var menuItems=menu.getElementsByTagName("li");
  for(i=0;i<menuItems.length;i++){
    menuItems[i].onclick=getPhpFile;
  }
}
function getPhpFile(direct,fileName){
  //have to make all file for menu items to be .php file
  if(direct=="direct"){
    new fileRequest(fileName);//called directly by program
  }else{
    new fileRequest(this.id+".php");//called by click
  }
}

/************************convert Enter to Tab in input fields**********************************/
function setEnter2Tab(DivId){
  //var inputTextFields=document.getElementById(DivId).getElementsByTagName("input");  
  if(document.getElementById(DivId)){
    var inputTextFields=document.getElementById(DivId).elements;
    for(i=0;i<inputTextFields.length;i++){
      if(inputTextFields[i].getAttribute("type")){
        var fieldType=inputTextFields[i].getAttribute("type").toLowerCase();
        if(fieldType=="text"||fieldType=="password"){
          inputTextFields[i].alt=i;
          inputTextFields[i].onkeydown=Enter2Tab;
        }
      }
    }
  }
}
function Enter2Tab(e){
  var e=window.event||e;
  if (e.type == "keydown" && e.keyCode == 13){
    //注意this的用法;
    if(this.tagName.toLowerCase()=="textarea"){return true;};
    this.form.elements[parseInt(this.alt)+1].focus();
  }
}

/************************process search and feedback**********************************/
function searchYP() {
  showAdDiv();
  if(!checkSearchInput(document.getElementById("searchForm"))){
    return false;
  }
  
  var city=document.getElementById("searchCity").value;
  var state=document.getElementById("searchState").value;
  var keyword=document.getElementById("searchKeyword").value;
  var url = "search.php";
  request.open("POST", url, true);
  request.onreadystatechange = showSearchResult;
  request.setRequestHeader("Content-type","application/x-www-form-urlencoded");
  /*request.send("city="+escape(city)+
               "&state="+escape(state)+
               "&keyword="+escape(keyword));*/
  request.send("city="+city+
               "&state="+state+
               "&keyword="+keyword);
}

function showSearchResult() {
  if (request.readyState == 4) {
    if (request.status == 200 || request.status == 304) {
      //prepare the result.DIV
      showResultDiv();
      var bg=new Array("#FFF3F3","#F3FFF3","#F3F3FF");
      if(request.responseText.indexOf("}]}")>0){
        var JSONDATA=eval('('+request.responseText+')');
        for(i=0;i<JSONDATA.company.length;i++){
          for(var ObjName in JSONDATA.company[i]){
            if(JSONDATA.company[i][ObjName]!=""){
              var dDIV=document.createElement("div");
              dDIV.innerHTML=JSONDATA.company[i][ObjName]; 
              dDIV.style.background=bg[i%3];        
              resultDiv.appendChild(dDIV);
            }
          }
          resultDiv.innerHTML=resultDiv.innerHTML+"<div style='border:0px; height:1.5em;'></div>";
        }
      }else{//not Json data
        var dDIV=document.createElement("div");
        dDIV.innerHTML=request.responseText; 
        dDIV.style.background=bg[0];        
        resultDiv.appendChild(dDIV);
      }
    } else {
      var message = request.getResponseHeader("Status");
      if ((message.length == null) || (message.length <= 0)) {
        alert("Error! Request status is " + request.status);
      } else {
        alert(message);
      }
    }
  }
}

/************************process all submits and feedback**********************************/
function submitForm(formName){
  var formObj=document.forms[1];
  if(!eval("check"+formName+"(formObj)")){return false;}
  showAdDiv();
  var url = formName+"FeedBack.php";
  var sendStr="";
  for(var i=0; i<formObj.elements.length; i++){
    sendStr=sendStr+formObj.elements[i].name+"="+formObj.elements[i].value+"&";
  }
  request.open("POST", url, true);
  request.onreadystatechange=formFeedBack;
  request.setRequestHeader("Content-type","application/x-www-form-urlencoded");
  request.send(sendStr);
}

function formFeedBack() {
  if (request.readyState == 4) {
    if (request.status == 200 || request.status == 304) {
      showResultDiv();
      resultDiv.innerHTML=request.responseText;
      if(document.forms.length==2){
        var formName=document.forms[1].id;
        setEnter2Tab(formName);
      }
    } else {
      var message = request.getResponseHeader("Status");
      if ((message.length == null) || (message.length <= 0)) {
        alert("Error! Request status is " + request.status);
      } else {
        alert(message);
      }
    }
  }
}

/************************validate user input in some Forms**********************************/
function checkSearchInput(Obj){
  if(!check(Obj.searchCity))return false;
  if(!check(Obj.searchState))return false;
  if(!check(Obj.searchKeyword))return false;
  return true;
}

function checkRegisterForm(Obj){
  if(!check(Obj.rOrganization,Obj.rJgmc))return false;
  //if(!check(Obj.rAddress))return false;
  if(!check(Obj.rCity))return false;
  if(!check(Obj.rState))return false;
  if(!check(Obj.rZipcode))return false;
  //if(!check(Obj.rContact))return false;
  if(!check(Obj.rTelephone))return false;
  if(!check(Obj.rFax))return false;
  if(!check(Obj.rEmail))return false;
  //if(!check(Obj.rWebsite))return false;
  if(!check(Obj.rJj))return false;
  if(!check(Obj.rIntroduction))return false;
  if(!check(Obj.rGjc))return false;
  if(!check(Obj.rKeywords))return false;
  if(!check(Obj.rAccount))return false;
  if(!check(Obj.rPassword))return false;
  if(!check(Obj.rConfirm,Obj.rPassword))return false;
  return true;
}

function checkConsultForm(Obj){
  if(!check(Obj.cEmail))return false;
  if(!check(Obj.cTitle))return false;
  if(!check(Obj.cContent))return false;
  return true;
}

function checkModifyForm(Obj){
  if(!check(Obj.eAccount))return false;
  if(!check(Obj.ePassword))return false;
  return true;
}

function check(Obj,Obj2){
  //remove the className of the field with errMsg style
  if(Obj.className.indexOf("errMsg")!=-1){
    Obj.className=Obj.className.replace(/errMsg/,"");
  }
  
  str=(Obj.value=Obj.value.trim());
  if(Obj2)str2=(Obj2.value=Obj2.value.trim());
  switch(Obj.name){
    case "searchState":
    case "rState":
         Obj.value=Obj.value.toUpperCase();
         if(!str.isState()){
           //showResultDiv("menustateName");
           return showErr('State is Error!\nSee State Abbreviation',Obj);}
         break;
    case "searchCity":
    case "rCity":
         if(!str.isEmpty() && !str.isCity())return showErr('City is Error',Obj);
         break;
    case "searchKeyword":
         str=(Obj.value=str.replace(/ of /gi," ").replace(/ and /gi," ").replace(/ or /gi," ").replace(/company/gi," ").replace(/,/gi," ").replace(/;/gi," "));
         if (str.length<2 && (str.length==0 || str.charCodeAt(0)<255))return showErr('"key Word" is too short',Obj);
         break;
    case "rOrganization":
         str=str+str2;
         if(str.isEmpty())return showErr('You should fill in at least one item, Chinese or English',Obj2);
         break;
    case "rZipcode":
         if(str.isEmpty() && !str.isZipCode())return showErr('Zip-Code should be xxxxx or xxxxxx-xxxx',Obj);
         break;
    case "rTelephone":
         str=(Obj.value=str.replace(/\(/g, "").replace(/\)/g, "-"));
         if(str.isEmpty() && !str.isTelNum())return showErr('Telephone should be xxx-xxx-xxxx\nor 1-800-xxx-xxxx\nor 1-888-xxx-xxxx\norxxx-xxx-xxxx(...)',Obj);
         break;
    case "rFax":
         if(!str.isEmpty() && !str.isTelNum())return showErr('Fax should be xxx-xxx-xxxx\nor 1-800-xxx-xxxx\nor 1-888-xxx-xxxx',Obj);
         break;
    case "rEmail":
         if(!str.isEmpty() && !str.isEmail())return showErr('Email is Error',Obj);
         break;
    case "cEmail":
         if(str.isEmpty() || !str.isEmail())return showErr('Email is Error',Obj);
         break;
    case "rJj":
         if(str.length>200)return showErr('Chinese Ad is too long(>200 chinese words)',Obj);
         Obj.value=str.clearGG();
         break;
    case "rIntroduction":
         if(str.length>600)return showErr('English Ad is too long(>600 characters)',Obj);
         Obj.value=str.clearGG();
         break;
    case "rGjc":
         if(str.isEmpty())return showErr('can\'t be empty',Obj);
           else if(!str.isGJC())return showErr('There should be a comma between any Key Word.',Obj);
         break;
    case "rKeywords":
         if(str.isEmpty())return showErr('can\'t be empty',Obj);
           else if(!str.isKeywords())return showErr('There should be a comma between any Key Word.',Obj);
         break;
    case "rAccount":
    case "eAccount":
         if(str.length<6)return showErr('Account should be 6 to 30 characters in length',Obj);
         break;
    case "rPassword":
    case "ePassword":
         if(str.length<6)return showErr('Password should be 6 to 30 characters in length',Obj);
         break;
    case "rConfirm":
         if(str2.length<6)return showErr('Password should be 6 to 30 characters in length',Obj2);
           else if(str!=str2)return showErr('The Passwords are not consistent',Obj2);
         break;
    case "cTitle":
    case "name":
    case "cContent":
         if(str.isEmpty())return showErr(Obj.name+' can\'t be empty',Obj);
         break;
    case "togroup":         
         if(str.isEmpty())return showErr(Obj.name+' can\'t be empty',Obj);
           else if(!str.isEmailGroup()){
                  Obj.value=str.replace(/ /g,"\n");
                  return showErr('Email is Error\nand there should be only one E-mail in a line',Obj);}
         Obj.value=str.replace(/ /g,"\n");
         break;
    //case "email":
         //if(str.isEmpty())return showErr('can\'t be empty',Obj);
           //else if(!str.isEmail())return showErr('Email is Error',Obj);
         //break;
    default:
         alert("Input field name "+Obj.name+" is not in check()");
         return true;
         break;
  }
  return true;
}

var Focus=true;
function showErr(msg,Obj){
  if(Focus){
    Focus=false;
    Obj.focus();
    //add the className with errMsg style to field 
    Obj.className=(Obj.className)?Obj.className+" errMsg":"errMsg";
    Focus=true;
    alert(msg);
  }
  return false;
}

/************************validatation function**********************************/
String.prototype.trim = function()
{
  return this.replace(/(^[\s]*)|([\s]*$)/g, "").replace(/[\s]+/g, " ");
}

String.prototype.isEmpty = function()
{
  return /^\s*$/.test(this)
}

String.prototype.isEmail = function()
{ 
  return /^\w+([\.\-_]\w+)?@\w+([\-_\.]\w+)*\.[a-zA-Z]{2,4}$/.test(this)
}

String.prototype.isTelNum = function()
{
  return /^((1-800)|(1-888)|[\d]{3})-[\d]{3}-[\d]{4}[ ]*(\([\w- ]+\))?[ ]*([,;£¬£»|]*[ ]*((1-800)|(1-888)|[\d]{3})-[\d]{3}-[\d]{4}[ ]*(\([\w- ]+\))?)*$/.test(this)
}

String.prototype.isZipCode = function()
{
  return /^\d{5}(-\d{4})*$/.test(this)
}

var state_code="AL|AK|AZ|AR|CA|CO|CT|DE|DC|FL|GA|HI|ID|IL|IN|IA|KS|KY|LA|ME|MD|MA|MI|MN|MS|MO|MT|NE|NV|NH|NJ|NM|NY|NC|ND|OH|OK|OR|PA|RI|SC|SD|TN|TX|UT|VT|VA|WA|WV|WI|WY";
String.prototype.isState = function()
{
  return eval("/^(US|"+state_code+")$/i.test(this)");
}

String.prototype.isCity = function()
{
  return /^([a-zA-Z\.]+)( [a-zA-Z]+){0,2}([ ]*[,][ ]*([a-zA-Z\.]+)( [a-zA-Z]+){0,2})*$/.test(this)
}

String.prototype.isGJC = function()
{
  return /^[^\s ,;£¬£»|!@#%]+([ ]*[ ,;£¬£»|][ ]*[^\s ,;£¬£»|!@#%]+[ ]*)*$/.test(this)
}

String.prototype.isKeywords = function()
{
  return /^[\w]+[ \w]*([ ]*[,;£¬£»|][ ]*([\w]+[ \w]*))*$/.test(this)
}

String.prototype.isEmailGroup = function()
{ 
  return /^\w+([\.\-_]\w+)?@\w+([\-_\.]\w+)*\.[a-zA-Z]{2,4}( \w+([\.\-_]\w+)?@\w+([\-_\.]\w+)*\.[a-zA-Z]{2,4})*$/.test(this)
}

String.prototype.clearGG = function()
{
  return this.replace(/<[\s]*br[\s]*(\/)?>/gi, "").replace(/<[\s]*script.*script[\s]*>/gi, "").replace(/<[\s]*form.*\/[\s]*form[\s]*>/gi,"").replace(/<[\s]*iframe.*\/[\s]*iframe[\s]*>/gi,"").replace(/<[\s]*applet.*\/[\s]*applet[\s]*>/gi,"").replace(/<[\s]*object.*\/[\s]*object[\s]*>/gi,"");
}

/************************google search**********************************/
function google(Obj){
  str=Obj.words.value;
  lan=Obj.lan.value;
  window.open("http://www.google.com/custom?sa=%CB%D1%CB%F7&client=pub-2000513332416981&forid=1&cof=GALT%3A%23008000%3BGL%3A1%3BDIV%3A%23336699%3BVLC%3A663399%3BAH%3Acenter%3BBGC%3AFFFFFF%3BLBGC%3A336699%3BALC%3A0000FF%3BLC%3A0000FF%3BT%3A000000%3BGFNT%3A0000FF%3BGIMP%3A0000FF%3BFORID%3A1%3B&ie=UTF-8&oe=UTF-8&lr=lang_zh-CN%7Clang_zh-TW%7Clang_en&hl="+lan+"&q="+str)
}

/************************exchange between simple Chinese and traditional Chinese**********************************/
function now2jt(){
  if(/_ft/i.test(location.href)){location.href=location.href.replace(/_ft/,"").replace(/zt=ft/,"zt=jt");}
}

function now2ft(){
  if(location.href=="http://www.chineseyellowpages.us/"){location.href="http://www.chineseyellowpages.us/index_ft.php";return true;}
  if(!/_ft/i.test(location.href)){location.href=location.href.replace(/_ft/,"").replace(/.php/,"_ft.php").replace(/zt=jt/,"zt=ft");}
}

/************************Debug tool for IE**********************************/
function printObj(Obj){ 
  var win=window.open("","win",""); 
  win.document.write('<hr width="770" color="#800080">');  
  for(var ObjName in Obj){if(ObjName!="domain"){win.document.write(ObjName+"="+Obj[ObjName]+"<br>");}}  
}  
   
function printStr(Obj){  
  var win=window.open("","win","");  
  win.document.write('<hr width="770" color="#800080">');  
  for(var ObjName in Obj){win.document.write(ObjName+"<br>");}  
}  

