﻿var selected=" selected=\'selected\'";
/******************************/
 //编码
function HtmlEncode(text)
{
 var re = {'<':'&lt;','>':'&gt;','&':'&amp;','"':'&quot;'};
 for (i in re) text = text.replace(new RegExp(i,'g'), re[i]);
 return text;
}
//解码
function HtmlDecode(text)
{
 var re = {'&lt;':'<','&gt;':'>','&amp;':'&','&quot;':'"'};
 for (i in re) text = text.replace(new RegExp(i,'g'), re[i]);
 return text;
}
function gid(id)
{
 return document.getElementById?document.getElementById(id):null;
}
function showByid(id,body)
{
    var obj = gid(id);
    if (obj)
    {
     if (body.length>0) obj.innerHTML = HtmlDecode(body);
    }
}
function InitRequest()
{
	var C_req = null;
	try
	{
		C_req = new ActiveXObject("Msxml2.XMLHTTP");
	}
	catch(e)
	{
		try{C_req = new ActiveXObject("Microsoft.XMLHTTP");}
		catch(oc){C_req = null;}
	}
	if (!C_req && typeof XMLHttpRequest != "undefined")
	{
		try{C_req = new XMLHttpRequest();}
		catch(fa){alert("对不起!您的浏览器不支持该功能,请使用Internet Explorer 6.0或FireFox浏览器!");C_req = null;}
	}
	return C_req;
}
function readcookie(name){
  var cookieValue = "";
  var search = name + "=";
  if(document.cookie.length > 0){ 
    offset = document.cookie.indexOf(search);
    if (offset != -1){ 
      offset += search.length;
      end = document.cookie.indexOf(";", offset);
      if (end == -1) end = document.cookie.length;
      cookieValue = unescape(document.cookie.substring(offset, end))
    }
  }
  return cookieValue;
}


var responseResultHaveErr=false;
function PostRequest(url, data)
{
    //alert(url+"?"+data);
    //prompt(url,url+"?"+data);
	    var AjaxRequestObj = InitRequest();
	    if (AjaxRequestObj != null)
	    {
		    AjaxRequestObj.onreadystatechange = function ()
		    {
			    if (AjaxRequestObj.readyState == 4 && AjaxRequestObj.responseText)
			    {
			        if(AjaxRequestObj.status == 500&&responseResultHaveErr==false)
                    {responseResultHaveErr=true;PostRequest(url, data);return;}
				    ProcessAjaxData(AjaxRequestObj.responseText);				
			    }
		    };
		    AjaxRequestObj.open("POST", url, true);
		    AjaxRequestObj.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
		    //AjaxRequestObj.setRequestHeader("Content-Type ", "text/html;charset=gb2312"); 
		    //AjaxRequestObj.setRequestHeader("SOAPAction", "http://tempuri.org/");
            //AjaxRequestObj.setRequestHeader "Content-Length",LEN(SoapRequest)
		    AjaxRequestObj.send(data);
	    }
}
function ProcessAjaxData(data)
{
      var data_list = new Array();
     data_list = data.split(";");
     if(data_list.length>0)
     {
         for(var i=0;i<data_list.length;i++)
         {
             if(data_list[i].toString().indexOf("<")!=-1)
             break;
             eval(data_list[i]);
         }
     } 
}
function PostRequestNoJs(url, data)
{
    //alert(url+"?"+data);
    //prompt(url,url+"?"+data);
	    var AjaxRequestObj = InitRequest();
	    if (AjaxRequestObj != null)
	    {
		    AjaxRequestObj.onreadystatechange = function ()
		    {
			    if (AjaxRequestObj.readyState == 4 && AjaxRequestObj.responseText)
			    {
			        if(AjaxRequestObj.status == 500&&responseResultHaveErr==false)
                    {responseResultHaveErr=true;PostRequestNoJs(url, data);return;}
				    AjaxRequestObj.responseText;
			    }
		    };
		    AjaxRequestObj.open("POST", url, true);
		    AjaxRequestObj.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
		    AjaxRequestObj.send(data);
	    }
}
function invokeServer(url)   
{
   var script_old=document.getElementById('temp_script');  
   if(script_old!=null && document.all)  
   {  
      script_old.src = url;   
      return;  
   }  
     
  var head=document.documentElement.firstChild;   
  var script=document.createElement('script');   
  script.id='temp_script';   
  script.type = 'text/javascript';   
  script.src = url;
  script.charset='utf-8';
  if(script_old!=null)  
     head.replaceChild(script,script_old);   
  else
     head.appendChild(script);
}
/******************************/
function bindBig(bid)
{
    if(bid<1)
    {
          document.getElementById("subBrandli").innerHTML = "<select name=\"subBrandId\" id=\"subBrandId\" style=\"width:120px;\"  onchange=\"bindmode(this.value);\"><option value=\"-1\">请选择系列</option></select>";
    }
    var memo = "<select name=\"bigBrandId\" id=\"bigBrandId\" style=\"width:120px;\"  onchange=\"bindsbrand(this.value,-1);\"><option value=\"-1\">请选择品牌</option>";//
    for(var i=0;i<bitautoBigBrand.length;i++)
    {
        if(bid==bitautoBigBrand[i][0])
        {
            memo +='<option value="'+ bitautoBigBrand[i][0] +'" '+selected+'>'+bitautoBigBrand[i][2]+'&nbsp;'+ bitautoBigBrand[i][1]  +'</option>\n';
        }
        else
        {
            memo +='<option value="'+ bitautoBigBrand[i][0] +'" >'+bitautoBigBrand[i][2]+'&nbsp;'+ bitautoBigBrand[i][1]  +'</option>\n';
        }
    }
    memo+="</select>";
    document.getElementById("bigBrandli").innerHTML = memo;
}
function MArray(len){ 
    this.length = len; 
    for(i=1;i<=len;i++) this[i] = 0; 
    return this; 
} 

function bindBigSome(bid,someBids)
{
    if(bid<1)
    {
          document.getElementById("subBrandli").innerHTML = "<select name=\"subBrandId\" id=\"subBrandId\" style=\"width:120px;\"  onchange=\"bindmode(this.value);\"><option value=\"-1\">请选择系列</option></select>";
    }
    var memo = "<select name=\"bigBrandId\" id=\"bigBrandId\" style=\"width:120px;\"  onchange=\"bindsbrand(this.value,-1);\"><option value=\"-1\">请选择品牌</option>";
    var bids = someBids.split(",");
    for(var i=0;i<bitautoBigBrand.length;i++)
    {
        if(HaveBig(bids,bitautoBigBrand[i][0]))
        {
            if(bid==bitautoBigBrand[i][0])
            {
                memo +='<option value="'+ bitautoBigBrand[i][0] +'" '+selected+'>'+bitautoBigBrand[i][2]+'&nbsp;'+ bitautoBigBrand[i][1]  +'</option>\n';
            }
            else
            {
                memo +='<option value="'+ bitautoBigBrand[i][0] +'" >'+bitautoBigBrand[i][2]+'&nbsp;'+ bitautoBigBrand[i][1]  +'</option>\n';
            }
        }
    }
    memo+="</select>";
    document.getElementById("bigBrandli").innerHTML = memo;
}
function bindsbrandSome(s_ids)
{
    if(s_ids.length==0||s_ids==null||s_ids=="-1")
    {
        if(gid("buycar"))
        {
            gid("buycar").style.display="none";
        }
        return;
    }
    var smemo = "<select name=\"subBrandId\" id=\"subBrandId\" style=\"width:120px;\"  onchange=\"bindmode(this.value);\"><option value=\"-1\">请选择系列</option>";
    var sids = s_ids.split(",");
    var Subbrand;
    for(var s in bitautoSubBrand)
    {
        Subbrand = bitautoSubBrand[s];       
        for(var j=0;j<Subbrand.length;j++)
        {
            if(HaveBig(sids,Subbrand[j][0]))
            {
                //if(sid==Subbrand[j][0])
                //{
                //    smemo +='<option value="'+ Subbrand[j][0] +'"  '+selected+'>'+ Subbrand[j][1]  +'</option>\n';
                //}
                //else
                //{
                    smemo +='<option value="'+ Subbrand[j][0] +'"  >'+ Subbrand[j][1]  +'</option>\n';  
                //} 
            } 
        } 
    }
    document.getElementById("subBrandli").innerHTML = smemo+"</select>";
    
}

//答疑页面有bid或者sid的参数
function loadbrand(bid,sid)
{
    if(sid>-1)
    {
        var Subbrand;
        for(var s in bitautoSubBrand)
        {
            Subbrand = bitautoSubBrand[s];       
            for(var j=0;j<Subbrand.length;j++)
            {
                if(sid==Subbrand[j][0])
                {
                    bid = s;
                }
            } 
        }
        bindsbrand(bid,sid);
    }
    else if(bid>-1)
    {
        bindsbrand(bid,-1);
    }
    if(gid("bigBrandId"))
        gid("bigBrandId").value=bid;
}

function getOrder(dealerid,carid)
{
    if(carid <= 0)
    {
        errorMsg("CarIdOl","请选择车型");
        return false;
    }
    else
    {
        if(O)
        {    
            if(gid("chioseDiv"))
            {        
                gid("chioseDiv").style.display="none";
            }
            if(gid("Logindiv"))
            { 
                gid("Logindiv").style.display="block";
            }
            if(gid("orderLayer"))
            { 
                gid("orderLayer").style.display="block";
            }
            O.GetPriceInfoNewCarID(dealerid,carid);
        }
    }
    return false;
}

function closeSumbit()
{
    hide("ordersubmit");hide("popBox");hide("popIframe");IsInit();
}
function HaveBig(bids,id)
{
    if(bids.length>0)
    {
        for(var j=0;j<bids.length;j++)
        {            
            if(bids[j]==id)
            {
                return true;
            }
        }
    }
    return false;
}
function bindsbrand(bid,sid)
{
    if(bid==-1)
    {
        document.getElementById("subBrandli").innerHTML = "<select name=\"subBrandId\" id=\"subBrandId\" style=\"width:120px;\"  onchange=\"bindmode(this.value);\"><option value=\"-1\">请选择系列</option></select>";
        return;
    }
    var smemo = "<select name=\"subBrandId\" id=\"subBrandId\" style=\"width:120px;\"  ><option value=\"-1\">请选择系列</option>";//onchange=\"bindmode(this.value);\"
    var Subbrand = bitautoSubBrand[bid];
    if(Subbrand!=undefined)
    {
    for(var i=0;i<Subbrand.length;i++)
    {
        if(sid==Subbrand[i][0])
        {
            smemo +='<option value="'+ Subbrand[i][0] +'"  '+selected+'>'+ Subbrand[i][1]  +'</option>\n';
        }
        else
        {
            smemo +='<option value="'+ Subbrand[i][0] +'"  >'+ Subbrand[i][1]  +'</option>\n';  
        }   
    }
    }
    document.getElementById("subBrandli").innerHTML = smemo+"</select>";
    
}
var haveCarIds;
function IncludeJS(sid) 
{
    var carids = haveCarIds.split(",");
    var HaveThisCar;
    
    var basicmemo = "<select name=\"CarType\" id=\"CarType\" style=\"width:120px;\"  ><option value=\"-1\">请选择车型</option>";//
    for(var i=0;i<bitautoBasic.length;i++)
    {
        HaveThisCar=false;
        for(var s=0;s<carids.length;s++)
        {
            if(carids[s]==bitautoBasic[i][0])
            {
                HaveThisCar=true;
            }
        }
        if(HaveThisCar)
        {
            if(car_id==bitautoBasic[i][0])
            {
                basicmemo +='<option value="'+ bitautoBasic[i][0] +'" '+selected+'>'+ bitautoBasic[i][1]  +'</option>\n';
            }
            else
            {
                basicmemo +='<option value="'+ bitautoBasic[i][0] +'" >'+ bitautoBasic[i][1]  +'</option>\n';
            }
        }
    }
    basicmemo+="</select>";
    document.getElementById("CarTypeli").innerHTML = basicmemo;
 
}
var car_id=0;
function bindmode(sid,carid)
{
    //return;
    if(sid < 1)
    {
        document.getElementById("CarTypeli").innerHTML = " <select name=\"CarType\" id=\"CarType\"  style=\"width:120px;\"><option selected=\"selected\" value=\"\">请选择车型</option></select>";
         return;
    }       
    invokeServer("http://dealer.bitauto.com/js/car/basic_"+sid+".js");
    car_id = carid;
    
}

function errorMsg(id,html)
{
    var span = document.createElement("span");
    span.id = "__ErrorMessagePanel"+id;
    span.className = "alert";
    if(gid(id))
    {
        if(gid("__ErrorMessagePanel"+id))
        {
            if(html.length>0)
            gid("__ErrorMessagePanel"+id).innerHTML = html;
            gid("__ErrorMessagePanel"+id).style.display="block";
        }
        else
        {
            gid(id).appendChild(span);
            span.innerHTML = html;
        }
    }
}
function error()
{
    popload("ordersubmit");
    alert('参数错误');
}
function rightMsg(id)
{
    if(gid("__ErrorMessagePanel"+id))
    {
        gid("__ErrorMessagePanel"+id).style.display="none";
    }
}

function checkMessage(dealerId,usIp)
{
    var HasError=false;
    var pid_s="",cid_s="",bigBrandId_s="",subBrandId_s="",askCon_s="";
    var form_value = window.document.getElementById("form1");
    if(form_value.ddlselectarealist!=undefined && form_value.ddlselectarealist.value!=0)
	{
	    pid_s = "&pid="+form_value.ddlselectarealist.value;
	    rightMsg("licity");
	}
	else
	{
	    errorMsg("licity","请选择您所在的省份");
	    HasError = true;
	}
	
    if(form_value.ddlselectedcitylist !=undefined && form_value.ddlselectedcitylist.value!="")
	{
	    cid_s = "&cid="+form_value.ddlselectedcitylist.value;	    
	}
	
    if(form_value.bigBrandId!=undefined && form_value.bigBrandId.value!="-1")
	{
	    bigBrandId_s = "&cbid="+form_value.bigBrandId.value;
	}
	
	if(form_value.subBrandId!=undefined && form_value.subBrandId.value!="-1")
	{
	    subBrandId_s = "&csid="+form_value.subBrandId.value;
	    rightMsg("librand");
	}
	else
	{
	    errorMsg("librand","请选择车型信息");
	    HasError = true;
	}
	
	if(form_value.askCon!=undefined && form_value.askCon.value.replace(/ /g,"").length>0)
	{
	    askCon_s = "&content="+ escape(form_value.askCon.value.replace(/ /g,""));
	    rightMsg("litext");
	}
	else
	{
	    errorMsg("litext","请填写提问内容信息");
	    HasError = true;
	}
	var allparm = "dealerId="+dealerId+"&ip="+escape(usIp)+pid_s+cid_s+subBrandId_s+askCon_s;//
	
	if(!HasError)
	{
        var PostData = allparm+"&"+Math.random();
	    PostRequest(window.location.protocol + "//" + window.location.host + "/ajaxpage/message.aspx", PostData); 
	}
	return false;
}
function IsLogin()
{
    PostRequest(window.location.protocol + "//" + window.location.host + "/ajaxpage/Login.aspx","type=3"+"&"+Math.random());
}
//登陆成功
function loginSucess(username)
{
    if(gid("sucMsg"))
    {
        gid("Logindiv").innerHTML ="<div class='memberLogin'><h3>" + username + "欢迎您！</h3><small>"+gid("sucMsg").innerHTML+"</small></div>";
        gid("Logindiv").className="";
    }
    else
    {
        showByid("Logindiv", "<div class='memberLogin'><h3>"+username+"  欢迎您 </h3>");
    }
}
function PopAlert(message)
{
    var Mess = message+" ";
    alert(Mess);
}
function loginSucessInfo(username,sex,phone,email,cityid)
{
    if(gid("userName"))
    {
        gid("userName").value =username;
    }
    if(sex==1&&gid("userSex1"))
    {
        gid("userSex1").checked =true;
    }
    else if(sex==2&&gid("userSex2"))
    {
        gid("userSex2").checked =true;
    }
    if(gid("phone"))
    {
        gid("phone").value =phone;
    }
    if(gid("email"))
    {
        gid("email").value =email;
    }
    if(cityid&&gid("province")&&gid("city"))
    {
        var province = document.getElementById("province").value;
        var city = document.getElementById("city");
        for(var i=0;i<gid("province").options.length;i++)
        {
            if(cityid.substring(0,cityid.length-2)==gid("province").options[i].value)
            {
                gid("province").options[i].selected=true;
                province = gid("province").value;
            }
        }
        city.options.length=0;

        for(var i=0;i<orderCitys.Rows.length;i++)
        {
            var cityId = orderCitys.Rows[i].city_Id+'';
            var cityName = orderCitys.Rows[i].city_Name;

            if(province+'' == cityId.substring(0,cityId.length-2))
            {
                city.options.add(new Option(cityName,cityId)); 
            }            
        }
        
        for(var i=0;i<city.options.length;i++)
        {
            if(cityid==city.options[i].value)
            city.options[i].selected=true;
        }
    }
    if(cityid && gid("ddlselectarealist")&&gid("ddlselectedcitylist")&&gid("citystate"))
    {
        if(cityid==0)
            return;
		var citySelectJs = new CitySelect();
		citySelectJs.showMode = 3;                    // 控件显示模式 1/2/3/4
		citySelectJs.maxCheck = 3;                    // 城市最大选择个数
		citySelectJs.xmlPath = '/Javascript/cityselect.xml';        // xml 文件路径
		citySelectJs.defaultArea = cityid;                 // 默认选择的地区编号
		citySelectJs.outputValue = 'cid';   // 输出城市编号的控件编号
		citySelectJs.attachControl = 'cid';              // 触发的控件之前的位置
		gid("citystate").innerHTML="<input id=\"cid\" name=\"cid\" type=\"hidden\" />";
        gid("citystate").innerHTML+="<select style=\"width: 75px;\">";
        gid("citystate").innerHTML+="   <option>所在省份</option>";
        gid("citystate").innerHTML+="</select>";
        gid("citystate").innerHTML+="<select style=\"width: 75px;\">";
        gid("citystate").innerHTML+="   <option>所在城市</option>";
        gid("citystate").innerHTML+="</select>";
		BitautoCitySelect.loadCitySelect(citySelectJs);
		//citySelectJs.attachEvent('onload');           // 触发的控件的事件名称 onload/onclick/onchange
    }
}
//验证
function IsLegalUser(userName,userpwd)
{
    PostRequestNoJs(window.location.protocol + "//" + window.location.host + "/ajaxpage/Login.aspx","username="+userName+"&password="+userpwd+"&type=2");
}
//登陆验证
function checkLogin(form)
{
    var pusern_s,puserpwd_s;
    if(form.input_username!=undefined && form.input_username.value!="")
	{
	    pusern_s = "username="+form.input_username.value;	
	    rightMsg("userNameli");    
	}
	else
	{
	    errorMsg("userNameli","请输入用户名");
	}
	if(form.input_userpwd!=undefined && form.input_userpwd.value!="")
	{
	    //alert(typeof(form.input_userpwd.value)+','+form.input_userpwd.value);
	    puserpwd_s = "&password="+form.input_userpwd.value;	    
        rightMsg("userpwdli");
	}
	else
	{
	    errorMsg("userpwdli","请输入密码");
	}
	if(pusern_s&&puserpwd_s)
    {
        rightMsg("userNameli");
        rightMsg("userpwdli");
        PostRequest(window.location.protocol + "//" + window.location.host + "/ajaxpage/Login.aspx",pusern_s+puserpwd_s+"&type=1"+"&"+Math.random());
        return false;
    }
    return false;
}
/**/
function SubmitVote(dealerId,voteid)
{
    if(gid("VoteDiv"))
    {
        var form_value = window.document.getElementById("formvote");
        var xid = 0;
        var objs = window.document.getElementsByName("buttonvote");
	    for(var i=0; i < objs.length; i++)
	    {
	        if(objs[i].checked)  
            {  
                  xid += objs[i].value+",";
            }
	    }
	    if(xid==0)
	    {
	        alert('对不起，您还没有选择选项。');
	        return;
	    }              
        var PostData = "voteid="+voteid+"&voteitemid="+xid+"&dealerid="+dealerId+"&"+Math.random();
	    PostRequest(window.location.protocol + "//" + window.location.host + "/ajaxpage/VoteSend.aspx", PostData);	
    }
}
function SubmitVoteByNews(dealerId,voteid,newsid)
{
    if(gid("VoteDiv"))
    {
        var form_value = window.document.getElementById("formvote");
        var xid = 0;
        var objs = window.document.getElementsByName("buttonvote");
	    for(var i=0; i < objs.length; i++)
	    {
	        if(objs[i].checked)  
            {  
                  xid += objs[i].value+",";
            }
	    }
	    if(xid==0)
	    {
	        alert('对不起，您还没有选择选项。');
	        return;
	    }              
        var PostData = "voteid="+voteid+"&voteitemid="+xid+"&dealerid="+dealerId+"&newsid="+newsid+"&"+Math.random();
	    PostRequest(window.location.protocol + "//" + window.location.host + "/ajaxpage/VoteSend.aspx", PostData);	
    }
}
function GetViewVote(voteid)
{
    var PostData = "voteid="+voteid+"&v=1"+"&"+Math.random();
	    PostRequest(window.location.protocol + "//" + window.location.host + "/ajaxpage/VoteSend.aspx", PostData);	
}
function ViewVote(re)
{
    if(re.length>0)
    {
        for(var i=1;i<=re.length;i++)
        {
            if(gid("Vote_"+i))
            {
                gid("Vote_"+i).innerHTML = "<span title=\""+re[i-1][0]+"人("+re[i-1][1]+"%)\"><em style=\"width:"+re[i-1][2]+"px\"></em></span><strong>"+re[i-1][0]+"人("+re[i-1][1]+"%)</strong>";
            }
        }
        popload('investRuselt');return false;
    }
}
function VoteSuccess()
{    
    gid("resultDiv").style.display="block";
    gid("submitDiv").style.display="none";
    var form_value = window.document.getElementById("formvote");
    var objs = window.document.getElementsByName("buttonvote");
	for(var i=0; i < objs.length; i++)
	{
	    objs[i].disabled="disabled";
	}
}
function ReadcookieVote(voteid,dealerid)
{
    var str = readcookie("bitauto_voteitem");
    if(str.indexOf("=")>0)
    {
        var beginPosition =str.substr(0,str.indexOf("="));
        if(beginPosition=="vote"+voteid+dealerid)
        {
            VoteDisabled();
        }
    }
}
function ReadcookieVoteByNews(voteid,dealerid,newsid)
{
    var str = readcookie("bitauto_voteitem");
    if(str.indexOf("=")>0)
    {
        var beginPosition =str.substr(0,str.indexOf("="));
        if(beginPosition=="vote"+voteid+dealerid+newsid)
        {
            VoteDisabled();
        }
    }
}
function VoteDisabled()
{
    gid("resultDiv").style.display="block";
    gid("submitDiv").style.display="none";
    var objs = window.document.getElementsByName("buttonvote");
	for(var i=0; i < objs.length; i++)
	{
	    objs[i].disabled="disabled";
	}
}
/**/
//限制图片大小
function DrawImage(img){ 
var width=280;
var height=210;
var image=new Image(); 
image.src=img.src; 
	if(image.width>width)
	{
	  	rate=image.height/image.width;
	  	newHeight=rate*width;
	  	img.width=width;
	  	img.height=newHeight;
	}
//	if(img.height>height)
//	{
//		rate=image.width/image.height;
//		newWidth=rate*height;
//		img.height=height;
//		img.width=newWidth;
//	}
}
function searchkeyclass()
{
    if(document.getElementById("key").value!='请输入经销商名称')
    {
        document.getElementById("key").className='black';
    }
    else
    {
        document.getElementById("key").className='';
    }
}
function searchkeynull()
{
    if(document.getElementById("key").value=='请输入经销商名称')
    {
        document.getElementById("key").value='';
    }
    else if(document.getElementById("key").value=='')
    {
        document.getElementById("key").value='请输入经销商名称';
    }
}
var BitautoCitySelect = 
{
    version: '0.1.0.0', xmlDoc: null, xmlPath: 'cityarea.xml', maxCheck: 3, selectedList: [], defaultArea: 0, outputAreaName: ''
    ,outputControlId: 'txtCitySelect', outputCityName: '',divShowCity: 'divshowcitylist', divSelectCity: 'divselectcitylist'
    ,tagNode: 'ValueItem', tagName: 'CitemName', tagValue: 'ItemValue', tagParent: 'ParentValue', tagOrder: 'ItemIndex'
    ,tagDisabled: 'Disabled', tagHotCity: 'HotCity', isIE: true, showMode: 1, firstShow: []
    ,$: function(id)  { return document.getElementById(id);  }
	,tagArray: function(obj, name)  {   return obj.getElementsByTagName(name);  }
	,addEvent: function(obj, eventName, fun)
	{
	    return document.all ? obj.attachEvent(eventName, fun) : obj.addEventListener(eventName.substr(2), fun, false);
	}
	,addObject: function(htmlCode, tagId, tagClassName)
	{
	    var divTag = document.createElement("div");
	    if(tagId) 
	    { 
	        divTag.id =  tagId;
	    } 
	    if(tagClassName) 
	    {
	        divTag.className =  tagClassName;
	    } 
        divTag.innerHTML = htmlCode;
        document.body.appendChild(divTag);
	}
	,ReplaceObject: function(LocationId,htmlCode, tagId, tagClassName)
	{
	    var divTag = document.getElementById(LocationId);
	    if(tagId) 
	    { 
	        divTag.id =  tagId;
	    } 
	    if(tagClassName) 
	    {
	        divTag.className =  tagClassName;
	    } 
        divTag.innerHTML = "<input id=\""+this.outputControlId+"\" name=\""+this.outputControlId+"\" type=\"hidden\" />"+htmlCode;
	}
	,getXmlDocument: function()
	{
	   if(window.ActiveXObject)   // ie
	   {
	       this.xmlDoc = new ActiveXObject('Microsoft.XMLDOM');
	   } 
	   else if (document.implementation && document.implementation.createDocument)  // ff
	   {
	       this.isIE = false;
	       this.xmlDoc = document.implementation.createDocument("", "", null);
	       
	        XMLDocument.prototype.loadXML = function(xmlString)
	        {
		        var childNodes = this.childNodes;
		        for (var i = childNodes.length - 1; i >= 0; i--)
			        this.removeChild(childNodes[i]);

		        var dp = new DOMParser();
		        var newDOM = dp.parseFromString(xmlString, "text/xml");
		        var newElt = this.importNode(newDOM.documentElement, true);
		        this.appendChild(newElt);
	        };

	        // check for XPath implementation
	        if( document.implementation.hasFeature("XPath", "3.0") )
	        {
	           // prototying the XMLDocument
	           XMLDocument.prototype.selectNodes = function(cXPathString, xNode)
	           {
		          if( !xNode ) { xNode = this; } 
		          var oNSResolver = this.createNSResolver(this.documentElement)
		          var aItems = this.evaluate(cXPathString, xNode, oNSResolver, 
					           XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null)
		          var aResult = [];
		          for( var i = 0; i < aItems.snapshotLength; i++)
		          {
			         aResult[i] =  aItems.snapshotItem(i);
		          }
		          return aResult;
	           }

	           // prototying the Element
	           Element.prototype.selectNodes = function(cXPathString)
	           {
		          if(this.ownerDocument.selectNodes)
		          {
			         return this.ownerDocument.selectNodes(cXPathString, this);
		          }
		          else{throw "For XML Elements Only";}
	           }
	        }

	        // check for XPath implementation
	        if( document.implementation.hasFeature("XPath", "3.0") )
	        {
	           // prototying the XMLDocument
	           XMLDocument.prototype.selectSingleNode = function(cXPathString, xNode)
	           {
		          if( !xNode ) { xNode = this; } 
		          var xItems = this.selectNodes(cXPathString, xNode);
		          if( xItems.length > 0 )
		          {
			         return xItems[0];
		          }
		          else
		          {
			         return null;
		          }
	           }
        	   
	           // prototying the Element
	           Element.prototype.selectSingleNode = function(cXPathString)
	           {    
		          if(this.ownerDocument.selectSingleNode)
		          {
			         return this.ownerDocument.selectSingleNode(cXPathString, this);
		          }
		          else{throw "For XML Elements Only";}
	           }
	        }	       
	   }
	   else
	   {
	        throw "不支持此浏览器!";
	   }
	}
	,loadXml: function(filePath)
	{
       this.getXmlDocument();
	
       if(this.xmlDoc == null)
       {
            return;
       }
       
       this.xmlDoc.async = false; 
	   this.xmlDoc.load(filePath);
	}
    ,getNodeList: function(key, value)
	{
	   var nodes = null;
	   var cityList = [], item = [], status = '', condition = '';
	   if (this.isIE)
	   {
	       nodes = this.xmlDoc.documentElement.childNodes
	       for(var index=0; index < nodes.length; index++) 
	       {
	           if(nodes(index).nodeName == this.tagNode && nodes(index).selectNodes(key)(0).text == value)
	           {
	                item = this.readNode(nodes(index));
	                if(item.length == 2)
	                {
	                    cityList[cityList.length] = item;
	                }
	           }
	       }
	   }
	   else
	   {
            nodes = this.xmlDoc.documentElement;
            var items = nodes.selectNodes('//ValueSet/'+ this.tagNode), status = '';
            for(var i=0;i<items.length;i++)
            {
                status = this.GetNodeValue(items[i].selectSingleNode(this.tagDisabled));
                tagName = this.GetNodeValue(items[i].selectSingleNode(key));
                if ( status.toLowerCase() == 'false' && tagName == value)
                {
                    item = [];
                    item[0] = this.GetNodeValue(items[i].selectSingleNode(this.tagName));
                    item[1] = this.GetNodeValue(items[i].selectSingleNode(this.tagValue));
                    cityList[cityList.length] = item;
                }
            }
	   }
	   
	   return cityList;
	}
	,GetNodeValue:function(obj)
    {
        var str = "";
        try
        {
            if(obj.childNodes.length>0)
            {
	            str = obj.childNodes[0].nodeValue;
	        }
	        else
	        {
	            return "";
	        }
        }
        catch(ex)
        {
	        str = "";
        }
        return str;
    }
 	,readNode: function(node)
	{
	   var item = [];
	   if (node.selectNodes(this.tagDisabled)(0).text.toLowerCase() == 'false')
	   {
	        item[0] = node.selectNodes(this.tagName)(0).text;
	        item[1] = node.selectNodes(this.tagValue)(0).text;
	   }
	   return item;
	}
	,loadCitySelect: function(obj)
	{
	    this.load(obj.xmlPath, obj.maxCheck, obj.outputValue, obj.outputName, obj.attachControl, obj.defaultArea, obj.showMode);
	}
	,load: function(xmlPath, maxCheck, outputValue, outputName, attachControl, defaultArea, showMode)
	{
	   if(this.$(outputValue) == undefined)
	   {
	        return;
	   }
	   
	   this.outputControlId = outputValue;
	   this.outputCityName =  outputName;
	    
	    if (xmlPath)
	   {
	        this.xmlPath = xmlPath;
	   } 

	   if (!isNaN(maxCheck))
	   {
	     this.maxCheck = maxCheck;
	   }
	   
	   if (!isNaN(defaultArea))
	   {
	         this.defaultArea = defaultArea;
	   }
	   
	   if (!isNaN(showMode))
	   {
	         this.showMode = showMode;
	   }
	   else
	   {
	        return;
	   }
	
	   this.loadXml(this.xmlPath);

       if (this.xmlDoc.documentElement == null) 
       {
            alert('未找到 XML 文件, 请检查文件路径! ');
            return; 
       }
       
	    var areaList = this.getNodeList(this.tagParent, '');
	    var hotCity = this.getNodeList(this.tagHotCity, 1);
	    
	    var html = ''; 
	    switch (this.showMode) 
	    {
	        case 1:     
	            html = this.InitialContent1(areaList, hotCity);
	            break;
	        case 2:
	            html = this.InitialContent2(areaList, hotCity);
	            break;
	     	case 3:    //divShowCity divSelectCity
	     	case 4:  
	     	    html = this.InitialContent3(areaList);
	            break;
	    } 
	     
		if (this.$('dropdiv') == undefined)
		{		
	       var obj = this.$(attachControl);
	       if (obj == undefined)
	       {
	            this.addObject(html);	            	            
	       }
	       else  
	       {
	            this.ReplaceObject(obj.parentNode.id,html);
	            /*var tag=document.createElement("div");
	            tag.innerHTML = html;
	            obj.parentNode.appendChild(tag, obj);
	            */
	       }
	    } 
	    else
	    { 
		   transfer('dropdiv');
	       if (this.showMode == 1) 
	       {
                this.showCity(this.$('ddlselectarealist').value); 
           } 
	    }   
        this.outputValue()
	}
	,showCity: function(parentValue, text)
	{
	    if(isNaN(parentValue))
	    {
	        return; 
	    }
	   else if(parentValue == 0)
	   {
	        if (this.showMode == 1)
	        this.$(this.divShowCity).innerHTML = '&nbsp; &nbsp; 所在城市!';
	       else 
	        this.$(this.divShowCity).innerHTML =	'<select><option>所在城市</option></select>';
	        return; 
	   }
	    
	    var citylist = this.getNodeList(this.tagParent, parentValue);
	    
	   var content = '' 
	    if (this.showMode == 1) 
	   { 
	        content = this.generateCheckBoxList(citylist);
	   } 
	   else if (this.showMode == 3)
	   {
	        if (citylist.length > 0)
	       { 
	            content = this.generateDropDownList2(citylist, 'ddlselectedcitylist', 'javascript:BitautoCitySelect.selectDropDownList(this.text, this.value);');
	            this.selectedList[0] =  this.firstShow;
	       }
	       this.outputValue()   
	   }
	    this.$(this.divShowCity).innerHTML = content;
	}
	,selectCity: function(checkBox)
	{
	    if (isNaN(checkBox.value))
	    {
	        return; 
	    }

	   if(checkBox.checked)
	   {
		   if(this.selectedList.length >= this.maxCheck)
	       {
	            checkBox.checked = false;
	            alert('最多只允许选择 ' + this.maxCheck + '个城市! ');
	            return;
	        }
	   }
       
       this.selectValue(checkBox.checked, checkBox.title, checkBox.value);
	}
    ,selectValue: function(isSelected, cityName, cityId)
	{
	    if (isSelected)
	    {
	        this.selectedList[this.selectedList.length] = new Array(cityName, cityId);
	    } 
	    else
	    {
            for (var index=0; index< this.selectedList.length; index++)
            {
                if (this.selectedList[index][1] == cityId)
                {
                   if(length == 1)
                   {   this.selectedList = []; }
                  else
                   {    this.selectedList.splice(index, 1); }
                  break; 
                }
            } 
           var hotCity = this.$('selectcityid' + cityId);
           if (hotCity != null && hotCity != undefined && hotCity.checked != undefined)
           {
                hotCity.checked = false;
           }
           this.showCity(this.$('ddlselectarealist').value);
	    }
       this.showSelectedArea();
	}
	,showSelectedArea: function()
	{
	    this.outputValue();  
	    var code = "<ul>";
        for(var index=0; index < this.selectedList.length; index++) 
        {
            code += '<li><input type="checkbox" name="selectedcity" onclick="javascript:BitautoCitySelect.selectValue(this.checked, this.title, this.value);" ';
            code += ' checked="checked" ';
            code += ' value="' +  this.selectedList[index][1] + '" title="'+ this.selectedList[index][0]  +'" /> '+ this.selectedList[index][0] + '</li>';
        }
        code += "<ul>"  
       
	    this.$(this.divSelectCity).innerHTML = code;
	}
	,allOptionalList: function(isSelect)
	{
	    if (!isSelect)
	   {
	      for(var index = 0, hotCity ; index < this.selectedList.length; index++)
	     { 
	           hotCity = this.$('selectcityid' + this.selectedList[index][1]);
               if (hotCity != null && hotCity != undefined && hotCity.checked != undefined)
               {
                    hotCity.checked = false;
               }
          }
           this.selectedList = [];
           this.showCity(this.$('ddlselectarealist').value);
	   } 
	   this.showSelectedArea();
	}
	,outputValue: function()
	{
	
	    var control = this.$(this.outputControlId);
	    if (control == undefined)
	    {
	        alert('未找到输出控件 ' + this.outputControlId + ', 你选择的城市无法保存!');
	        return;
	    }
	    
	    control.value = ''; 
	    if (control.value != undefined)
	    {
	         control.value = this.getSelectCityId();
	    }
	   else
	   {
	        control.innerText =  this.getSelectCityId();
	   } 
	   
	   if (this.outputCityName != '')
	   {
	        control = this.$(this.outputCityName);
	       if (control == undefined)
	       {
	            return;
	       } 
            if (control.value != undefined)
            {
                control.value = this.getSelectCityName();
            }
            else
            {
             control.innerText =  this.getSelectCityName();
            } 
	   }
	 
	}
	,getSelectCityId: function()
	{
	   var idList = [];
	   for(var index=0; index < this.selectedList.length; index++)
	   {
	        idList[idList.length] = this.selectedList[index][1];
	   }
	   return idList.join(',');
	}
	,getSelectCityName: function()
	{
	   var idList = [];
	   for(var index=0; index < this.selectedList.length; index++)
	   {
	        idList[idList.length] = this.selectedList[index][0];
	   }
	   return idList.join(',');
	}
	,selectLink: function(aLink)
	{
	   if (aLink != null)
	   {
	        for (var index = 0; index < this.selectedList.length; index++)
	        {
                this.setClassName(this.selectedList[index][1], '');
	        } 
	        this.selectedList[0] = new Array(aLink.title, aLink.id);
	        this.setClassName(this.selectedList[0][1], 'linknow');
	   }
	   else
	   {
	        for (var index = 0; index < this.selectedList.length; index++)
	        {
                this.setClassName(this.selectedList[index][1], '');
	        } 
	        this.selectedList = [];
	   }
	   this.outputValue();
	}
	,selectDropDownList: function(text, value)
	{
	    if (text == undefined)
	   {
	        ddl = this.$('ddlselectedcitylist')
	        for (var index=0; index < ddl.options.length; index++) 
	       {
	            if (ddl.options[index].value == value)
	            {
	                  text = ddl.options[index].text;
	                  break;
	            }
	       } 
	   } 
	    this.selectedList[0] = new Array(text, value);
	    this.outputValue();
	}
	,setClassName: function(id, className)
	{
        var link = this.$(id);
        if (link != undefined) 
        {
            link.className = className;
        }
	}
	,generateLink: function(list)
	{
	    var code = '<ul>';
        for(var index=0; index < list.length; index++)
        {
            code += '<li><a href="#" onclick="javascript:BitautoCitySelect.selectLink(this);" title="' + list[index][0] + '"' ;
           if (this.exist(this.selectedList, list[index][1]))
           {
                code += ' class="linknow"';
           }
            code += ' id="' + list[index][1] + '" >' + list[index][0] + '</a></li>';
        }
	    code += '</ul>'; 
	    return code; 
	}
	,generateDropDownList: function(list)
	{
	    return this.generateDropDownList2(list, 'ddlselectarealist', 'javascript:BitautoCitySelect.showCity(this.value);');
	}
	,generateDropDownList2: function(list, id, eventScript)
	{
	    var code = '<select id="' +id + '" name="' + id + '"   onchange="' + eventScript +'">';
	    if(id=="ddlselectedcitylist")
	        code+="<option value=\"\" >所在城市</option>";
	    var city_id="",prov_id="";
	    if((this.defaultArea+"").length==3)
	    {
	        prov_id=(this.defaultArea+"").substr(0,1);	        
	    }
	    else
	    {
	        prov_id=(this.defaultArea+"").substr(0,2);
	    }
	    cityid=this.defaultArea+"";
        for(var index=0; index < list.length; index++)
        {
            if (index == 0) 
           {
                this.firstShow = new Array(list[0][0], list[0][1]);
           } 
            code += '<option value="' + list[index][1] + '" ';
            
            if (list[index][1] == cityid ||  list[index][1] == prov_id) 
            {
                 code += ' selected="selected" ';                
                 this.firstShow = list[index];
            } 
            code += '>'+ list[index][0] + '</option>'; 
        }
        code += '</select>';
      
        return code;
	}
	,generateCheckBoxList: function(list)
	{
	    //<li><input type="checkbox" name="selectcity" value="1" onclick="javascript:BitautoCitySelect.selectCity(this.checked, this.title, this.value);" title="abc" /><label>北京</label></li>
	    var code = '<ul>';
        for(var index=0; index < list.length; index++)
        {
            code += '<li><input type="checkbox" name="selectcity" onclick="javascript:BitautoCitySelect.selectCity(this);" ';
           if (this.exist(this.selectedList, list[index][1]))
           {
                code += ' checked="checked" ';
           }
            
            code += 'id="selectcityid' + list[index][1] + '" value="' +  list[index][1] + '" title="'+ list[index][0] +'" /><label>'+  list[index][0] + '</label></li>';
        }
	    code += '</ul>'; 
	    return code; 
	}
	,InitialContent1: function(areaList, hotCity)
	{
	    var code = '<div class="dropdiv" id="dropdiv">';
	    code += ' <h3>选择地区<small>(最多可选<strong>'+ this.maxCheck +'</strong>项)</small><a href="#"><img src="i/close.jpg" alt="close" onclick="transfer(\'dropdiv\')" /></a></h3>';
	   if (hotCity.length > 0) 
	   {
	        code += '<div class="hot">';
		    code += '	<h3>热门地区:</h3>';
		    code += this.generateCheckBoxList(hotCity);
		    code += '</div>'; 
	   }
		if(areaList.length > 0)
		{
		    code += this.generateDropDownList(areaList);
        }
        code += '<div id="' + this.divShowCity +'">&nbsp; &nbsp; 选择地区!</div>';//待选择的城市列表
        code += '<div class="selected">';
        //code += '  <h3><input type="checkbox" id="selectedall" name="selectedall" onclick="javascript:BitautoCitySelect.allOptionalList(this.checked);" />您已选择的地区:</h3>';
		
		code += '<h3>您已选择的地区: <a href="#" onclick="javascript:BitautoCitySelect.allOptionalList(false);">取消所有选项</a></h3>';
        code += '  <div id="' + this.divSelectCity +'"><ul></ul></div>'; //已选择的城市列表
        //code += '  <ul id="' + this.divSelectCity +'"></ul>'; //已选择的城市列表
        code += '</div>';
        code += '<ul class="oprator">';
        code += '	<li><input type="reset" value="取消" onclick="BitautoCitySelect.allOptionalList(false);transfer(\'dropdiv\')" /></li>'; 
        code += '	<li><input type="reset" value="确定" onclick="transfer(\'dropdiv\')" /></li>'; 
        code += '</ul>'; 
        code += '</div>'; 
        return code; 
	}
	,InitialContent2: function(areaList, hotCity)
	{
	    var code = '<div class="dropdiv" id="dropdiv">';
	    code += ' <h3>选择地区<a href="#"><img src="i/close.jpg" alt="close" onclick="transfer(\'dropdiv\');" /></a></h3>';
	   if (hotCity.length > 0) 
	   {
	        code += '<div class="hot">';
		    code += '	<h3>热门地区:</h3>';
		    code += this.generateLink(hotCity);
		    code += '</div>'; 
	   }
	   
	   if (areaList.length > 0) 
	   {
	        code += '<div class="hot">';
		    code += '	<h3>热门省份:</h3>';
		    code += this.generateLink(areaList);
		    code += '</div>'; 
	   }
        code += '<ul class="oprator">';
        code += '	<li><input type="reset" value="取消" onclick="BitautoCitySelect.selectLink(null);transfer(\'dropdiv\');" /></li>'; 
        code += '	<li><input type="reset" value="确定" onclick="transfer(\'dropdiv\');" /></li>'; 
        code += '</ul>'; 
        code += '</div>'; 
        return code; 
	}
	,InitialContent3: function(areaList)
	{
	     var code = '<div class="dropdiv" id="dropdiv">';
	     if(this.showMode == 4)
	     {
	        code += this.generateDropDownList2(areaList, 'ddlselectedcitylist', 'javascript:BitautoCitySelect.selectDropDownList(this.text, this.value);');
	        if (this.firstShow.length > 0)
	        {
	             this.selectedList[0] =  this.firstShow;
	        } 
	        code +=  '</div>'
	        return code; 
	     }
	    code += this.generateDropDownList(areaList);
	    code +=  '<span id="' + this.divShowCity + '" >';
	    if( this.firstShow.length > 0 && this.firstShow[1] != 0) 
	    {
	        var citylist = this.getNodeList(this.tagParent,  this.firstShow[1]);
	        if (citylist.length > 0) 
	       {
	           code += this.generateDropDownList2(citylist, 'ddlselectedcitylist', 'javascript:BitautoCitySelect.selectDropDownList(this.text, this.value);');
	           this.selectedList[0] =  this.firstShow;
	       } 
	    } 
	   else
	   {
	        code += '<select ><option>所在城市</option></select>';
	   } 
	    code +=  '</span>'
	    code +=  '</div>'
        return code;
	}
	,exist: function(list, cityId)
	{
	    var exists = false;
	   for(var index=0; index < list.length; index++) 
	   {
	        if (list[index][1] == cityId)
	       {
	            exists = true;
	            break;
	       } 
	   } 
	   return exists;
	}
	,checkXml: function()
	{
        if (this.xmlDoc == null)
        {
            return;
        } 
        if(xmlDoc.parseError.errorCode != 0) 
        { 
            alert(xmlDoc.parseError.reason); 
            return; 
        } 
	}/**/
}
function transfer(obj_id) { 
    var target = document.getElementById(obj_id);
	if (target.style.display=="none")  {
        target.style.display="block"; }
	 else    { target.style.display="none";  }
}
function CitySelect()
{
    this.showMode = 1;                    // 控件显示模式 1/2/3
    this.maxCheck = 3;                      // 城市最大选择个数
    this.xmlPath = 'cityarea.xml';                             // xml 文件路径
    this.defaultArea = 0;                                            // 默认选择的地区编号
    this.outputValue = 'txtCityValue';                   // 输出城市编号的控件id
    this.outputName = 'txtCityName';                  // 输出城市名称的控件id
    this.attachControl = 'txtCityName';                   // 触发的控件id
    this.attachEvent = function(eventName)  // 触发的事件名称  onload/onfocus/onclick/onchange
    {//xmlPath, maxCheck, outputValue, outputName, attachControl, defaultArea, showMode
       var obj = this;
       switch(eventName.toLowerCase())
       {
            case 'onload':
                     BitautoCitySelect.addEvent(window, 'onload', function(){BitautoCitySelect.loadCitySelect(obj);});
                    break; 
            default:
                    BitautoCitySelect.addEvent(window, 'onload', function(){  var control = BitautoCitySelect.$(obj.attachControl);  if (control )control[eventName.toLowerCase()] = function(){BitautoCitySelect.loadCitySelect(obj);}}); 
                    break;  
       }
   };
}