//var d=new Deferred;
var callback_path="";
var block_body=true;
xmlHttp=HTTPRequest();
var rez_id;
var errorData="";
function HTTPRequest(){
 var obj;
 var navigator_sig=navigator.appName;
 if(navigator_sig=='Microsoft Internet Explorer'){
    try{
 	 obj=new ActiveXObject('Msxml2.XMLHTTP');
    }
    catch(e){
 	 obj=new ActiveXObject('Microsoft.XMLHTTP');
    }
 }
 else{
   obj=new XMLHttpRequest();
 }
 return obj;
 
}

function sendRequest(file,procRequest,id){
 //xmlHttp.setRequestHeader("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
 xmlHttp.open("get",file,true);
 xmlHttp.onreadystatechange=procRequest;
 xmlHttp.send(null);
 rez_id=id
}

function changeData(){
	//alert("123");
 if (xmlHttp.readyState==4){
  //alert(xmlHttp.responseText);
  //document.getElementById(rez_id).innerHTML+=xmlHttp.responseText;
  //if(xmlHttp.responseText!="undefined")
  //try{
  eval('('+xmlHttp.responseText+')');
 // }
  //catch(e){
  	//eval(xmlHttp.responseText);
  //}
 }
 else{
 	if(document.getElementById(rez_id)){
 		document.getElementById(rez_id).innerHTML="Подождите, идет обработка запроса....";
 	}
 	
 }
}

function set(name_){
	name_="sort_"+name_;
	setCookie("sort_first",name_,"/");
	var cookie=getCookie(name_);
	//
	
	if(!cookie){
		
		setCookie(name_,"ASC","/");
	}
	else{
		if(cookie=="ASC"){
			setCookie(name_,"DESC","/");
		}
		else if(cookie=="DESC"){
			setCookie(name_,"ASC","/");
		}
		else{
			setCookie(name_,"ASC","/");
		}
	}
	
}
function setCookie(name, value,path) {
        var curCookie = name + "=" + escape(value) +
               // ((expires) ? "; expires=" + expires.toGMTString() : "") +
                ((path) ? "; path=" + path : "")
               // ((domain) ? "; domain=" + domain : "") +
               // ((secure) ? "; secure" : "")
         //alert(curCookie);
        if ((name + "=" + escape(value)).length <= 4000){
           
                document.cookie = curCookie;
        }
        else
                if (confirm("Cookie превышает 4KB и будет вырезан !"))
                        document.cookie = curCookie
}
function getCookie(name) {
	    //alert(name);
        var prefix = name + "="
        var cookieStartIndex = document.cookie.indexOf(prefix)
        
        if (cookieStartIndex == -1)
                return null
        var cookieEndIndex = document.cookie.indexOf(";", cookieStartIndex + prefix.length)
        if (cookieEndIndex == -1)
                cookieEndIndex = document.cookie.length
        return unescape(document.cookie.substring(cookieStartIndex + prefix.length, cookieEndIndex))
}
function deleteCookie(name, path, domain) {
        if (getCookie(name)) {
                document.cookie = name + "=" + 
                ((path) ? "; path=" + path : "") +
                ((domain) ? "; domain=" + domain : "") +
                "; expires=Thu, 01-Jan-70 00:00:01 GMT"
        }
}
function selModel(cat_,id){
	//alert(cat);
	//cat=cat_.length;
	//alert(cat);
	var cat;
	var model=document.getElementById(id);
	model.innerHTML="";
	/*
	for(i=0;i<model.childNodes.length;i++){
		//alert(model.options[i].value+'='+model.options[i].innerHTML);
		model.childNodes[i].parentNode.removeChild(model.childNodes[i]);
	}
	*/
	for(m=0;m<cat_.length;m++){
		if(cat_[m].selected){
		cat=cat_[m].value;
		//alert(cat);
		for(i in optArr){
			if(i.indexOf(cat+"#")===0){
			var opt=document.createElement("option");
			opt.value=i;
			opt.innerHTML=optArr[i];
			model.appendChild(opt);
			}
		}
		//alert(cat);
		/*
	    for(i=0;i<model.options.length;i++){
		     if(i==0){model.options[0].selected='true'; continue;}
	         if(model.options[i].value.indexOf(cat+"#")===0){
	     	    model.options[i].style.display='block';
	         }
	         //else{
	     	  //  model.options[i].style.display='none';
	         //}
	    }*/
	    	}
	}
	
}
function authenticFunc(name,callback){
	var regBlockWidth,regBlockHeight;
	var reg_div=document.getElementById('reg_enter_div');
	var block_div=document.getElementById('block_screen');
	block_div.style.display='block';
	if(name=="enter_"){
			 regBlockWidth=300;
	         regBlockHeight=150;
	         reg_div.innerHTML='<div><div align=right><img style="cursor:pointer;" onclick="location.href=\''+callback+'\'" hspace=1 vspace=1 border=1 src="/close2.jpg"></div><form method=post onsubmit="return sendForm(this,\'enter_\');">'+
	                           '<table style="border-style:outset;border-width:2px;">'+
	                           '<tr><td>Логин</td><td><input type="text" name="login"></td></tr>'+
	                           '<tr><td>Пароль</td><td><input type="text" name="pass"></td></tr>'+
	                           '<tr><td colspan=2 align=center><input type=submit name=submit_ value="Войти"></td></tr><input type=hidden name=callback value="'+callback+'"'+
	                           '</table></form><div id="response"></div></div>';
	}
	else if(name=="reg_"){
			 regBlockWidth=300;
	         regBlockHeight=210;
	         reg_div.innerHTML='<div><div align=right><img style="cursor:pointer;" onclick="location.href=\''+callback+'\'" hspace=1 vspace=1 border=1 src="/close2.jpg"></div><form method=post onsubmit="return sendForm(this,\'reg_\');">'+
	                           '<table style="border-style:outset;border-width:2px;">'+
	                           '<tr><td>Логин</td><td><input type="text" name="reg_login"></td></tr>'+
	                           '<tr><td>Пароль</td><td><input type="text" name="reg_pass"></td></tr>'+
	                           '<tr><td>E-mail</td><td><input type="text" name="reg_email"></td></tr>'+
	                           '<tr><td>Город</td><td><input type="text" name="reg_city"></td></tr>'+
	                           '<tr><td colspan=2 align=center><input type=submit name=submit_ value="Зарегистрироваться"></td></tr><input type=hidden name=callback value="'+callback+'"'+
	                           '<tr><td colspan=2 align=center><font color=red>Все поля обязательны для заполнения</font></td></tr>'+
	                           '</table></form><div id="response"></div></div>';
    }
	//alert(reg_div.innerHTML);
	reg_div.style.width=regBlockWidth;
	reg_div.style.height=regBlockHeight;
	reg_div.style.top=(block_div.offsetHeight/2)-(regBlockHeight/2)-100;
	reg_div.style.left=(block_div.offsetWidth/2)-(regBlockWidth/2);
	//reg_div.innerHTML="123<br>3444444<br>666600000";
	reg_div.style.display="block";
}
function sendForm(obj,act){
	if(act=="reg_"){
		var error="";
		
		if(obj.reg_login.value.length<3){
			error+="Логин должен быть не короче 3 символов\n";
		}
		if(obj.reg_pass.value.length<3){
			error+="Пароль должен быть не короче 6 символов\n";
		}
		if(obj.reg_city.value.length<2){
			error+="Город должен быть не короче 2 символов\n";
		}
		if(!/^[A-Za-z0-9_\.]+@\w+\.\w{2,4}$/i.test(obj.reg_email.value)){
			error+="E-mail должен быть формата something@example.com\n";
		}
		if(error!=""){
			alert(error);
			return false;
		}
		var login=obj.reg_login.value;
		var email=obj.reg_email.value;
		var pass=obj.reg_pass.value;
		var city=encodeURI(obj.reg_city.value);
		sendRequest('/registry.php?act=reg&reg_login='+login+'&reg_email='+email+'&reg_pass='+pass+'&reg_city='+city,changeData,"");
		setTimeout(function(){
			         if(typeof(errorData)=="object"){
			         	var errStr="";
			         	for(i in errorData){
			         		errStr+=errorData[i]+"\n";
			         	}
			         	if(errStr!=""){
			         	 alert(errStr);
			         	}
			         	else{
			         		if(confirm("Поздравляем вы успешно зарегистрировались\nперейти к авторизации")){
			         			authenticFunc("enter_",obj.callback.value);
			         		}
			         	}
			         }
			         else{
			         	alert("Сервер перегружен, попробуйте\n повторить попытку позднее");
			         }
		},2000);


	}
	else if(act=="enter_"){
	sendRequest('/registry.php?act=login&login='+obj.login.value+'&pass='+obj.pass.value+'&callback='+obj.callback.value,changeData,'response');
	}
	return false;
	
}
function showUserInterface(text){
	var reg_div=document.getElementById('reg_enter_div');
	var block_div=document.getElementById('block_screen');
	block_div.style.display='block';
	reg_div.style.width='80%';
	reg_div.style.margin='80px';
	reg_div.style.display='block';
	//alert(text);
	reg_div.innerHTML=text;
}
function addField(obj){
	var inner=obj.parentNode.cloneNode(true);
	obj.parentNode.parentNode.appendChild(inner);
}
function delField(obj){
	obj.parentNode.parentNode.removeChild(obj.parentNode);
}
function sendForm_(obj,sendPath,callbackPath){
	//alert(sendPath+"&callback="+callbackPath);
	obj.action=sendPath+"&callback="+callbackPath;
	obj.target="upload_target";
	document.getElementById("upload_target").onload=function () {sendRequest(callbackPath,changeData,"");}
	obj.submit();
	//return false;
	
}

/**************************************Class userInterface****************************************/
function userInterface(){
 /*prepare workspace*/
	this.reg_div=document.getElementById('reg_enter_div');
	var block_div=document.getElementById('block_screen');
	block_div.style.display='block';
	this.reg_div.style.width='80%';
	this.reg_div.style.margin='80px';
	this.reg_div.style.display='block';
	
 /******************/
 /*form menu block*/
   this.formMenuBlock=function (){
    	var text="<div style='width:19%;float:left;border-style:solid;border-width:0px;text-align:left;'>"+this.formMenu(menuArr,-1)+"</div>";
    	this.reg_div.innerHTML+=text;
   }
   
   this.formMenu=function (obj,recurs_num){
   	var menu="",otstup="";
   	recurs_num++;
   	for(l=0;l<recurs_num;l++){
   		otstup+="&nbsp;&nbsp;";
   	}
   	 for(i in obj){
   	 	if(typeof(obj[i])=="object"){
   	 		menu+='<div style="margin-left:5px;">'+otstup+'<span style="text-decoration:underline;cursor:pointer" onclick="userInterface_.proccesModule(\''+(obj[i].func)+'\')">'+(obj[i].name)+'</span></div>';
   	 		menu+=this.formMenu(obj[i],recurs_num);
   	 		
   	 	}
        }
        recurs_num--;
        return menu;
   }
 /*****************/
 /*form work block*/
   this.formBodyBlock=function (){
   	//alert("module");
   	      var text="<div style='width:79%;float:left;border-style:solid;border-width:1px;' id='body_block'>"+(this.proccesModule('tableAdvertisment'))+"</div>";
   	      this.reg_div.innerHTML+=text;
   }
    
 /****************/
 /*modules*/
 this.proccesModule=function(func){
 	eval(""+func+"_ = new "+func+"();");
 	//userInterface.call(this,func);
 	//func();
 }
 /*******/
 /*Draw table advertisments*/
 /*
  this.table_adv=function (){
  	sendRequest("/index.php?js_action=showTable",changeData,"body_block");
  }
  this.table_adv_complete=function(obj){
    dataObject=eval('('+obj+')');
  	var block=document.getElementById("body_block");
  	var text="<p><table><tr><td colspan=9 align=right>"+dataObject.page+"</td></tr>"+
  	          "<tr align=center>"+
  	            "<td style='border-style:outset;border-width:2px'>Дата</td>"+
  	            "<td style='border-style:outset;border-width:2px'>Производитель</td>"+
  	            "<td style='border-style:outset;border-width:2px'>Модель</td>"+
  	            "<td style='border-style:outset;border-width:2px'>Год</td>"+
  	            "<td style='border-style:outset;border-width:2px'>Кузов</td>"+
  	            "<td style='border-style:outset;border-width:2px'>V, л</td>"+
  	            "<td style='border-style:outset;border-width:2px'>Пробег, км</td>"+
  	            "<td style='border-style:outset;border-width:2px'>Цена, руб</td>"+
  	            "<td style='border-style:outset;border-width:2px'>Действие</td>"+
  	           "</tr>";
  	for(i in dataObject){
  		if(typeof(dataObject[i])=="object"){
  		 //var object=dataObject[i];
  		 text+="<tr align=center>";
  		 text+= "<td style='border-style:solid;border-width:1px'>&nbsp;"+dataObject[i].date+"&nbsp;</td>"+
  	          "<td style='border-style:solid;border-width:1px'>&nbsp;"+dataObject[i].firma+"&nbsp;</td>"+
  	          "<td style='border-style:solid;border-width:1px'>&nbsp;"+dataObject[i].model_id+"&nbsp;</td>"+
  	          "<td style='border-style:solid;border-width:1px'>&nbsp;"+dataObject[i].year_born+"&nbsp;</td>"+
  	          "<td style='border-style:solid;border-width:1px'>&nbsp;"+dataObject[i].kuzov+"&nbsp;</td>"+
  	          "<td style='border-style:solid;border-width:1px'>&nbsp;"+dataObject[i].v+"&nbsp;</td>"+
  	          "<td style='border-style:solid;border-width:1px'>&nbsp;"+dataObject[i].probeg+"&nbsp;</td>"+
  	          "<td style='border-style:solid;border-width:1px'>&nbsp;"+dataObject[i].price+"&nbsp;</td>"+
  	          "<td style='border-style:solid;border-width:1px'>"+
  	    "&nbsp;<span style='text-decoration:underline;cursor:pointer' onclick='userInterface.description_adv(\""+dataObject[i].id+"\",\"edit\")'>Редактировать</span>&nbsp;"+
  	    "<br>&nbsp;<span style='text-decoration:underline;cursor:pointer' onclick='userInterface.description_adv(\""+dataObject[i].id+"\",\"del\")'>Удалить</span>&nbsp;"+
  	          "</td>";
  		 text+="</tr>";
  		}
  		
  	}
  	text+="</table><p>";
  	block.innerHTML=text;
  }
  */
  /*****************************/
  /****Draw full description form */
  /*
  this.description_adv=function(id,act){
  	var text="<p><table>";
  	var block=document.getElementById("body_block");
  	text+='<tr>'+
           '<td>Кузов: </td>'+
           '<td><input type="text" name="kuzov" value="'+dataObject[id].kuzov+'"></td>'+
          '</tr>'+
          '<tr>'+
           '<td>Пробег: </td>'+
           '<td><input type="text" name="probeg" value="'+dataObject[id].probeg+'"></td>'+
          '</tr>'+
          '<tr>'+
           '<td>Цвет: </td>'+
           '<td><input type="text" name="color" value="'+dataObject[id].color+'"></td>'+
          '</tr>'+
          '<tr>'+
            '<td>КПП: </td>'+
            '<td><input type="text" name="kpp" value="'+dataObject[id].kpp+'"></td>'+
          '</tr>'+
          '<tr>'+
            '<td>Объем двигателя: </td>'+
            '<td><input type="text" name="v" value="'+dataObject[id].v+'"></td>'+
          '</tr>'+
          '<tr>'+
            '<td>Цена: </td>'+
            '<td><input type="text" name="price" value="'+dataObject[id].price+'"></td>'+
          '</tr>'+
          '<tr>'+
            '<td>Доп. сведения: </td>'+
            '<td><textarea name="opis">'+dataObject[id].opis+'</textarea></td>'+
          '</tr>'+
          '<tr>'+
            '<td>Ф.И.О.: </td>'+
            '<td><input type="text" name="fio" value="'+dataObject[id].fio+'"></td>'+
          '</tr>'+
          '<tr>'+
            '<td>Телефон: </td>'+
            '<td><input type="text" name="phone" value="'+dataObject[id].phone+'"></td>'+
          '</tr>'+
          '<tr>'+
            '<td>E-mail: </td>'+
            '<td><input type="text" name="email" value="'+dataObject[id].email+'"></td>'+
          '</tr>'+
          '</table><p>';
          block.innerHTML=text;
  }
  */
  /********************************
  this.second=function (){
  	var block=document.getElementById("body_block");
  	block.innerHTML="123<br>456<br>78678678";
  }

 ***************/
  
   this.show=function (){
   	this.formMenuBlock();
   	this.formBodyBlock();
   }
   this.tt=function(){
   	alert("123");
   }
	
}
/***********************************Объявления*******************************************/
function tableAdvertisment(func){
	//tableAdvertisment.prototype=new userInterface();
	//tableAdvertisment.prototype.constructor=tableAdvertisment;
	//alert(typeof(func));
	//userInterface_.show_rez();
	
	
	this.table_adv=function (path){
		//alert(path);
  	  sendRequest(path,changeData,"body_block");
    }
    
    
  this.table_adv_complete=function(obj){
    dataObject=eval('('+obj+')');
  	var block=document.getElementById("body_block");
  	var text="<p><table><tr><td colspan=9 align=right>"+(this.pageNavigation(dataObject.page_num_,dataObject.cur_page_,dataObject.items_per_page_))+"</td></tr>"+
  	          "<tr align=center>"+
  	            "<td style='border-style:outset;border-width:2px'>Дата</td>"+
  	            "<td style='border-style:outset;border-width:2px'>Производитель</td>"+
  	            "<td style='border-style:outset;border-width:2px'>Модель</td>"+
  	            "<td style='border-style:outset;border-width:2px'>Год</td>"+
  	            "<td style='border-style:outset;border-width:2px'>Кузов</td>"+
  	            "<td style='border-style:outset;border-width:2px'>V, л</td>"+
  	            "<td style='border-style:outset;border-width:2px'>Пробег, км</td>"+
  	            "<td style='border-style:outset;border-width:2px'>Цена, руб</td>"+
  	            "<td style='border-style:outset;border-width:2px'>Действие</td>"+
  	           "</tr>";
  	for(i in dataObject){
  		if(typeof(dataObject[i])=="object"){
  		 //var object=dataObject[i];
  		 text+="<tr align=center>";
  		 text+= "<td style='border-style:solid;border-width:1px'>&nbsp;"+dataObject[i].date+"&nbsp;</td>"+
  	          "<td style='border-style:solid;border-width:1px'>&nbsp;"+dataObject[i].firma+"&nbsp;</td>"+
  	          "<td style='border-style:solid;border-width:1px'>&nbsp;"+dataObject[i].model_id+"&nbsp;</td>"+
  	          "<td style='border-style:solid;border-width:1px'>&nbsp;"+dataObject[i].year_born+"&nbsp;</td>"+
  	          "<td style='border-style:solid;border-width:1px'>&nbsp;"+dataObject[i].kuzov+"&nbsp;</td>"+
  	          "<td style='border-style:solid;border-width:1px'>&nbsp;"+dataObject[i].v+"&nbsp;</td>"+
  	          "<td style='border-style:solid;border-width:1px'>&nbsp;"+dataObject[i].probeg+"&nbsp;</td>"+
  	          "<td style='border-style:solid;border-width:1px'>&nbsp;"+dataObject[i].price+"&nbsp;</td>"+
  	          "<td style='border-style:solid;border-width:1px'>"+
  	    "&nbsp;<span style='text-decoration:underline;cursor:pointer' onclick='tableAdvertisment_.description_adv(\""+dataObject[i].id+"\",\"edit\")'>Редактировать</span>&nbsp;"+
  	    "<br>&nbsp;<span style='text-decoration:underline;cursor:pointer' onclick='tableAdvertisment_.description_adv(\""+dataObject[i].id+"\",\"del\")'>Удалить</span>&nbsp;"+
  	          "</td>";
  		 text+="</tr>";
  		}
  		
  	}
  	text+="</table><p>";
  	block.innerHTML=text;
  }
  
  this.description_adv=function(id,act){
  	var text="<p><table>";
  	var block=document.getElementById("body_block");
  	text+='<tr>'+
           '<td>Кузов: </td>'+
           '<td><input type="text" name="kuzov" value="'+dataObject[id].kuzov+'"></td>'+
          '</tr>'+
          '<tr>'+
           '<td>Пробег: </td>'+
           '<td><input type="text" name="probeg" value="'+dataObject[id].probeg+'"></td>'+
          '</tr>'+
          '<tr>'+
           '<td>Цвет: </td>'+
           '<td><input type="text" name="color" value="'+dataObject[id].color+'"></td>'+
          '</tr>'+
          '<tr>'+
            '<td>КПП: </td>'+
            '<td><input type="text" name="kpp" value="'+dataObject[id].kpp+'"></td>'+
          '</tr>'+
          '<tr>'+
            '<td>Объем двигателя: </td>'+
            '<td><input type="text" name="v" value="'+dataObject[id].v+'"></td>'+
          '</tr>'+
          '<tr>'+
            '<td>Цена: </td>'+
            '<td><input type="text" name="price" value="'+dataObject[id].price+'"></td>'+
          '</tr>'+
          '<tr>'+
            '<td>Доп. сведения: </td>'+
            '<td><textarea name="opis">'+dataObject[id].opis+'</textarea></td>'+
          '</tr>'+
          '<tr>'+
            '<td>Ф.И.О.: </td>'+
            '<td><input type="text" name="fio" value="'+dataObject[id].fio+'"></td>'+
          '</tr>'+
          '<tr>'+
            '<td>Телефон: </td>'+
            '<td><input type="text" name="phone" value="'+dataObject[id].phone+'"></td>'+
          '</tr>'+
          '<tr>'+
            '<td>E-mail: </td>'+
            '<td><input type="text" name="email" value="'+dataObject[id].email+'"></td>'+
          '</tr>'+
          '</table><p>';
          block.innerHTML=text;
  }
  this.pageNavigation=function(total,cur_page,items_per_page){
        var total=parseInt(total,10);
        var cur_page=parseInt(cur_page,10);
        var items_per_page=parseInt(items_per_page,10);
		var pageStr="";
		var pages_per_page=4;
		var pages=Math.ceil(total/items_per_page);
		var begin_page=((Math.ceil(cur_page/pages_per_page)-1)*pages_per_page)+1;
		var end_page=begin_page+pages_per_page;
		if (cur_page>pages_per_page){
		 pageStr="Страницы&nbsp;&nbsp;&nbsp; <span style='cursor:pointer' onclick='sendRequest(\"/index.php?js_action=showTable&page="+(begin_page-1)+"\",changeData,\"\")'>&laquo;</span> | ";
		}
		else {
		 pageStr="Страницы&nbsp;&nbsp;&nbsp; | ";
		}
		
		for (i=begin_page;i<end_page;i++){
			if (i==cur_page){
				pageStr+=" <strong>"+i+"</strong> | ";
			}
			else {
				pageStr+=" <span style='cursor:pointer;color:blue;text-decoration:underline' onclick='sendRequest(\"/index.php?js_action=showTable&page="+i+"\",changeData,\"\")' >"+i+"</span> | ";
			}
			if (i==pages) break;
		}
		
		if (end_page<=pages){
			pageStr+=" <span style='cursor:pointer' onclick='sendRequest(\"/index.php?js_action=showTable&page="+end_page+"\",changeData,\"\")' >&raquo;</span>";
		}
 	    return  pageStr;
  }
  
  
  if(typeof(func)=="undefined"){
  	 this.table_adv("/index.php?js_action=showTable");
    }
	
}
//tableAdvertisment.prototype=new userInterface();
/*************************************************************************************/
/*****************************************End userInterface**************************************/

/********************************__________________________________________________**************/
/****Base function****/

function extend(Child, Parent) {
    var F = function() { }
    F.prototype = Parent.prototype
    Child.prototype = new F()
    Child.prototype.constructor = Child
    Child.superclass = Parent.prototype    
}
//window.captureEvents(Event.CLICK);
//window.onclick=function(){alert("test");}
//for(i in window){
	//alert(window[i]);
//}
/**End base function**/
/*_______________________________________________________________________________*/
/****Common function****/

function showUserInterface__(){
	if(typeof(arguments[0])!='undefined'){
		menuArr=eval('('+arguments[0]+')');
		back=new Array();
		forward=new Array();
		userInterface__obj=new userInterface__();
	    userInterface__obj.show();
	}
	else{
	    sendRequest("/userInterface_new.php?js_action=loadMenu",changeData,"");
	}
}

function defineModule(name,obj){
	var parent=obj.parentNode.parentNode;
	var divArr=parent.getElementsByTagName('DIV');
	for(i=0;i<divArr.length;i++){
		divArr[i].className="";
	}
	obj.parentNode.className="selDiv";
	eval(""+name+"__obj = new "+name+"__(); if(userInterface instanceof userInterface__); extend("+name+"__,userInterface__); "+name+"__obj.loadTemplate();");
}

function startBlock(){
		tableAdvertisment__obj=new tableAdvertisment__();
		tableAdvertisment__obj.loadTemplate();
}
function sendForm__(obj,sendPath,callbackPath){
	obj.action=sendPath;
	obj.target="upload_target";
	document.getElementById("upload_target").onload=function () {sendRequest(callbackPath,changeData,"");}
	obj.submit();
	return false;
	
}
function saveCurPage(evt){
	var obj=(evt.target)?evt.target:evt.srcElement;
	if(obj.className=="link"){
		var cur_text=document.getElementById("body_block").innerHTML;
		back[back.length]="'"+cur_text+"'";
	}
}
function back_(){
	for(i in back){
		alert(i+"="+back[i]);
	}
	//document.getElementById("body_block").innerHTML=back.pop();
	//alert(back.pop());
}
function searchInit(){
	var body_search=document.getElementById("search_body");
	//body_search.style.borderStyle="solid";
	//body_search.style.borderWidth="1px";
	//alert(typeof(search_obj));
	if (typeof(search_obj)!="object"){
		search_obj=new searchEngine(body_search);
	    search_obj.init();
	}
	else{
	    search_obj=false;
		body_search.innerHTML="";
	}
}
/**End common function**/
/*_______________________________________________________________________________*/
/****Classes****/

function userInterface__(){
 /*prepare workspace*/
	this.reg_div=document.getElementById('reg_enter_div');
	var block_div=document.getElementById('block_screen');
	block_div.style.display='block';
	this.reg_div.style.width='80%';
	this.reg_div.style.margin='80px';
	this.reg_div.style.display='block';
	
 /******************/
 /*form menu block*/
   this.formMenuBlock=function (){
   	    //fnc_();
    	var text='<div style="width:19%;float:left;border-style:solid;border-width:0px;text-align:left;"><span style="cursor:pointer;color:#8B0000" onclick="location.href=\''+callback_path+'\';"> Выход</span><p>'+this.formMenu(menuArr,-1)+'</div>';
    	this.reg_div.innerHTML+=text;
   }
   
   this.formMenu=function (obj,recurs_num){
   	var menu="",otstup="";
   	recurs_num++;
   	for(l=0;l<recurs_num;l++){
   		otstup+="&nbsp;&nbsp;";
   	}
   	 for(i in obj){
   	 	if(typeof(obj[i])=="object"){
   	 		menu+='<div style="margin-left:5px;width:80%" '+((obj[i].func=="tableAdvertisment")?'class="selDiv"':'')+'>'+otstup+'<span style="text-decoration:underline;cursor:pointer" onclick="search_obj=false;defineModule(\''+(obj[i].func)+'\',this)">'+(obj[i].name)+'</span></div>';
   	 		menu+=this.formMenu(obj[i],recurs_num);
   	 		
   	 	}
        }
        recurs_num--;
        return menu;
   }
 /*****************/
 /*form work block*/
   this.formBodyBlock=function (){

   	      var text="<div style='width:79%;float:left;border-style:solid;border-width:1px;' id='body_block'>"+(startBlock())+"</div>";
   	      this.reg_div.innerHTML+=text;
   }
    
 /****************/
 /*modules*/
  this.proccesModule=function(func){
 	eval(""+func+"_ = new "+func+"();");
  }
  
   this.show=function (){
   	this.formMenuBlock();
   	this.formBodyBlock();
   }
	
}

function tableAdvertisment__(){
	
	this.table_adv=function (path){
  	  sendRequest(path,changeData,"body_block");
    }
    
    
  this.table_adv_complete=function(obj){
  	//search_obj=false;
    dataObject=eval('('+obj+')');
  	var block=document.getElementById("body_block");
  	var text="<p><table><tr><td colspan=3><span class='link' style='color:#8B0000;cursor:pointer;' onclick='tableAdvertisment__obj.description_adv();'>Добавить объявление</span></td><td colspan=7 align=right>"+(this.pageNavigation(dataObject.page_num_,dataObject.cur_page_,dataObject.items_per_page_))+"</td></tr>"+
  	          "<tr align=center>"+
  	            "<td style='border-style:outset;border-width:2px'>Дата</td>"+
  	            "<td style='border-style:outset;border-width:2px'>Город</td>"+
  	            "<td style='border-style:outset;border-width:2px'>Производитель</td>"+
  	            "<td style='border-style:outset;border-width:2px'>Модель</td>"+
  	            "<td style='border-style:outset;border-width:2px'>Год</td>"+
  	            "<td style='border-style:outset;border-width:2px'>Кузов</td>"+
  	            "<td style='border-style:outset;border-width:2px'>V, л</td>"+
  	            "<td style='border-style:outset;border-width:2px'>Пробег, км</td>"+
  	            "<td style='border-style:outset;border-width:2px'>Цена, руб</td>"+
  	            "<td style='border-style:outset;border-width:2px'>Действие</td>"+
  	           "</tr>";
  	for(i in dataObject){
  		if((typeof(dataObject[i])=="object")&&(i!="model_data")&&(i!="town")){
  		 //alert(dataObject[i].date);
  		 text+="<tr align=center>";
  		 text+= "<td style='border-style:solid;border-width:1px'>&nbsp;"+dataObject[i].date+"&nbsp;</td>"+
  		      "<td style='border-style:solid;border-width:1px'>&nbsp;"+dataObject[i].town+"&nbsp;</td>"+
  	          "<td style='border-style:solid;border-width:1px'>&nbsp;"+dataObject[i].firma_+"&nbsp;</td>"+
  	          "<td style='border-style:solid;border-width:1px'>&nbsp;"+dataObject[i].model_+"&nbsp;</td>"+
  	          "<td style='border-style:solid;border-width:1px'>&nbsp;"+dataObject[i].year_born+"&nbsp;</td>"+
  	          "<td style='border-style:solid;border-width:1px'>&nbsp;"+dataObject[i].kuzov+"&nbsp;</td>"+
  	          "<td style='border-style:solid;border-width:1px'>&nbsp;"+dataObject[i].v+"&nbsp;</td>"+
  	          "<td style='border-style:solid;border-width:1px'>&nbsp;"+dataObject[i].probeg+"&nbsp;</td>"+
  	          "<td style='border-style:solid;border-width:1px'>&nbsp;"+dataObject[i].price+"&nbsp;</td>"+
  	          "<td style='border-style:solid;border-width:1px'>"+
  	    "&nbsp;<span class='link' style='text-decoration:underline;cursor:pointer' onclick='tableAdvertisment__obj.description_adv(\""+dataObject[i].id+"\",\"edit\")'>Редактировать</span>&nbsp;"+
  	    "<br>&nbsp;<span style='text-decoration:underline;cursor:pointer' class='link' onclick='if(confirm(\"Вы уверенны\")){tableAdvertisment__obj.del_item(\""+dataObject[i].id+"\",\""+dataObject["cur_page_"]+"\")}'>Удалить</span>&nbsp;"+
  	          "</td>";
  		 text+="</tr>";
  		}
  		
  	}
  	text+="</table><p>";
  	block.innerHTML='<div align=center id=search><span style="text-decoration:underline;cursor:pointer" onclick="searchInit();">Поиск</span><div id=search_body></div></div>'+text;
  }
  this.description_adv=function(id,act){
  	var text='<p><form method=post action="" enctype="multipart/form-data" onsubmit="return sendForm__(this,\'/userInterface_new.php?js_action=add&id='+((id)?id:"")+'\',\'/userInterface_new.php?js_action=showTable&page='+((id)?dataObject["cur_page_"]:"1")+((typeof(search_obj)=="object")?search_obj.searchData:'')+'\')"><table>';
  	var block=document.getElementById("body_block");
  	var firma_option="";
  	var model_option="";
  	var year="";
  	for(i in dataObject["model_data"]){
  		firma_option+='<option value='+i+' '+((dataObject[id]&&dataObject[id].firma==i)?"selected":"")+'>'+dataObject["model_data"][i]["name"]+'</option>';
  	}
  	if(dataObject[id]&&dataObject[id].model_id!="0"){
  		for(i in dataObject["model_data"][dataObject[id].firma]["model"]){
  			model_option+='<option value='+i+' '+((dataObject[id].model_id==i)?"selected":"")+'>'+dataObject["model_data"][dataObject[id].firma]["model"][i]+'</option>'
  		}
  	}
  	else{
  		model_option+='<option value=0>Не выбрана</option>';
  	}
  	for(i=2008;i>=1940;i--){
  		year+='<option value='+i+' '+((dataObject[id]&&dataObject[id].year_born==i)?"selected":"")+'>'+i+'</option>';
  	}
  	var images="";
  	if(dataObject[id]){
  	 for(i in dataObject[id].foto){
  		images+='<div style="width:80px;float:left;" align="center"><img width="75px" style="border-style:solid;border-width:1px;" src="http://images.n-novgorod.com/auto/'+id.substring(1)+'/'+(dataObject[id].foto[i])+'"><br><span style="color:blue;text-decoration:underline;cursor:pointer" onclick="tableAdvertisment__obj.del_image(\''+id.substring(1)+'\',\''+(dataObject[id].foto[i])+'\',this)">Удалить</span></div>';
  	 }
  	}
  	
  	var kuzov='<select name="kuzov">'+
  	            '<option value="Не выбран" '+((dataObject[id]&&dataObject[id].kuzov=="Не выбран")?"selected":"")+'>Не выбран'+
  	            '<option value="Седан" '+((dataObject[id]&&dataObject[id].kuzov=="Седан")?"selected":"")+'>Седан'+
  	            '<option value="Хэтчбек" '+((dataObject[id]&&dataObject[id].kuzov=="Хэтчбек")?"selected":"")+'>Хэтчбек'+
  	            '<option value="Внедорожник" '+((dataObject[id]&&dataObject[id].kuzov=="Внедорожник")?"selected":"")+'>Внедорожник'+
  	            '<option value="Купе" '+((dataObject[id]&&dataObject[id].kuzov=="Купе")?"selected":"")+'>Купе'+
  	            '<option value="Универсал" '+((dataObject[id]&&dataObject[id].kuzov=="Универсал")?"selected":"")+'>Универсал'+
  	            '<option value="Кабриолет" '+((dataObject[id]&&dataObject[id].kuzov=="Кабриолет")?"selected":"")+'>Кабриолет'+
  	            '<option value="Пикап" '+((dataObject[id]&&dataObject[id].kuzov=="Пикап")?"selected":"")+'>Пикап'+
  	          '</select>';
  	          
    var kpp='<select name="kpp">'+
               '<option value="Не выбран" '+((dataObject[id]&&dataObject[id].kpp=="Не выбран")?"selected":"")+'>Не выбран'+
               '<option value="automat" '+((dataObject[id]&&dataObject[id].kpp=="automat")?"selected":"")+'>Автоматическая'+
               '<option value="mechanic" '+((dataObject[id]&&dataObject[id].kpp=="mechanic")?"selected":"")+'>Механическая'+
               '<option value="robot" '+((dataObject[id]&&dataObject[id].kpp=="robot")?"selected":"")+'>Роботизированная'+
               '</select>';
   var town='<select name=town_id>';
   for(i in dataObject["town"]){
   	 town+='<option value='+i.substring(1)+' '+((dataObject[id]&&dataObject[id].town_id==i.substring(1))?"selected":"")+'>'+dataObject["town"][i]+'</option>'
   }
   town+='</select>';
  	
  	text+='<tr>'+
           '<td>Город: </td>'+
           '<td>'+town+'</td>'+
          '</tr>'+
  	      '<tr>'+
           '<td>Производитель: </td>'+
           '<td><select name=firma onchange="tableAdvertisment__obj.changeModel(this.value)" style="width:50%">'+firma_option+'</select></td>'+
          '</tr>'+
          '<tr>'+
           '<td>Марка: </td>'+
           '<td id=model_id><select name=model_id style="width:50%">'+model_option+'</select></td>'+
          '</tr>'+
          '<tr>'+
           '<td>Дополнительно: </td>'+
           '<td><input type="text" style="width:100%" name="marka" value="'+((dataObject[id])?dataObject[id].marka:"")+'"></td>'+
          '</tr>'+
          '<tr>'+
           '<td>Год выпуска: </td>'+
           '<td><select name=year_born style="width:50%"><option value=0>Не выбран</option>'+year+'</select></td>'+
          '</tr>'+
  	      '<tr>'+
           '<td>Кузов: </td>'+
           '<td><!--<input type="text" name="kuzov" style="width:100%" value="'+((dataObject[id])?dataObject[id].kuzov:"")+'">-->'+kuzov+'</td>'+
          '</tr>'+
          '<tr>'+
           '<td>Пробег: </td>'+
         '<td><input type="text" name="probeg" style="width:100%" value="'+((dataObject[id])?dataObject[id].probeg:"")+'"></td>'+
          '</tr>'+
          '<tr>'+
           '<td>Цвет: </td>'+
           '<td><input type="text" name="color" style="width:100%" value="'+((dataObject[id])?dataObject[id].color:"")+'"></td>'+
          '</tr>'+
          '<tr>'+
            '<td>КПП: </td>'+
            '<td><!--<input type="text" name="kpp" style="width:100%" value="'+((dataObject[id])?dataObject[id].kpp:"")+'">-->'+kpp+'</td>'+
          '</tr>'+
          '<tr>'+
            '<td>Объем двигателя: </td>'+
            '<td><input type="text" name="v" style="width:100%" value="'+((dataObject[id])?dataObject[id].v:"")+'"></td>'+
          '</tr>'+
          '<tr>'+
            '<td>Цена: </td>'+
           '<td><input type="text" name="price" style="width:100%" value="'+((dataObject[id])?dataObject[id].price:"")+'"></td>'+
          '</tr>'+
          '<tr>'+
            '<td>Доп. сведения: </td>'+
    '<td><textarea name="opis" cols=46 rows=10 >'+((dataObject[id])?dataObject[id].opis:"")+'</textarea></td>'+
          '</tr>'+
          '<tr>'+
            '<td>Ф.И.О.: </td>'+
            '<td><input type="text" name="fio" style="width:100%" value="'+((dataObject[id])?dataObject[id].fio:"")+'"></td>'+
          '</tr>'+
          '<tr>'+
            '<td>Телефон: </td>'+
           '<td><input type="text" name="phone" style="width:100%" value="'+((dataObject[id])?dataObject[id].phone:"")+'"></td>'+
          '</tr>'+
          '<tr>'+
            '<td>E-mail: </td>'+
           '<td><input type="text" name="email" style="width:100%" value="'+((dataObject[id])?dataObject[id].email:"")+'"></td>'+
          '</tr>'+
          '<tr>'+
            '<td>Фото: </td>'+
           '<td>'+images+'<div style="clear:both;"><input type="file" name="foto[]">&nbsp;&nbsp;<input type="button" value="+" onclick="addField(this);">&nbsp;&nbsp;<input type="button" value="-" onclick="delField(this)"></div></td>'+
          '</tr>'+
          '<tr>'+
            '<td colspan=2 align=center><input type="submit" name="submit_" value="Сохранить"></td>'+
          '</tr>'+
          '</table></form><iframe id="upload_target" onload="" name="upload_target" src="" style="width:0;height:0;border:0px solid #FFFFFF;"></iframe><p>';
          block.innerHTML=text;
          return true;
          
  }
  this.pageNavigation=function(total,cur_page,items_per_page){
        var total=parseInt(total,10);
        var cur_page=parseInt(cur_page,10);
        var items_per_page=parseInt(items_per_page,10);
		var pageStr="";
		var pages_per_page=4;
		var pages=Math.ceil(total/items_per_page);
		var begin_page=((Math.ceil(cur_page/pages_per_page)-1)*pages_per_page)+1;
		var end_page=begin_page+pages_per_page;
		if (cur_page>pages_per_page){
		 pageStr="Страницы&nbsp;&nbsp;&nbsp; <span style='cursor:pointer' onclick='sendRequest(\"/userInterface_new.php?js_action=showTable&page="+(begin_page-1)+((typeof(search_obj)=="object")?search_obj.searchData:'')+"\",changeData,\"\")'>&laquo;</span> | ";
		}
		else {
		 pageStr="Страницы&nbsp;&nbsp;&nbsp; | ";
		}
		
		for (i=begin_page;i<end_page;i++){
			if (i==cur_page){
				pageStr+=" <strong>"+i+"</strong> | ";
			}
			else {
				pageStr+=" <span style='cursor:pointer;color:blue;text-decoration:underline' class='link' onclick='sendRequest(\"/userInterface_new.php?js_action=showTable&page="+i+((typeof(search_obj)=="object")?search_obj.searchData:'')+"\",changeData,\"\")' >"+i+"</span> | ";
			}
			if (i==pages) break;
		}
		
		if (end_page<=pages){
			pageStr+=" <span style='cursor:pointer' onclick='sendRequest(\"/userInterface_new.php?js_action=showTable&page="+end_page+((typeof(search_obj)=="object")?search_obj.searchData:'')+"\",changeData,\"\")' >&raquo;</span>";
		}
 	    return  pageStr;
  }
  
   this.changeModel=function(id){
   	var sel=document.getElementById("model_id");
   	var text='<select name="model_id" style="width:50%">';
   	 for(i in dataObject["model_data"][id]["model"]){
   	 	text+='<option value='+i+'>'+dataObject["model_data"][id]["model"][i]+'</option>';
   	 }
   	text+='</select>';
   	sel.innerHTML=text;
   }
   this.del_item=function(id,page){
   	//alert(id+"="+page);
   	sendRequest("/userInterface_new.php?js_action=del_item&id="+id+"&page="+page,changeData,"");
   }
   this.del_image=function(dir,name,obj){
   	obj.parentNode.parentNode.removeChild(obj.parentNode);
   	sendRequest("/userInterface_new.php?js_action=del_image&dir="+dir+"&name="+name,changeData,"");
   }
   
    this.loadTemplate=function(){
    	if(!arguments.length){
    		this.table_adv("/userInterface_new.php?js_action=showTable"+((typeof(search_obj)=="object")?search_obj.searchData:''));
    	}
    	else{
    		return true;
    	}
    }
	
}
function second__(){
	
	this.loadTemplate=function(){
		return;
	}
}

function searchEngine(body_){
	this._body_=body_
	this.searchData='';
	this.init=function(){
		this._body_.innerHTML='<p><span>Выберите режим поиска &nbsp;&nbsp;</span>'+
		                 '<select onchange="search_obj.selModule(this.value)">'+
		                  '<option value=0>не выбран'+
		                  '<option value=1>по дате'+
		                  '<option value=2>по производителю'+
		                  '<option value=3>по городу'+
		                 '</select>';
	}
	this.selModule=function(id_){
		switch (id_){
			case "1":{
				this.dateSearch();
				break;
			}
			case "2":{
				this.proizvSearch();
				break;
			}
			case "3":{
				this.townSearch();
				break;
			}
		}
	}
	
	this.dateSearch=function(){
		this._body_.innerHTML='<p><form method=post onsubmit="return search_obj.proccesedSearchForm(this);"><table>'+
		                       '<tr><td>начало <input type=text size=10 name="begin_date" id="begin_date" value="dd/mm/yy" onfocus="this.select();lcs(this)" onclick="event.cancelBubble=true;this.select();lcs(this)"></td>'+
		                       '<td>окончание <input type=text size=10 name="end_date" id="end_date" value="dd/mm/yy" onfocus="this.select();lcs(this)" onclick="event.cancelBubble=true;this.select();lcs(this)"></td>'+
		                       '</tr><tr>'+
		                       '<td colspan=2 align=center><input type="submit" value="Поиск"></td>'+
		                       '<input type=hidden name="search_type" value="date_search">'+
		                       '</tr></table></form>';
	}
	this.proizvSearch=function(){
		var firma_option='';
		for(i in dataObject["model_data"]){
  		  firma_option+='<option value='+i+'>'+dataObject["model_data"][i]["name"]+'</option>';
  	    }
		this._body_.innerHTML='<p><form method=post onsubmit="return search_obj.proccesedSearchForm(this);"><table>'+
	                     '<tr><td>Выберите производителя </td><td><select name="proizv">'+firma_option+'</select></td></tr>'+
	                     '<tr><td colspan=2 align=center><input type=submit value="Поиск">'+
	                     '<input type=hidden name="search_type" value="proizv_search"></td>'+
	                     '</tr></table></form>';
	}
	this.townSearch=function(){
		var town='<select name=town>';
		for(i in dataObject["town"]){
			town+='<option value='+i.substring(1)+'>'+dataObject["town"][i]+'</option>';
		}
		town+='</select>';
		this._body_.innerHTML='<p><form method=post onsubmit="return search_obj.proccesedSearchForm(this);"><table>'+
	                     '<tr><td>Выберите город </td><td>'+town+'</td></tr>'+
	                     '<tr><td colspan=2 align=center><input type=submit value="Поиск">'+
	                     '<input type=hidden name="search_type" value="town_search"></td>'+
	                     '</tr></table></form>';
	}
	this.proccesedSearchForm=function(obj){
		if(typeof(obj)=="object"){
			if(obj.search_type.value=="date_search"){
				
				this.searchData='&search_type=date_search&begin_date='+obj.begin_date.value+'&end_date='+obj.end_date.value+'';
			}
			else if(obj.search_type.value=="proizv_search"){
				this.searchData='&search_type=proizv_search&proizv='+obj.proizv.value;
			}
			else if(obj.search_type.value=="town_search"){
				this.searchData='&search_type=town_search&town_id='+obj.town.value;
			}
			tableAdvertisment__obj.loadTemplate();
		}
		else{
			return false;
		}
		return false;
	}
	
}

/**End classes**/

/*______________________________________________________________________________________________*/
