var login_div;
var reg_div;
var main_div;
var mail_div;
var showed=0;
var reg_show=0;
var ad_start=0;
var urlafterlogin;
var hexcase = 0;  /* hex output format. 0 - lowercase; 1 - uppercase        */
var b64pad  = ""; /* base-64 pad character. "=" for strict RFC compliance   */
var chrsz   = 8;  /* bits per input character. 8 - ASCII; 16 - Unicode      */
var inbig=0, insmall=0;
var custom_after_login = null;
var crush = new Array();
var testdrive = new Array();
var js1 = new Array();
var js2 = new Array();
var js = new Array();
var istest = 0;

/*
 * These are the functions you'll usually want to call
 * They take string arguments and return either hex or base-64 encoded strings
 */
function hex_md5(s){ return binl2hex(core_md5(str2binl(s), s.length * chrsz));}
function b64_md5(s){ return binl2b64(core_md5(str2binl(s), s.length * chrsz));}
function str_md5(s){ return binl2str(core_md5(str2binl(s), s.length * chrsz));}
function hex_hmac_md5(key, data) { return binl2hex(core_hmac_md5(key, data)); }
function b64_hmac_md5(key, data) { return binl2b64(core_hmac_md5(key, data)); }
function str_hmac_md5(key, data) { return binl2str(core_hmac_md5(key, data)); }

/*
 * Perform a simple self-test to see if the VM is working
 */
function md5_vm_test()
{
  return hex_md5("abc") == "900150983cd24fb0d6963f7d28e17f72";
}

/*
 * Calculate the MD5 of an array of little-endian words, and a bit length
 */
function core_md5(x, len)
{
  /* append padding */
  x[len >> 5] |= 0x80 << ((len) % 32);
  x[(((len + 64) >>> 9) << 4) + 14] = len;

  var a =  1732584193;
  var b = -271733879;
  var c = -1732584194;
  var d =  271733878;

  for(var i = 0; i < x.length; i += 16)
  {
    var olda = a;
    var oldb = b;
    var oldc = c;
    var oldd = d;

    a = md5_ff(a, b, c, d, x[i+ 0], 7 , -680876936);
    d = md5_ff(d, a, b, c, x[i+ 1], 12, -389564586);
    c = md5_ff(c, d, a, b, x[i+ 2], 17,  606105819);
    b = md5_ff(b, c, d, a, x[i+ 3], 22, -1044525330);
    a = md5_ff(a, b, c, d, x[i+ 4], 7 , -176418897);
    d = md5_ff(d, a, b, c, x[i+ 5], 12,  1200080426);
    c = md5_ff(c, d, a, b, x[i+ 6], 17, -1473231341);
    b = md5_ff(b, c, d, a, x[i+ 7], 22, -45705983);
    a = md5_ff(a, b, c, d, x[i+ 8], 7 ,  1770035416);
    d = md5_ff(d, a, b, c, x[i+ 9], 12, -1958414417);
    c = md5_ff(c, d, a, b, x[i+10], 17, -42063);
    b = md5_ff(b, c, d, a, x[i+11], 22, -1990404162);
    a = md5_ff(a, b, c, d, x[i+12], 7 ,  1804603682);
    d = md5_ff(d, a, b, c, x[i+13], 12, -40341101);
    c = md5_ff(c, d, a, b, x[i+14], 17, -1502002290);
    b = md5_ff(b, c, d, a, x[i+15], 22,  1236535329);

    a = md5_gg(a, b, c, d, x[i+ 1], 5 , -165796510);
    d = md5_gg(d, a, b, c, x[i+ 6], 9 , -1069501632);
    c = md5_gg(c, d, a, b, x[i+11], 14,  643717713);
    b = md5_gg(b, c, d, a, x[i+ 0], 20, -373897302);
    a = md5_gg(a, b, c, d, x[i+ 5], 5 , -701558691);
    d = md5_gg(d, a, b, c, x[i+10], 9 ,  38016083);
    c = md5_gg(c, d, a, b, x[i+15], 14, -660478335);
    b = md5_gg(b, c, d, a, x[i+ 4], 20, -405537848);
    a = md5_gg(a, b, c, d, x[i+ 9], 5 ,  568446438);
    d = md5_gg(d, a, b, c, x[i+14], 9 , -1019803690);
    c = md5_gg(c, d, a, b, x[i+ 3], 14, -187363961);
    b = md5_gg(b, c, d, a, x[i+ 8], 20,  1163531501);
    a = md5_gg(a, b, c, d, x[i+13], 5 , -1444681467);
    d = md5_gg(d, a, b, c, x[i+ 2], 9 , -51403784);
    c = md5_gg(c, d, a, b, x[i+ 7], 14,  1735328473);
    b = md5_gg(b, c, d, a, x[i+12], 20, -1926607734);

    a = md5_hh(a, b, c, d, x[i+ 5], 4 , -378558);
    d = md5_hh(d, a, b, c, x[i+ 8], 11, -2022574463);
    c = md5_hh(c, d, a, b, x[i+11], 16,  1839030562);
    b = md5_hh(b, c, d, a, x[i+14], 23, -35309556);
    a = md5_hh(a, b, c, d, x[i+ 1], 4 , -1530992060);
    d = md5_hh(d, a, b, c, x[i+ 4], 11,  1272893353);
    c = md5_hh(c, d, a, b, x[i+ 7], 16, -155497632);
    b = md5_hh(b, c, d, a, x[i+10], 23, -1094730640);
    a = md5_hh(a, b, c, d, x[i+13], 4 ,  681279174);
    d = md5_hh(d, a, b, c, x[i+ 0], 11, -358537222);
    c = md5_hh(c, d, a, b, x[i+ 3], 16, -722521979);
    b = md5_hh(b, c, d, a, x[i+ 6], 23,  76029189);
    a = md5_hh(a, b, c, d, x[i+ 9], 4 , -640364487);
    d = md5_hh(d, a, b, c, x[i+12], 11, -421815835);
    c = md5_hh(c, d, a, b, x[i+15], 16,  530742520);
    b = md5_hh(b, c, d, a, x[i+ 2], 23, -995338651);

    a = md5_ii(a, b, c, d, x[i+ 0], 6 , -198630844);
    d = md5_ii(d, a, b, c, x[i+ 7], 10,  1126891415);
    c = md5_ii(c, d, a, b, x[i+14], 15, -1416354905);
    b = md5_ii(b, c, d, a, x[i+ 5], 21, -57434055);
    a = md5_ii(a, b, c, d, x[i+12], 6 ,  1700485571);
    d = md5_ii(d, a, b, c, x[i+ 3], 10, -1894986606);
    c = md5_ii(c, d, a, b, x[i+10], 15, -1051523);
    b = md5_ii(b, c, d, a, x[i+ 1], 21, -2054922799);
    a = md5_ii(a, b, c, d, x[i+ 8], 6 ,  1873313359);
    d = md5_ii(d, a, b, c, x[i+15], 10, -30611744);
    c = md5_ii(c, d, a, b, x[i+ 6], 15, -1560198380);
    b = md5_ii(b, c, d, a, x[i+13], 21,  1309151649);
    a = md5_ii(a, b, c, d, x[i+ 4], 6 , -145523070);
    d = md5_ii(d, a, b, c, x[i+11], 10, -1120210379);
    c = md5_ii(c, d, a, b, x[i+ 2], 15,  718787259);
    b = md5_ii(b, c, d, a, x[i+ 9], 21, -343485551);

    a = safe_add(a, olda);
    b = safe_add(b, oldb);
    c = safe_add(c, oldc);
    d = safe_add(d, oldd);
  }
  return Array(a, b, c, d);

}

/*
 * These functions implement the four basic operations the algorithm uses.
 */
function md5_cmn(q, a, b, x, s, t)
{
  return safe_add(bit_rol(safe_add(safe_add(a, q), safe_add(x, t)), s),b);
}
function md5_ff(a, b, c, d, x, s, t)
{
  return md5_cmn((b & c) | ((~b) & d), a, b, x, s, t);
}
function md5_gg(a, b, c, d, x, s, t)
{
  return md5_cmn((b & d) | (c & (~d)), a, b, x, s, t);
}
function md5_hh(a, b, c, d, x, s, t)
{
  return md5_cmn(b ^ c ^ d, a, b, x, s, t);
}
function md5_ii(a, b, c, d, x, s, t)
{
  return md5_cmn(c ^ (b | (~d)), a, b, x, s, t);
}

/*
 * Calculate the HMAC-MD5, of a key and some data
 */
function core_hmac_md5(key, data)
{
  var bkey = str2binl(key);
  if(bkey.length > 16) bkey = core_md5(bkey, key.length * chrsz);

  var ipad = Array(16), opad = Array(16);
  for(var i = 0; i < 16; i++)
  {
    ipad[i] = bkey[i] ^ 0x36363636;
    opad[i] = bkey[i] ^ 0x5C5C5C5C;
  }

  var hash = core_md5(ipad.concat(str2binl(data)), 512 + data.length * chrsz);
  return core_md5(opad.concat(hash), 512 + 128);
}

/*
 * Add integers, wrapping at 2^32. This uses 16-bit operations internally
 * to work around bugs in some JS interpreters.
 */
function safe_add(x, y)
{
  var lsw = (x & 0xFFFF) + (y & 0xFFFF);
  var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
  return (msw << 16) | (lsw & 0xFFFF);
}

/*
 * Bitwise rotate a 32-bit number to the left.
 */
function bit_rol(num, cnt)
{
  return (num << cnt) | (num >>> (32 - cnt));
}

/*
 * Convert a string to an array of little-endian words
 * If chrsz is ASCII, characters >255 have their hi-byte silently ignored.
 */
function str2binl(str)
{
  var bin = Array();
  var mask = (1 << chrsz) - 1;
  for(var i = 0; i < str.length * chrsz; i += chrsz)
    bin[i>>5] |= (str.charCodeAt(i / chrsz) & mask) << (i%32);
  return bin;
}

/*
 * Convert an array of little-endian words to a string
 */
function binl2str(bin)
{
  var str = "";
  var mask = (1 << chrsz) - 1;
  for(var i = 0; i < bin.length * 32; i += chrsz)
    str += String.fromCharCode((bin[i>>5] >>> (i % 32)) & mask);
  return str;
}

/*
 * Convert an array of little-endian words to a hex string.
 */
function binl2hex(binarray)
{
  var hex_tab = hexcase ? "0123456789ABCDEF" : "0123456789abcdef";
  var str = "";
  for(var i = 0; i < binarray.length * 4; i++)
  {
    str += hex_tab.charAt((binarray[i>>2] >> ((i%4)*8+4)) & 0xF) +
           hex_tab.charAt((binarray[i>>2] >> ((i%4)*8  )) & 0xF);
  }
  return str;
}

/*
 * Convert an array of little-endian words to a base-64 string
 */
function binl2b64(binarray)
{
  var tab = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  var str = "";
  for(var i = 0; i < binarray.length * 4; i += 3)
  {
    var triplet = (((binarray[i   >> 2] >> 8 * ( i   %4)) & 0xFF) << 16)
                | (((binarray[i+1 >> 2] >> 8 * ((i+1)%4)) & 0xFF) << 8 )
                |  ((binarray[i+2 >> 2] >> 8 * ((i+2)%4)) & 0xFF);
    for(var j = 0; j < 4; j++)
    {
      if(i * 8 + j * 6 > binarray.length * 32) str += b64pad;
      else str += tab.charAt((triplet >> 6*(3-j)) & 0x3F);
    }
  }
  return str;
}
  
function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*30*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}
  
function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}
function isemptyCookie(name) {
	s = readCookie(name);
    if((s=='')||(s==null)) { return 1; }
	return 0;
}

function getPageScroll(){

	var yScroll;

	if (self.pageYOffset) {
		yScroll = self.pageYOffset;
	} else if (document.documentElement && document.documentElement.scrollTop){	 // Explorer 6 Strict
		yScroll = document.documentElement.scrollTop;
	} else if (document.body) {// all other Explorers
		yScroll = document.body.scrollTop;
	}

	arrayPageScroll = new Array('',yScroll) 
	return arrayPageScroll;
}

function getPageSize(){
	
	var xScroll, yScroll;
	
	if (window.innerHeight && window.scrollMaxY) {	
		xScroll = document.body.scrollWidth;
		yScroll = window.innerHeight + window.scrollMaxY;
	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;
	} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		xScroll = document.body.offsetWidth;
		yScroll = document.body.offsetHeight;
	}
	
	var windowWidth, windowHeight;
	if (self.innerHeight) {	// all except Explorer
		windowWidth = self.innerWidth;
		windowHeight = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	} else if (document.body) { // other Explorers
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	}	
	
	// for small pages with total height less then height of the viewport
	if(yScroll < windowHeight){
		pageHeight = windowHeight;
	} else { 
		pageHeight = yScroll;
	}

	// for small pages with total width less then width of the viewport
	if(xScroll < windowWidth){	
		pageWidth = windowWidth;
	} else {
		pageWidth = xScroll;
	}


	arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight) 
	return arrayPageSize;
}


function getClientWidth(){
  if(window.opera){ return window.innerWidth; }
  return (document.compatMode=='CSS1Compat' && !window.opera)?document.documentElement.clientWidth:document.body.clientWidth;
}

function getClientHeight(){
  if(window.opera){ return 800; }
  return (document.compatMode=='CSS1Compat' && !window.opera)?document.documentElement.clientHeight:document.body.clientHeight;
}


/*function getDocumentHeight()
{
    return (document.body.scrollHeight > document.body.offsetHeight)?document.body.scrollHeight:document.body.offsetHeight;
}
//Размер документа по горизонтали
function getDocumentWidth()
{
    return (document.body.scrollWidth > document.body.offsetWidth)?document.body.scrollWidth:document.body.offsetWidth;
}
*/

function do_register(){
  ulogin = document.frmregister.rlogin.value;
  upass1 = document.frmregister.password.value;
  upass2 = document.frmregister.password2.value;
  uregion = document.frmregister.regions.value;
  //alert(uregion);
  if(ulogin=='') { alert("Не указан email"); return; }
  if((upass1=='')||(upass2=='')) { alert("Пароль не соответствует ограничениям"); return; }
  if(uregion==-1) { alert("Не указан регион"); return; }
    $.get("ajax_check.php", { command: "register", login: ulogin, password: upass1, region: uregion },
      function(res){
        alert(res);
      });
  reg_close();
}

function load_login2(){
  ulogin = readCookie('login');
  upass = readCookie('password');
  if((ulogin=='')||(upass=='')) { return; }    
   $.get("/ajax_check.php", { command: "login2", login: ulogin, password: upass },
      function(res){
        resp = eval('('+res+')');
        /*$("div#yui-gen6").html(res);*/
        if(resp.login=='1') {
          $('#toplogin').html("<img src='/img/main-menu/profile-icon-bw.gif' border='0'> Мой профиль");
          $('#toplogin').unbind('click', void(0));
          $('#toplogin').attr('onclick' , 'void(0)');
          $('#toplogin').attr('href', '/profile/');
          $('#submenu_myobj').html('<a class="yuimenuitemlabel" href="/myobj/">Мои объявления</a>');
          $('#submenu_mydoc').html('<a class="yuimenuitemlabel" href="/mydocs/">Мои автодокументы</a>');
          $('#submenu_notepad').html('<a class="yuimenuitemlabel" href="/notepad/">Блокнот</a>');
          $('#submenu_mail').html('<a class="yuimenuitemlabel" href="/mail/">Сообщения</a>');
          $('#submenu_exit').html('<a class="yuimenuitemlabel" onclick="do_logout2()" href="javascript:void(0)">Выход</a>');
          if(resp.comptype=='1'){
            $("div#bottomlogin").html('<a href="/profile/" class="headprofilelink">'+readCookie("login")+'</a><br><a  href="/myobj/">Мои объявления</a><br><a  href="/mail/">Сообщения</a><br><a  href="/stat/">Статистика</a>');
          } else {
            $("div#bottomlogin").html('<a href="/profile/" class="headprofilelink">'+readCookie("login")+'</a><br><a  href="/myobj/">Мои объявления</a><br><a  href="/mydocs/">Мои автодокументы</a><br><a  href="/notepad/">Блокнот</a><br><a  href="/mail/">Сообщения</a>');
          }}
      });
  login_close();
}

function load_login(){
  load_login2();
}

function do_logout2(){
  eraseCookie('login');
  eraseCookie('password');
  $.get("/ajax_check.php", { command: "logout2" },
      function(res){
        //$("div#yui-gen6").html(res);
        resp = eval('('+res+')');
        $('#toplogin').html("<img src='/img/main-menu/profile-icon-bw.gif' border='0'> Войти");
        $('#toplogin').attr('href', 'javascript:void(0)');
        $('#toplogin').click(function(){ login_window(); });
        //$('#toplogin').$('#toplogin').attr('onclick', 'login_window()');
        $('#submenu_myobj').hide();
        $('#submenu_mydoc').html('<a class="yuimenuitemlabel" onclick="reg_window()" href="javascript:void(0)">Регистрация</a>');
        $('#submenu_notepad').hide();
        $('#submenu_mail').hide();
        $('#submenu_exit').hide();
        $("div#bottomlogin").html('<a class="maina" href="javascript:void(0)" onclick="login_window();">Вход</a><br><a  href="javascript:void(0)" onclick="reg_window();">Регистрация</a>');
		if(readCookie('personal')==1) { document.location = '/'; }
      });
}

function do_logout(){
  do_logout2();
}

function setPersonal(id) {
  createCookie('personal', id, 1);
}

function do_mail(){
  ulogin = document.frmmail.login.value;
  umess = document.frmmail.messagetext.value;
  uto = document.frmmail.user.value;
  url1 = document.frmmail.url.value;
  if((ulogin=="")||(umess=="")){
    alert("Оба поля обязательны к заполнению");
	return;
  }
  st = ulogin;
  reg = /[\w]+@[\w\.]+/i;
  st1 = reg.test(st);
  if(!st1){
    alert("Неправильно введёно поле электронной почты!");
	return;
  }
  $.get("/ajax_check.php", { command: "mail", login: ulogin, messagetext: umess, user: uto, url: url1 },
    function(res){
      if(res=="mail1")
	    { alert("Сообщение отослано!"); }
	  else
	    { alert("Возникла ошибка при отсылке письма! "+res); }
	  mail_close();
    });
}

// New login fuction
function do_login2(){
  //console.log('login2 try...');
  ulogin = document.frmlogin.login.value;
  upass = hex_md5(document.frmlogin.password.value);
  createCookie('login', ulogin, 1);
  createCookie('password', upass, 1);
  $.get("/ajax_check.php", { command: "login2", login: ulogin, password: upass },
      function(res){
        login_close();
        resp = eval('('+res+')');
        if(resp.login=='1') {
          $('#toplogin').html("<img src='/img/main-menu/profile-icon-bw.gif' border='0'> Мой профиль");
          $('#toplogin').unbind('click', void(0));
          $('#toplogin').attr('onclick' , 'void(0)');
          $('#toplogin').attr('href', '/profile/');
          $('#submenu_myobj').html('<a class="yuimenuitemlabel" href="/myobj/">Мои объявления</a>');
          $('#submenu_mydoc').html('<a class="yuimenuitemlabel" href="/mydocs/">Мои автодокументы</a>');
          $('#submenu_myobj').show();
          $('#submenu_notepad').show();
          $('#submenu_mail').show();
          $('#submenu_exit').show();
          $('#submenu_notepad').html('<a class="yuimenuitemlabel" href="/notepad/">Блокнот</a>');
          $('#submenu_mail').html('<a class="yuimenuitemlabel" href="/mail/">Сообщения</a>');
          $('#submenu_exit').html('<a class="yuimenuitemlabel" onclick="do_logout2()" href="javascript:void(0)">Выход</a>');
          if(resp.comptype=='1'){
            $("div#bottomlogin").html('<a href="/profile/" class="headprofilelink">'+readCookie("login")+'</a><br><a  href="/myobj/">Мои объявления</a><br><a  href="/mail/">Сообщения</a><br><a  href="/stat/">Статистика</a>');
          } else {
            $("div#bottomlogin").html('<a href="/profile/" class="headprofilelink">'+readCookie("login")+'</a><br><a  href="/myobj/">Мои объявления</a><br><a  href="/mydocs/">Мои автодокументы</a><br><a  href="/notepad/">Блокнот</a><br><a  href="/mail/">Сообщения</a>');
          }}
        if((readCookie('urlafterlogin')==null)||(readCookie('urlafterlogin')=='')){
          if((resp.reslogin=='1')||(resp.reslogin=='2')) {
            eraseCookie('login');
            eraseCookie('password');
            return;
          }
          if(custom_after_login!=null) {
            custom_after_login();
            custom_after_login = null;
            return;
          }
          if(resp.reslogin=='10') {
            document.location='/profile/';
          }
        }  else {
          s = readCookie('urlafterlogin');
          eraseCookie('urlafterlogin');
          document.location=s;
        }
      });
}

function do_login(){
  do_login2();
}

function remember(){
  $.get("/ajax_check.php", { command: "passreq", login: document.frmlogin.login.value },
    function(res){
      if(res=='mail1') {
	    alert("На Ваш email выслано письмо с паролем");
	  } else {
	    alert("При попытке отправить email произошла ошибка. Попробуйте позже или свяжитесь с администрацией.");
	  }
    });
}

function reactivation(){
$.get("/ajax_check.php", { command: "reactivation", login: document.frmregister.rlogin.value },
    function(res){
      if(res=='mail1') {
	    alert("На Ваш email выслано письмо с активацией");
	  } else {
	    alert("При попытке отправить email произошла ошибка. Попробуйте позже или свяжитесь с администрацией.");
	  }
    });
}

function load_region(){
  $.get("/ajax_town.php", { command: "towns" },
    function(res){
      $("span#reg_list").html(res);
    });
}

function load_model(mod, cpan, cls, evnt){
  $.get("/ajax_check.php", { command: "model",  marka: mod, clas: cls, ev: 'ChangeModel(document.long_search.model.value, 1)'},
    function(res){
      $("span#mod_list_l").html(res);
      if(document.long_search) { document.long_search.marka.value = mod; }
    });
  $.get("/ajax_check.php", { command: "model",  marka: mod, clas: cls, ev: 'void(0)'},
    function(res){
      $("span#mod_list").html(res);
      if(document.long_search) { document.long_search.marka.value = mod; }
    });
  $.get("/ajax_check.php", { command: "model",  marka: mod, clas: cls, ev: 'void(0)'},
    function(res){
      $("span#mod_obj").html(res);
      if(document.long_search) { document.long_search.marka.value = mod; }
    });
}

function load_model_salon(mod, cpan, cls, evnt){
  $.get("/ajax_check.php", { command: "model",  marka: mod, clas: cls, ev: 'ChangeModel(document.long_search.model.value, 1)'},
    function(res){
      $("span#mod_list_l").html(res);
      if(document.long_search) { document.long_search.marka.value = mod; }
    });
  $.get("/ajax_check.php", { command: "model",  marka: mod, clas: cls, ev: 'void(0)'},
    function(res){
      $("span#mod_list").html(res);
      if(document.long_search) { document.long_search.marka.value = mod; }
    });
  $.get("/ajax_check.php", { command: "model",  marka: mod, clas: cls, ev: 'void(0)'},
    function(res){
      $("span#mod_obj").html(res);
      if(document.long_search) { document.long_search.marka.value = mod; }
    });
}

function load_model_salon_obj(mod, cpan, cls){
  $.get("/ajax_check.php", { command: "modelnew",  marka: mod, clas: cls, ev: "load_submodel_salon(document.obj_edit.model.value, 'mod_obj', 'obj_edit')"},
    function(res){
      $("span#mod_obj").html(res);
      document.obj_edit.model.value = -1;
      DelPic(0);
    });
}

function load_submodel_salon(mod, cpan, cls){
  $.get("/ajax_check.php", { command: "submodel",  model: mod, clas: cls},
    function(res){
      $("span#mod_list_sub").html(res);
      DelPic(0);
      if(imgcnt==0){
        if($("span#filename").text()!='-') $('<li id="lin0"></li>').appendTo('#example1 .files').html("<input name='file0' type='hidden' value='"+$("span#filename").text()+"'><img width='150' src='/upload/"+$("span#filename").text()+"'> <a href='javascript:void(0)' onclick='javascript:DelPic(0)'>Удалить</a>");
      }
    });
}

function load_model_newold(mod, cpan, cls, evnt, no){
  //$.get("/ajax_check.php", { command: "model",  marka: mod, clas: cls},
  $.get("/ajax_check.php", { command: "model", newold: no, marka: mod, clas: cls, ev: 'ChangeModel(document.long_search.model.value, 1)'},
    function(res){
      $("span#"+cpan).html(res);
      if(document.long_search) { document.long_search.marka.value = mod; }
    });
}

function load_submodel_descr(mod, divname){
   $.get("/ajax_check.php", { command: "submodeldescr", submodel: mod},
    function(res){
      $("div#"+divname).html(res);
    }); 
}

function load_model_id(mod, cpan, cls, id, val){
  $.get("/ajax_check.php", { command: "model",  marka: mod, clas: cls},
    function(res){
      $("span#"+cpan).html(res);
      if(id==2){ document.long_search.model.value = val; }
    });
}

function ChangeModel(mod, v){
  //if(v==1) { load_model_id(document.long_search.marka.value, 'mod_list', 'find_block_optw', mod); }
  if(v==2) { document.long_search.model.value = mod; }
}

function load_smtown(id, cpan, cls){
  $.get("/ajax_town.php", { command: "smtown",  region: id, clas: cls},
    function(res){
      $("span#"+cpan).html(res);
    });
}
function load_smtown_w(id, cpan, cls, val){
  $.get("/ajax_town.php", { command: "smtown",  region: id, clas: cls},
    function(res){
      $("span#"+cpan).html(res);
      document.long_search.smtown.value = val;
    });
}

function email_change(event){
  $.get("/ajax_check.php", { command: "emailcheck", email: $("#rlogin").val() },
    function(res){
      if(res=='email1'){
        $("span#correct").html("<span class='span_ok'>Ошибок нет</span>");
      };
	  if(res=='email0') {
        $("span#correct").html("<span class='span_err'>Неверно введённый адрес</span>");
      };
	if(res=='emailex') {
        $("span#correct").html("<span class='span_err'>Этот email уже введён</span>");
	  };
    });
}

function password_change(event){
    if(
       ($("#pass1").val() == $("#pass2").val()) && 
       ($("#pass2").val().length >= 5)
      ){
      $("span#correct2").html("<span class='span_ok'>Ошибок нет</span>");
    } else {
      if($("#pass1").val().length < 5){
        $("span#correct2").html("<span class='span_err'>Пароль слишком короткий</span>");
      } else {
        $("span#correct2").html("<span class='span_err'>1-й и 2-й варианты пароля не совпадают</span>");
      }
    }
}
  
function addHandler(object, event, handler, useCapture) {
    if (object.addEventListener) {
        object.addEventListener(event, handler, useCapture ? useCapture : false);
    } else if (object.attachEvent) {
        object.attachEvent('on' + event, handler);
    };
}
function removeHandler(object, event, handler) {
  if (typeof object.removeEventListener != 'undefined')
    object.removeEventListener(event, handler, false);
  else if (typeof object.detachEvent != 'undefined')
    object.detachEvent('on' + event, handler);	
}
function wheel(event) {
    var delta; // Направление скролла
    // -1 - скролл вниз
    // 1  - скролл вверх
    event = event || window.event;
    // Opera и IE работают со свойством wheelDelta
    if (event.wheelDelta) {
        delta = event.wheelDelta / 120;
        // В Опере значение wheelDelta такое же, но с противоположным знаком
        if (window.opera) delta = -delta;
    // В реализации Gecko получим свойство detail
    } else if (event.detail) {
        delta = -event.detail / 3;
    }
    // Запрещаем обработку события браузером по умолчанию
    if (event.preventDefault)  event.preventDefault();
    event.returnValue = false;
	//document.getElementById('block_login').style.top = document.getElementById('block_login').style.top+delta;
    return delta;
}
function clk(event) {
  login_close();
  reg_close();
  mail_close();
  return 1;
}
function block_main_scroll() {
  var arrayPageSize = getPageSize();
  var arrayPageScroll = getPageScroll();
  addHandler(window, 'DOMMouseScroll', wheel);
  addHandler(window, 'mousewheel', wheel);
  addHandler(document, 'mousewheel', wheel);
  addHandler(document.getElementById("helper"), 'mousedown', clk);
  $("body").css("overflow", "hidden");
  $("#helper").css("background-color", "#646464");
  $("#helper").css("opacity", "0.5");
  $("#helper").css("z-index", "2000");
  $("#helper").height(arrayPageSize[1]);
}
function unblock_main_scroll() {
  removeHandler(window, 'DOMMouseScroll', wheel);
  removeHandler(window, 'mousewheel', wheel);
  removeHandler(document, 'mousewheel', wheel);
  removeHandler(document.getElementById("helper"), 'mousedown', clk);
  $("body").css("overflow", "auto");
  $("#helper").css("background-color", "");
  $("#helper").css("opacity", "");
  $("#helper").css("z-index", "-10");
}

function load(){
  login_div = $('<div class="block_login" id="block_login"><a class="modalCloseImg" id="modalCloseImg" onclick="login_close_c();">&nbsp;</a><form name="frmlogin" style="margin-top: 15px; margin-bottom: 0; padding: 0;" action="javascript:do_login2();"><table border="0"><tr><td><span class="block_head">Войдите или <a href="javascript:void()" onclick="reg_window();">зарегистрируйтесь</a></span></td></tr><tr><td>&nbsp;</td></tr><tr><td>&nbsp;</td></tr><tr><td>Ваш адрес электронной почты</td></tr><tr><td><input name="login" class="login" id="login" style="width: 100%;"></td></tr><tr><td>&nbsp;</td></tr><tr><td>Ваш пароль:</td></tr><tr><td><input name="password" id="password" class="password"  type="password" style="width: 100%;"></td></tr><tr><td style="text-align: right;"><a class="sm_a" href="#" onclick="remember();">Напомнить пароль</a></td></tr><tr><td>&nbsp;</td></tr><tr><td><img src="/img/enter.gif" onclick="do_login();" alt="Войти"><input type="submit" style="display: none;"></td></tr></table></form></div>');
  login_div.appendTo("#bl");
  login_div.hide();
  reg_div = $('<div class="block_reg" id="block_reg"><a class="modalCloseImg" id="modalCloseImg" onclick="reg_close();">&nbsp;</a><form name="frmregister" style="margin-top: 15px; margin-bottom: 0; padding: 0;" action="javascript:do_register();"><table border="0"><tr><td><span class="block_head">Зарегистрируйтесь или <a href="javascript:void()" onclick="login_window();">войдите</a></span></td></tr><tr><td>&nbsp;</td></tr><tr><td>Пожалуйста, заполните все поля</td></tr><tr><td>&nbsp;</td></tr><tr><td>Ваш адрес электронной почты</td></tr><tr><td><input name="rlogin" id="rlogin" class="rlogin" style="width: 100%;"></td></tr><tr><td><span id="correct" style="correct"></span></td></tr><tr><td>&nbsp;</td></tr><tr><td>Ваш пароль:</td></tr><tr><td><input name="password" id="pass1" type="password" style="width: 100%;"></td></tr><tr><td><span style="font-size: 11px;">Не менее 5 символов</span></td></tr><tr><td>&nbsp;</td></tr><tr><td>Повторите пароль</td></tr><tr><td><input name="password2" id="pass2" type="password" style="width: 100%;"></td></tr><tr><td><span id="correct2"></span></td></tr><tr><td>&nbsp;</td></tr><tr><td>Выберите Ваш регион:</td></tr><tr><td><span id="reg_list" class="reg_list">&nbsp;</span></td></tr><tr><td style="text-align: right;"><a class="sm_a" href="#" onclick="reactivation();">Повторить письмо активации</a></td></tr><tr><td>&nbsp;</td></tr><tr><td><img src="/img/reg.gif" onclick="do_register();" alt="Зарегистрироваться"><input type="submit" style="display: none;"></td></tr></table></form></div>');
  reg_div.appendTo("#bl");
  reg_div.hide();
  lg = readCookie('login');
  ds = '';
  if(lg!=null) ds = 'disabled';
  if(lg==null) lg = '';
  mail_div = $('<div class="block_mail" id="block_mail"><form name="frmmail" style="margin: 0pt; padding: 0pt;"><table border="0"><tr><td><span class="block_head">Письмо автору ↓</span></td></tr><tr><td>&nbsp;</td></tr><tr><td>&nbsp;</td></tr><tr><td>Ваш адрес электронной почты</td></tr><tr><td><input name="login" id="login" style="width: 100%;" value="'+lg+'" '+ds+'></td></tr><tr><td>&nbsp;</td></tr><tr><td>&nbsp;</td></tr><tr><td>Текст сообщения:</td></tr><tr><td><textarea name="messagetext" id="messagetext" type="password" style="width: 100%;" rows="5"></textarea></td></tr><tr><td><input type="hidden" name="user"><input type="hidden" name="url"></td></tr><tr><td>&nbsp;</td></tr><tr><td><img src="/img/send.gif" onclick="do_mail();" alt="Отправить"></td></tr></table></form><a class="modalCloseImg" id="modalCloseImg" onclick="mail_close();">&nbsp;</a></div>');
  mail_div.appendTo("#bl");
  mail_div.hide();
  
  main_div = $("div#main");
  showed=0;
  reg_show=0;
  load_region();
  $("#reg_submit").click(do_register);
  $("#log_submit").click(do_login);
  $("#mail_submit").click(do_mail);
  $("#rlogin").keyup(function(event) { email_change(event); });
  $("#pass1").keyup(function(event) { password_change(event); });
  $("#pass2").keyup(function(event) { password_change(event); });
  $("#regtowns").keyup(function(event){
    if(event.keyCode==13) do_register();
  }); 
}

function login_window(){
    if(reg_show==1) reg_close();
    if(showed==0){
      var arrayPageSize = getPageSize();
      var arrayPageScroll = getPageScroll();
      showed=1;
      $("#block_login").show();

      document.getElementById('block_login').style.left = (getClientWidth() -$("#block_login").width() -30)/2+"px";
      document.getElementById('block_login').style.top =  (arrayPageSize[3]-$("#block_login").height()-30)/2+"px";
      //document.getElementById('block_login').style.left = (getClientWidth() -$("#block_login").width() -30)/2+"px";
      //document.getElementById('block_login').style.top =  (getClientHeight()-$("#block_login").height()-30)/2+"px";
      
      main_div.click(function (e) { e.preventDefault(); });
      login_div.submit(function (e) { do_login(); return false; });
      block_main_scroll();
    }
}

function reg_window(){
    if(showed==1) login_close();
    if(reg_show==0){
      reg_show=1;
      document.getElementById('block_reg').style.left = (getClientWidth()-reg_div.width()-30)/2+"px";
      document.getElementById('block_reg').style.top = (getClientHeight()-reg_div.height()-30)/2+"px";
      reg_div.show("fast");
      /*main_div.fadeTo("fast", 0.1);*/
      $(".top_banner").hide();
      $(".middle_banner").hide();
      $(".right_banner").hide();
      main_div.click(function (e) { e.preventDefault(); });
      reg_div.submit(function (e) { do_register(); return false; });
      block_main_scroll();
    }
}

function mail_window(email){
  document.getElementById('block_mail').style.left = (getClientWidth()-reg_div.width()-30)/2+"px";
  document.getElementById('block_mail').style.top = (getClientHeight()-reg_div.height()-30)/2+"px";
  document.frmmail.user.value = email;
  mail_div.show("fast");
  /*main_div.fadeTo("fast", 0.1);*/
  $(".top_banner").hide();
  $(".middle_banner").hide();
  $(".right_banner").hide();
  scroll(0,0);
  main_div.click(function (e) { e.preventDefault(); });
  block_main_scroll();
}

function ad_window(){
  document.getElementById('block_reg').style.left = (getClientWidth()-reg_div.width()-30)/2+"px";
  document.getElementById('block_reg').style.top = (getClientHeight()-reg_div.height()-30)/2+"px";
  reg_div.show("fast");
  main_div.fadeTo("fast", 0.1);
}

function reg_close(){
  if(reg_show==0) return;
  if(reg_show==1){
	document.frmregister.rlogin.value = '';
	document.frmregister.password.value = '';
	document.frmregister.password2.value = '';
	document.frmregister.regions.value = -1;
    reg_show=0;
    reg_div.hide();
    main_div.unbind('click');
    $(".top_banner").show();
    $(".middle_banner").show();
    $(".right_banner").show();
    main_div.fadeTo("fast", 1);
    unblock_main_scroll();
  }
}

function login_close(){
  if(showed==0) return;
  if(showed==1){
	document.frmlogin.login.value = '';
	document.frmlogin.password.value = '';
    showed=0;
    login_div.hide();
    main_div.unbind('click');
    $(".top_banner").show();
    $(".middle_banner").show();
    $(".right_banner").show();
    /*main_div.fadeTo("fast", 1);*/
    unblock_main_scroll();
  }
}

function login_close_c(){
  eraseCookie('urlafterlogin');
  login_close();
}

function mail_close(){
  mail_div.hide();
  main_div.unbind('click');
  $(".top_banner").show();
  $(".middle_banner").show();
  $(".right_banner").show();
  main_div.fadeTo("fast", 1);
  unblock_main_scroll();
}

function last_add_page_image_width(){
  return 3*getClientWidth()/500;
}

function do_adv_search(){
  if(document.getElementById('find_block').style.display=='none'){
    document.getElementById('find_block').style.display='block';
	document.getElementById('find_adv_block').style.display='none';
  } else {
    document.getElementById('find_block').style.display='none';
	document.getElementById('find_adv_block').style.display='block';  
  }
}

function mwnd(number, x, y){
  if($('ad_'+number).css('display')!='block') {
    document.getElementById('ad_'+number).style.display='block';
    if(inbig==1){
      p = $('#image_'+number).offset();
      h=$('#image_'+number).height()/2;
      w=$('#image_'+number).width()/2;
      document.getElementById('ad_'+number).style.top = p.top+h;
      document.getElementById('ad_'+number).style.left = p.left+w;
    }
  }
}

function wind_ad(number, x, y){
  s = 'mwnd(' + number + ',' + x + ',' + y+ ');';
  setTimeout(s, 600);
}

function wind_unad(number){
  if((inbig==0)&&(insmall==0)){
    setTimeout("document.getElementById('ad_'+"+number+").style.display='none';", 600);
  }
}

function LoginAndGo(url){
  createCookie('urlafterlogin', url, 1);
  login_window();
}

function SaveToNotepad(obj){
  $.get("/ajax_check.php", {
    command: "addnote",
    login: readCookie('login'),
    password: readCookie('password'),
    id: obj},
    function(res){
      if(res!="") { alert(res); return 1; }
    });
}

function LoginAndSaveToNotepad(idn){
  if((isemptyCookie('login')==1)||(isemptyCookie('password')==1)){
    custom_after_login = function(){
      SaveToNotepad(idn);
    };
    createCookie('urlafterlogin', '', 1);
    login_window();
  } else {
    SaveToNotepad(idn);
  }
}

function ChShortRegion(){
  load_smtown(document.long_search.town.value, 'lnsmtown', 'find_block_opt');
}
function ChLongRegion(){
  load_smtown(document.long_search.town.value, 'lnsmtown', 'find_block_opt');
}
function ChLongRegionEx(isnew){
  load_smtown(document.long_search.town.value, 'lnsmtown', 'find_block_opt');
}
/*=== Samrt columns ===*/
function smartColumns() { //Create a function that calculates the smart columns

        //Reset column size to a 100% once view port has been adjusted
	$("ul.column").css({ 'width' : "100%"});

	var colWrap = $("ul.column").width(); //Get the width of row
	var colNum = Math.floor(colWrap / 200); //Find how many columns of 200px can fit per row / then round it down to a whole number
	var colFixed = Math.floor(colWrap / colNum); //Get the width of the row and divide it by the number of columns it can fit / then round it down to a whole number. This value will be the exact width of the re-adjusted column

	$("ul.column").css({ 'width' : colWrap}); //Set exact width of row in pixels instead of using % - Prevents cross-browser bugs that appear in certain view port resolutions.
	$("ul.column li").css({ 'width' : colFixed}); //Set exact width of the re-adjusted column	

}

//smartColumns();//Execute the function when page loads

function IncCrush(id){
  $.get('/ajax_check.php?par='+id+'&command=incviewmedia&type=2');
}
function IncPhoto(id){
  $.get('/ajax_check.php?par='+id+'&command=incviewmedia&type=3');
}
function IncTestdrive(id){
  $.get('/ajax_check.php?par='+id+'&command=incviewmedia&type=1');
}
function ShowCrush(no, id, marka, model){
  IncCrush(id);
  $("#crushtest"+no).modal({overlayClose:true});
}
function ShowPhoto(no, id, marka, model){
  IncPhoto(id);
  //$("#photo"+no).modal({overlayClose:true});
}
function ShowTestdrive(no, id, marka, model){
  IncTestdrive(id);
  $("#testdrive"+no).modal({overlayClose:true});
}

function tweet(text){
  window.my_callback = function(response) {
    if(response.error_message) window.open('http://twitter.com/home/?status='+encodeURIComponent(text),this.target)
    else window.open('http://twitter.com/home/?status='+encodeURIComponent(text),this.target)
  };
  var s = document.createElement("script");
  s.src = "http://ggl-shortener.appspot.com/?url=" + encodeURIComponent('http://automobil.ua/') + "&jsonp=my_callback";
  document.body.appendChild(s);

  return false;
}

function ShowSms(){
  $("#sms").modal({overlayClose:true});
  $("#simplemodal-container").css('background-image', 'none');
  $("#simplemodal-container").css('background-color', 'white');
  $("#simplemodal-container").css('color', 'black');
  $("#simplemodal-container a").css('color', 'black');
  $("#simplemodal-container a").css('font-size', '10px');
  $("#simplemodal-container h2").css('display', 'block');
}

function getBrowserInfo() {
    var t,v = undefined;
    if (window.opera) t = 'Opera';
    else if (document.all) {
        t = 'IE';
        var nv = navigator.appVersion;
        var s = nv.indexOf('MSIE')+5;
        v = nv.substring(s,s+1);
    }
    else if (navigator.appName) t = 'Netscape';
    return {type:t,version:v};
}


function bookmark(a){
    var url = window.document.location;
    var title = window.document.title;
    var b = getBrowserInfo();
    if (b.type == 'IE' && 8 > b.version && b.version >= 4) window.external.AddFavorite(url,title);
    else if (b.type == 'Opera') {
        a.href = url;
        a.rel = "sidebar";
        a.title = url+','+title;
        return true;
    }
    else if (b.type == "Netscape") { window.sidebar.addPanel(title,url,""); }
    else alert("Нажмите CTRL-D, чтобы добавить страницу в закладки.");
    return false;
}
