//аякс
//url - url страницы
//element - ид-р элемента
function myAjax(url,element) {
    req = null;
    if (window.XMLHttpRequest) {
        try {
            req = new XMLHttpRequest();
        } catch (e){}
    } else if (window.ActiveXObject) {
        try {
            req = new ActiveXObject('Msxml2.XMLHTTP');
        } catch (e){
            try {
                req = new ActiveXObject('Microsoft.XMLHTTP');
            } catch (e){}
        }
    }

    if (req) {
        req.onreadystatechange = function() { processReqChange(element); };
        req.open("GET", url, true);
        req.send(null);
       // reqTimeout = setTimeout("req.abort();", 5000);
    } else {
        alert("Браузер не поддерживает AJAX");
    }
}

function processReqChange(element) {
    if (req.readyState == 4) {
        // only if "OK"
        if (req.status == 200) {
            document.getElementById(element).innerHTML = req.responseText;
        } else {
			//processReqChange(element);
           // alert("Не удалось получить данные:\n" + req.statusText);
        }
    }
}

//проверка комментарие в новостях
function SetComment(){
	if (document.comment.Text.value == "")
		alert("Поле 'Tекст' должно быть заполнено");
	else {document.comment.submit();}

}

//ограничивает длину комментария в новостях
function StrLen(){
	var str = new String;
	str = document.comment.Text.value;
	if (str.length >= 250) {
		window.event.returnValue=false;
		document.comment.Text.value = str.substr(0,250);
	}

}

//ограничивает дилину текста
//name - ид-р элемента
//len - кол-во символов
function LengthStr(name,len){
	var str = new String;
	str = document.getElementById(name).value;
	if (str.length >= len) {
		window.event.returnValue=false;
		document.getElementById(name).value = str.substr(0,len);
	}

}

//переключатель формы поиска резюме/работы
function SelectSearchJob(obj,curActive){
	obj.className = 'active';
	document.getElementById(curActive).className = 'noactive';
	document.getElementById('job').value = obj.id;
	document.getElementById('job_search').action = "index.php?page=job&search="+obj.id;
	name = (obj.id == 'resume') ? 'резюме' : 'вакансии';
	html = 'Поиск '+name;
	document.getElementById('head').innerHTML = html;}

//отправка с формы с ид-ром name
function Submit(name){
	document.getElementById(name).submit();
}

//разрешает набор только чисел
function Numbers(e)
{
	var keynum;
	var keychar;
	var numcheck;if(window.event) // IE
	  {
	  keynum = e.keyCode;
	  }
	else if(e.which) // Netscape/Firefox/Opera
	  {
	  keynum = e.which;
	  }
	keychar = String.fromCharCode(keynum);
	numcheck = /\d/;
	return numcheck.test(keychar);
}

//разрешает набор числа "." и ","
function Float(e)
{
	var keynum;
	var keychar;
	var numcheck;if(window.event) // IE
	  {
	  keynum = e.keyCode;
	  }
	else if(e.which) // Netscape/Firefox/Opera
	  {
	  keynum = e.which;
	  }
	keychar = String.fromCharCode(keynum);
	numcheck = /\d|\.|,/;
	return numcheck.test(keychar);
}

//разрешает печать числа или "-"
function Telephon(e)
{
	var keynum;
	var keychar;
	var numcheck;if(window.event) // IE
	  {
	  keynum = e.keyCode;
	  }
	else if(e.which) // Netscape/Firefox/Opera
	  {
	  keynum = e.which;
	  }
	keychar = String.fromCharCode(keynum);
	numcheck = /\d|-|,/;
	return numcheck.test(keychar);
}

//проверка формы регистрация
function CheckRegistr()
{  var str = "";
	if(registr.email.value == ""){		str = "Поле 'E-mail' должно быть заполнено; \n";
	}else if(!valid_email(registr.email.value)){		str = "Поле 'E-mail' заполнено некорректно;\n";	}
	if (registr.pass.value == "")
		str = str+"Поле 'Пароль для входа' должно быть заполнено; \n";
	else if(registr.pass.value != registr.pass2.value){		str = str+"Разные значения полей 'Пароль для входа' и 'Пароль для входа';\n";
	}
	if(registr.code.value == ""){		str = str+"Поле 'Код' должно быть заполнено;";
	}
	if (str == ""){		registr.submit();
	}else alert(str);
}

//проверка формы авторизация
function CheckAuthoriz()
{
	if (document.author.email.value == "" || document.author.email.value == ""){	 	alert("Неверный e-mail или пароль");
	}else document.author.submit();
}

//форма фото
function AddPhoto(){
	window.open('index.php?page=auto&ajax=open','add_photo','width=450 height=150');
}

//форма подачи объявления продажа
function auto_sale(){
	myAjax("index.php?page=auto&ajax=sale","form_sale");
}

//форма подачи объявления покупки
function auto_purchase(){   myAjax("index.php?page=auto&ajax=purchase","form_sale");
}

//выбор марки
function SelectManufacture(id){
	myAjax("index.php?page=auto&ajax=model&modelID="+id,"select_model");
}

//выбор модификации
function SelectModification(id){
	myAjax("index.php?page=auto&ajax=modification&modifID="+id,"s_modification");
}

//загрузка фото
function reloadPhoto(html){
	window.opener.document.getElementById('photos').innerHTML = html;
	window.close();
}

//перезагрузка фотографий при удалении фото
function deletePhoto(id){
	myAjax("index.php?page=auto&ajax=delete&deleteID="+id,"photos");
}

//проверка телефона
function CheckTel(){
	var res = true;	if (document.sale.tel.value == "" || document.sale.tel_1.value == "" || document.sale.tel_2.value == ""){
	 	alert("Поле 'Телефон' должно быть заполнено");
	 	res = false;
	}
	return res;
}

//удаление объявления
function deleteAd(id){
	myAjax("index.php?page=auto&ajax=deleteAd&deleteID="+id,"ad");
}

//Сортировка по дате в "Мои объявления"
function SortDate(obj){	myAjax('index.php?page=auto&ajax=cabinet&sort='+obj.name,'center');
}

function CheckForDisabled(obj){
   if (obj[obj.selectedIndex].disabled == true)   		obj[0].selected = true;
}

function CurPhoto(photo){
	myAjax('index.php?page=auto&ajax=loadImg&img='+photo,'img');}
function CheckMail(){	var str = "";
	if (document.mail.email.value == ""){		str = "Поле 'Ваш e-mail' должно быть заполнено \n";	}
	if (!valid_email(document.mail.email.value) && document.mail.email.value != ""){	   str = "Поле 'Ваш e-mail' заполнено некорректно;\n";
	}
	if (document.mail.text.value == ""){
		str = str+"Поле 'Текст' должно быть заполнено";
	}
	if (str == ""){		document.mail.submit();
	}else{	    alert(str);
	}}

function auto_search(obj,curActive){   	obj.className = 'active';
	document.getElementById(curActive).className = 'noactive';
	document.getElementById('search').action = "index.php?page=auto&searchlist="+obj.id;
}

function auto_new(cur){   if (cur == "bu"){      document.getElementById('bu').innerHTML = "<i>[ <span class='b grey_t'>Б/У</span> ]</i>";
      document.getElementById('n').innerHTML =  "<i>[ <a href=\"javascript:auto_new('n');\">Новые</a> ]</i>";
      document.getElementById('new').value = 0;
      document.getElementById('year').disabled = false;   }else{   	  document.getElementById('bu').innerHTML = "<i>[ <a href=\"javascript:auto_new('bu');\">Б/У</a> ]</i>";
   	  document.getElementById('year').disabled = true;
      document.getElementById('n').innerHTML =  "<i>[  <span class='b grey_t'>Новые</span> ]</i>";
      document.getElementById('new').value = 1;   }
}

function auto_year(){
	var index = 0;
	var now=new Date();
	var curyear=now.getFullYear();
	if (document.search.year.value != ""){	   document.search.year2.disabled = false;
	}else{		document.search.year2.disabled = true;
		document.search.year2.options[0].selected = true;
	}
	for (i=1950;i<curyear;i++){  		if (i < document.search.year.value){
  			index =curyear-i+1;  			document.search.year2.options[index].disabled = true;
  			document.search.year2.options[index].style.color = '#afb0b0';
  		}else{
  			index =curyear-i+1;
  			document.search.year2.options[index].disabled = false;
  			document.search.year2.options[index].style.color = 'black';  		}
  	}
  	CheckForDisabled(document.search.year2);
}

function auto_hours(id1,id2){
	for (i=0;i<=23;i++){
  		if (i < document.getElementById(id1).selectedIndex && i != 0){
  			document.getElementById(id2).options[i].disabled = true;
  			document.getElementById(id2).options[i].style.color = '#afb0b0';
  		}else{
  			document.getElementById(id2).options[i].disabled = false;
  			document.getElementById(id2).options[i].style.color = 'black';
  		}
  	}
  	//auto_hours_select(id1,id2);
}

function auto_hours_select(id1,id2){	if (document.getElementById(id2).options[document.getElementById(id2).selectedIndex].disabled == true)		document.getElementById(id2).options[document.getElementById(id1).selectedIndex].selected = true;}

function ChangeColor(id){
	if (document.getElementById(id).className == "red"){	   document.getElementById(id).className = "";
	}else{	   document.getElementById(id).className = "red";
	}}

function ChangeColorCatalog(id){
	if (document.getElementById(id).className == "f15 b red"){
	   document.getElementById(id).className = "f15 b";
	}else{
	   document.getElementById(id).className = "f15 b red";
	}
}

function ChangeColorCatalog2(id){
	if (document.getElementById(id).className == "f13 b red"){
	   document.getElementById(id).className = "f13 b";
	}else{
	   document.getElementById(id).className = "f13 b red";
	}
}

function SetRed(id){	document.getElementById(id).className = "f13 b red";
}

var isIE = false;
    var ua = navigator.userAgent.toLowerCase();
	isIE = (ua.indexOf("msie") != -1 && ua.indexOf("opera") == -1 && ua.indexOf("webtv") == -1);

   	function checkLoginMain(is_enter){
	  var login = document.getElementById('login');
	  if (is_enter){
	    login.className = "width90px";
	    if (login.value == "Логин") login.value = "";
	    login.focus();
	  }
	  else{
	    if (login.value == ""){
	      login.className = "width90px grey";
	      login.value = "Логин";
	    }
	  }
	}


   	function checkPasswordMain(is_enter)
   	{
		 if(!isIE)
		 {
		    var password = document.getElementById('password');

		    if (is_enter)
		    {
		      password.className = "width90px";
		      password.setAttribute("type", "password");
		      if (password.value == "Пароль") password.value = "";
		      password.focus();
		    }
		    else
		    {
		      if (password.value == "")
		      {
		        password.className = "width90px grey";
		        password.setAttribute("type", "text");
		        password.value = "Пароль";
		      }
		    }
		 }
	}

	function initiateLoginPassword(){
       var login = document.getElementById('login');
  	   //alert(login);
  	   login.className = "width90px grey";

       if(!isIE)
       {
		    var password = document.getElementById('password');
		    password.className = "width90px grey";
		    password.setAttribute("type", "text");
		    password.value = "Пароль";
		}
	}
