var showdivssel = true;

function SF_select(obj)
{
    var ItemsList = null;
    var ItemText = null;
	if (obj){
		for(i=0;i<obj.childNodes.length;i++)
	    {
			if(obj.childNodes[i].id=="SF_items") ItemsList = obj.childNodes[i];
			if(obj.childNodes[i].id=="SF_text")  ItemText = obj.childNodes[i];
	    }
	}
	if (obj) showdivssel = true;
	if (showdivssel){
		var objs = document.getElementsByTagName("DIV");
		for (i=0; i<objs.length; i++){
			if ((objs[i].id=="SF_items") && (objs[i]!=ItemsList)) objs[i].style.display = "none";
			if ((objs[i].id=="SF_text") && (objs[i]!=ItemText)) objs[i].style.border = '1px solid #B6B6B6';
		}
		showdivssel = false;
	}
	else showdivssel = true;
	
	if (ItemsList && ItemText){
	    if ((ItemsList.style.display == "none") || (ItemsList.style.display == ""))
	    {
			ItemsList.style.display = "block";
			ItemText.style.border = '1px solid #444';
	    }
	    else
	    {
			ItemsList.style.display = "none";
			ItemText.style.border = '1px solid #B6B6B6';
	    }
	}
}

function SF_set(obj)
{
    var SF_text = null;
	var SF_name = false;
    for (var i=0;i<obj.parentNode.parentNode.childNodes.length;i++){
	    if (obj.parentNode.parentNode.childNodes[i].id=="SF_text")
	        SF_text = obj.parentNode.parentNode.childNodes[i];
		if (obj.parentNode.parentNode.childNodes[i].id=="SF_name")
	        SF_name = obj.parentNode.parentNode.childNodes[i].name;
    }
	if (SF_name){
		SF_input = document.getElementById(SF_name);
		if (SF_input){
			SF_input.value = obj.innerHTML;
		}
	}
    SF_text.innerHTML = obj.innerHTML;
    if (document.forms['feedbackform']){
		var SF_input = document.forms['feedbackform'].authrub;
	    SF_input.value = obj.name;
	}
}


function setActPas(obj)
{
obj = obj.parentNode;
if (obj.parentNode.className.length==8)
	obj.parentNode.className = 'question active';
else
	obj.parentNode.className = 'question';
}

function	trim(s)
{
	return 	s.replace(/^(\s*)/,"$`").replace(/(\s*)$/,"$'");
}

function CheckFeedback(obj){
	if (trim(obj.authname.value)=="") {alert("Укажите ваше имя"); return false;}
	if (!emailCheck(obj.authmail.value)) {alert("Укажите корректный адрес электронной почты"); return false;}
	if (trim(obj.authtext.value)=="") {alert("Введите текст сообщения"); return false;}
	var rubric = 1;
	//if (obj.authrub) rubric = parseInt(obj.authrub.value,10);
	//if (isNaN(rubric)) rubric = 0;
	
	//if (rubric==0) {alert("Укажите, пожалуйста, рубрику"); return false;}
	
	var ai = new ajaxInit('/inc/sendmail.asp');
	var postVars = new Array();
		postVars['text'] = obj.authtext.value;
		postVars['rubric'] = rubric;
		postVars['authname'] = trim(obj.authname.value);
		postVars['authphone'] = trim(obj.authphone.value);
		postVars['authmail'] = trim(obj.authmail.value);
	var first = new Boolean(true);
	var postStr = '';
	for (var pkey in postVars) {
		if (!first) postStr += "&";
		postStr += pkey + "=" + encodeURI(postVars[pkey]);
		first = false;
	}
	ai.sendPost(postStr);
	return false;
}
function ajaxInit(url) {
	var timeobj = document.getElementById("feedwait");
	var sendobj = document.getElementById("feedbutton");
	var postsendobj = document.getElementById("message-send");
	url += '?uniqueID=' + (new Date()).getTime();
	var req = (window.XMLHttpRequest) ? new XMLHttpRequest : new ActiveXObject("Microsoft.XMLHTTP");
	req.onreadystatechange = processRequest;
	
	function processRequest() {
		sendobj.style.display = "none";
		timeobj.style.display = "";
		postsendobj.style.display = "none";
		if (req.readyState == 4)
			if (req.status == 200) {
				sendobj.style.display = "";
				timeobj.style.display = "none";
				postsendobj.style.display = "";
				document.forms['feedbackform'].authtext.value = "";
				HidePopUp();
			}
			else{
				alert('Ошибка, попробуйте позднее');
				sendobj.style.display = "";
				timeobj.style.display = "none";
			}
	}
	
	this.sendPost = function(postStr) {
		req.open("POST", url, true);
		req.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
		//req.setRequestHeader("Content","text/html;charset=windows-1251");
		req.send(postStr);
	}
}

IE = navigator.appName=="Microsoft Internet Explorer";
NS = navigator.appName=="Netscape";
bVer = parseInt(navigator.appVersion);
var newWin=null;

function PopUp(loc_ie, name, width, height, altname) {
	if (window.NewWindow == null || window.NewWindow.closed)
	{
		var _params = "width="+width+",height="+height+",resizable=no,status=no,scrollbars=0";
		loc_ns = loc_ie;
		if (bVer >= 4) {
				 _left = ( (screen.width-width) >>1 );
				 _top = ( (screen.height-height) >>1 );
		} else {
				 _left = ( (800-width) >>1 );
				 _top = ( (600-height) >>1 );
		}
		if (IE) _params += ",top=" + _top + ",left=" + _left;
		else if (NS) _params += ",screenX=" + _left + ",screenY=" + _top;
		else _params += ",screenX=" + _left + ",screenY=" + _top;
		newWin = window.open(loc_ie, name, _params);
		newWin.document.open();

		newWin.document.write('<html><head><title>'+((altname==undefined)?'Trade-In':altname)+'</title></head><body leftmargin=0 topmargin=0 marginwidth=0 marginheight=0><img src='+loc_ie+' height="'+height+'" width="'+width+'" onClick="parent.self.close(); return false" style="cursor:pointer" title="Закрыть окно" alt="'+((altname==undefined)?'Фотогалерея Trade-In':altname)+'"></body></html>');
		newWin.document.close();
		if ( newWin!=null )
				newWin.focus();
	}
	else
	{
		window.NewWindow.location.href = loc_ie;			
		window.NewWindow.focus();
	}
}

function PopUp2(loc_ie, name, width, height) {
	if (window.NewWindow == null || window.NewWindow.closed) {
	    var _params = "width="+width+",height="+height+",resizable=no,status=no,scrollbars=0";
		loc_ns = loc_ie;
        if (bVer >= 4) {
                 _left = ( (screen.width-width) >>1 );
       	         _top = ( (screen.height-height) >>1 );
        } else {
                 _left = ( (800-width) >>1 );
       	         _top = ( (600-height) >>1 );
        }

	    _params += ",top=" + _top + ",left=" + _left;
		newWin = window.open(loc_ie, name, _params);

	    if (newWin!=null) newWin.focus();
	}
	else {
	    window.NewWindow.location.href = loc_ie;			
		window.NewWindow.focus();
	}

}

function ShowModels(num){
	var pobj = false;
	var pobjs = document.getElementById("modeldiv");
	for (var i=0; i<pobjs.childNodes.length; i++){
		if ((pobjs.childNodes[i].tagName=="DIV") && (pobjs.childNodes[i].id=="SF_items")) pobj = pobjs.childNodes[i];
	}
	var ai = new ajaxModels(pobj);
	var postVars = new Array();
		postVars['amark'] = num;
	var first = new Boolean(true);
	var postStr = '';
	for (var pkey in postVars) {
		if (!first) postStr += "&";
		postStr += pkey + "=" + encodeURI(postVars[pkey]);
		first = false;
	}
	ai.sendPost(postStr);
}

function ajaxModels(obj) {
	modeldisabled = true;
	Setmodeldisabled();
	url = '/inc/getsitemodels.asp?uniqueID=' + (new Date()).getTime();
	var req = (window.XMLHttpRequest) ? new XMLHttpRequest : new ActiveXObject("Microsoft.XMLHTTP");
	req.onreadystatechange = processRequest;
	function processRequest() {
		if (req.readyState == 4)
			if (req.status == 200) {
				if (obj){
					var restext = req.responseText;
					var count = 0;
					if (restext.indexOf('<a')>-1){
						count = parseInt(restext.slice(0,restext.indexOf('<a')),10);
						restext = restext.slice(restext.indexOf('<a'));
					}
					if (count<=13) obj.style.cssText = "height:auto;";
					else obj.style.cssText = "height:360px;";
					obj.innerHTML = restext;
					for(var i=0;i<obj.parentNode.childNodes.length;i++){
						if (obj.parentNode.childNodes[i].id=="SF_text")
							obj.parentNode.childNodes[i].innerHTML = 'Выберите модель';
				    }
					document.getElementById('idamodelname').value = "";
					modeldisabled = false;
					Setmodeldisabled(1);
				}
			}
			else{
				alert('Ошибка, попробуйте позднее');
			}
	}
	this.sendPost = function(postStr) {
		req.open("POST", url, true);
		req.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
		req.setRequestHeader("Content","text/html;charset=windows-1251");
		req.send(postStr);
	}
}

var modeldisabled = true;

function Setmodeldisabled(newd){
	var objs = document.getElementsByName('modelsftext');
	for (var i=0; i<objs.length; i++){
		if ((objs[i].tagName=="DIV") && (objs[i].id=="SF_text")){
			if (newd==1) modeldisabled = false;
			objs[i].className = (modeldisabled)?"disable":"";
		}
	}
}

function CheckValuation(obj){
	if (trim(obj.authname.value)=="") {alert('Укажите, пожалуйста, Ваше имя'); return false;}
	if (trim(obj.authphone.value)=="") {alert('Укажите, пожалуйста, телефон'); return false;}
	if (trim(obj.amarkname.value)=="") {alert('Укажите, пожалуйста, марку автомобиля'); return false;}
	if (trim(obj.amodelname.value)=="") {alert('Укажите, пожалуйста, модель автомобиля'); return false;}
	obj.submit();
	return false;
}

function	emailCheck (emailStr) 
{
	var checkTLD=1;
	var knownDomsPat=/^(com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum)$/;
	var emailPat=/^(.+)@(.+)$/;
	var specialChars="\\(\\)><@,;:\\\\\\\"\\.\\[\\]";
	var validChars="\[^\\s" + specialChars + "\]";
	var quotedUser="(\"[^\"]*\")";
	var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/;
	var atom=validChars + '+';
	var word="(" + atom + "|" + quotedUser + ")";
	var userPat=new RegExp("^" + word + "(\\." + word + ")*$");
	var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$");
	var matchArray=emailStr.match(emailPat);
	if (matchArray==null) return false;
	var user=matchArray[1];
	var domain=matchArray[2];
	for (i=0; i<user.length; i++)	if (user.charCodeAt(i)>127) 	return false;
	for (i=0; i<domain.length; i++)	if (domain.charCodeAt(i)>127)	return false;
	if (user.match(userPat)==null) 	return false;
	var IPArray=domain.match(ipDomainPat);
	if (IPArray!=null) {	for (var i=1;i<=4;i++) if (IPArray[i]>255) return false;
		return true;
	}
	var atomPat=new RegExp("^" + atom + "$");
	var domArr=domain.split(".");
	var len=domArr.length;
	for (i=0;i<len;i++) if (domArr[i].search(atomPat)==-1)	return false;
	if (checkTLD && domArr[domArr.length-1].length!=2 &&	domArr[domArr.length-1].search(knownDomsPat)==-1)			return false;
	if (len<2)		return false;
	return true;
}

function CheckSubscribe(obj){
	if (trim(obj.submail.value)=="") {alert("Укажите E-mail"); return false;}
	if (!emailCheck(obj.submail.value)) {alert("Укажите корректный E-mail"); return false;}
	obj.submit();
}

function SetNewTableMain(tmindex,tmcol,tmorder){
	var navtab = document.getElementById("table-nav");
	var anav = new Array('Новинки','Самые&nbsp;дешевые','Самые&nbsp;дорогие');
	var ii = 0;
	for (var i=0; i<navtab.childNodes.length; i++){
		if (navtab.childNodes[i].tagName=="SPAN"){
			if (ii==tmindex){
				navtab.childNodes[i].className = "active";
				navtab.childNodes[i].innerHTML = anav[ii]+'<div class="r-top-left"></div><div class="r-top-right"></div>';
			}
			else{
				navtab.childNodes[i].className = "";
				navtab.childNodes[i].innerHTML = '<a href="javascript:SetNewTableMain('+ii+','+((ii>0)?'3':'0')+','+((ii>1)?'1':'0')+')">'+anav[ii]+'</a>';
			}
			ii++;
		}
	}
	var newtbmain = document.createElement("TABLE");
	newtbmain.className = "table-content";
	newtbmain.id = "atablemain";
	var newtmhead = document.createElement("THEAD");
	var newtmbody = document.createElement("TBODY");
	var newrh = null;
	var newtd = null;
	var newrhinner = "";
	newtbmain.appendChild(newtmhead);
	newtbmain.appendChild(newtmbody);
	for (i=0; i<atbcolumns.length; i++){
		newrh = document.createElement("TH");
		if (i==5) newrhinner = '<a style="border-bottom:none;">'+atbcolumns[i][1]+'</a>';
		else newrhinner = '<a href="javascript:SetNewTableMain('+tmindex+','+i+','+(((i==tmcol) && (tmorder==0))?'1':'0')+')"'+((i==tmcol)?' class="active"':'')+'>'+atbcolumns[i][1]+'</a>'+((i==tmcol)?'<img src="/pics/'+((tmorder==0)?'bottom':'top')+'-pointer.gif" width=6 height=11/>':'');
		if (atbcolumns[i][3]!="") newrhinner = '<p align="'+atbcolumns[i][3]+'">'+newrhinner+'</p>';
		newrhinner = '<nobr>'+newrhinner+'</nobr>';
		newrh.innerHTML = newrhinner;
		newtmhead.appendChild(newrh);
	}
	var selecttab = new Array();
	var newpos = -1;
	var j = 0;
	var debugv = '';
	for (i=0; i<atablemain[tmindex].length; i++){
		if (selecttab.length<1) selecttab[0] = atablemain[tmindex][i];
		else{
			newpos = -1;
			for (j=0; j<selecttab.length; j++){
				if (newpos<0){
					if ((!tmorder) && (atablemain[tmindex][i][atbcolumns[tmcol][0]]<selecttab[j][atbcolumns[tmcol][0]])) newpos = j;
					if ((tmorder) && (atablemain[tmindex][i][atbcolumns[tmcol][0]]>selecttab[j][atbcolumns[tmcol][0]])) newpos = j;
				}
			}
			if (newpos>-1){
				for (j=(selecttab.length-1); j>=newpos; j--){
					selecttab[j+1] = selecttab[j];
				}
				selecttab[newpos] = atablemain[tmindex][i];
			}
			else selecttab[selecttab.length] = atablemain[tmindex][i]
		}
		debugv = '';
		for (j=0; j<selecttab.length; j++){
			debugv = debugv+'\n'+j+' : '+selecttab[j][0]+' '+selecttab[j][2]+' '+selecttab[j][3];
		}
	}
	for (i=0; i<selecttab.length; i++){
		newrh = document.createElement("TR");
		if (i%2==1) newrh.className = "line";
		for (j=0; j<atbcolumns.length; j++){
			newtd = document.createElement("TD");
			if (j==3) newtd.className = 'price';
			newrhinner = selecttab[i][atbcolumns[j][2]];
			if (j<3) newrhinner = '<a href="/buy/cars/show/?aid='+selecttab[i][0]+'">'+newrhinner+'</a>';
			if (atbcolumns[j][4]!="") newrhinner = '<p align="'+atbcolumns[j][4]+'">'+newrhinner+'</p>';
			newtd.innerHTML = newrhinner;
			newrh.appendChild(newtd);
		}
		newtmbody.appendChild(newrh);
	}
	var nowtb = document.getElementById("atablemain");
	var noetbpar = nowtb.parentNode;
	noetbpar.removeChild(nowtb);
	noetbpar.removeChild(document.getElementById("pundertab"));
	noetbpar.appendChild(newtbmain);
	noetbpar.innerHTML = noetbpar.innerHTML+'<p id="pundertab">Все цены указаны в&nbsp;рублях, а&nbsp;пробег в&nbsp;километрах.</p>';
}

function searchajaxInit(url,oncomplete,onerror){
	url += '?uniqueID=' + (new Date()).getTime();
	req = (window.XMLHttpRequest) ? new XMLHttpRequest : new ActiveXObject("Microsoft.XMLHTTP");
	req.onreadystatechange = processRequest;
	function processRequest(){
		if (req.readyState == 4){
			if (req.status == 200){
				var response = req.responseText;
				if (oncomplete!='') eval(oncomplete);
			}
			else{ eval(onerror); }
		}
	}
	this.sendPost = function(postStr){
		req.open("POST", url, true);
		req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		req.send(postStr);
	}
}
function preparePostVars(postVars){
	var first = new Boolean(true);
	var postStr = '';
	for (var pkey in postVars) {
		if (!first) postStr += "&";
		postStr += pkey + "=" + encodeURI(postVars[pkey]);
		first = false;
	}
	return postStr;
}
function searchDisable(id){
	var o = document.getElementById(id);
	if (o) o.disabled = true;
}
function searchDisableAll(){
	searchDisable('search_mark');
	searchDisable('search_model');
	searchDisable('search_year');
	searchDisable('search_body');
	searchDisable('search_kpp');
	searchDisable('search_submit');
}
function searchUnDisable(id){
	var o = document.getElementById(id);
	if (o) o.disabled = false;
}
function searchUnDisableAll(){
	searchUnDisable('search_mark');
	searchUnDisable('search_model');
	searchUnDisable('search_year');
	searchUnDisable('search_body');
	searchUnDisable('search_kpp');
	searchUnDisable('search_submit');
}
function searchGetValue(id){
	var o = document.getElementById(id);
	if (o) return trim(o.value);
	return '';
}
function searchPrepareDiv(id,response){
	var o = document.getElementById(id);
	if (o) o.innerHTML = response;
}
function searchError(){ alert("К сожалению поиск недоступен в данный момент"); }
function searchEndLoadAction(){ searchUnDisableAll(); }
function searchStartLoadAction(){
	searchDisableAll();
	searchLoadMark();
}
function searchLoadMark(){
	var oreq = new searchajaxInit('/inc/search/marks.asp','searchPrepareDiv("search_mark_div",response);searchOnMarkLoadAction();','searchError();');
	oreq.sendPost(preparePostVars({"mark_id":searchGetValue('search_mark')}));
}
function searchOnMarkLoadAction(){ searchDisableAll(); searchLoadModel(); }
function searchLoadModel(){
	var oreq = new searchajaxInit('/inc/search/models.asp','searchPrepareDiv("search_model_div",response);searchOnModelLoadAction();','searchError();');
	oreq.sendPost(preparePostVars({"mark_id":searchGetValue('search_mark'),"model_id":searchGetValue('search_model')}));
}
function searchOnModelLoadAction(){ searchDisableAll(); searchLoadYear(); }
function searchLoadYear(){
	var oreq = new searchajaxInit('/inc/search/years.asp','searchPrepareDiv("search_year_div",response);searchOnYearLoadAction();','searchError();');
	oreq.sendPost(preparePostVars({"mark_id":searchGetValue('search_mark'),"model_id":searchGetValue('search_model'),"year":searchGetValue('search_year')}));
}
function searchOnYearLoadAction(){ searchDisableAll(); searchLoadBody(); }
function searchLoadBody(){
	var oreq = new searchajaxInit('/inc/search/bodies.asp','searchPrepareDiv("search_body_div",response);searchOnBodyLoadAction();','searchError();');
	oreq.sendPost(preparePostVars({"mark_id":searchGetValue('search_mark'),"model_id":searchGetValue('search_model'),"year":searchGetValue('search_year'),"body_id":searchGetValue('search_body')}));
}
function searchOnBodyLoadAction(){ searchDisableAll(); searchLoadKpp(); }
function searchLoadKpp(){
	var oreq = new searchajaxInit('/inc/search/kpp.asp','searchPrepareDiv("search_kpp_div",response);searchOnKppLoadAction();','searchError();');
	oreq.sendPost(preparePostVars({"mark_id":searchGetValue('search_mark'),"model_id":searchGetValue('search_model'),"year":searchGetValue('search_year'),"body_id":searchGetValue('search_body'),"kpp_id":searchGetValue('search_kpp')}));
}
function searchOnKppLoadAction(){ searchEndLoadAction(); }
