if ('undefined' == typeof String.prototype.trim) {
  String.prototype.trim = function() {
    return this.replace(/^\s+/, '').replace(/\s+$/, '');
  }
}


$(function(){
	 $('input[type=radio].star2').rating({
                                        callback: function(value, link){
                                        var a=document.getElementById('articles_id').value;
                                        if(value)
                                        voice_articles(a,value);
                                        }
                                        });
	});

//Голосуем за статью инструктора
function voice_articles(id,value){
var req = new JsHttpRequest();
    req.onreadystatechange = function() {
        if (req.readyState == 4) {
                                  alert(req.responseJS.result);
                                 }
                                         }
    req.open(null, 'http://www.avtoas.ru/upload.php', true);
    req.send( { id: id, value: value ,ajax: "voice_articles" } );
}


//Форма вопроса к инструктору
function instructor_vopros(id){

$(document).ready(function(){
                           
                    jQuery.facebox("<form style=font-size:10px; enctype=multipart/form-data method=post name=f id=f>" +
                              "Имя<br><input type=text name=name size=25 maxlength=20><br>" +
                              "E-mail<br><input type=text name=email size=25 maxlength=20><br>" +
                              "Ваш вопрос<br><textarea onmousemove=tick(); onkeydown=tick(); name=info id=info cols=40 rows=5></textarea><br><br>Максимальное количество символов: 500<br><input value=500 size=3 id=msgCL name=msgCL disabled><br><br>"+
                              "<input type=submit id=vopros name=vopros value=Отправить onclick='instructor_vopros_do(this.form);return false;'>" +
                              "<input type=hidden name=id value=" + id + "></form>");

                              });
                              return false;
}
function instructor_vopros_do(value){
var req = new JsHttpRequest();
    req.onreadystatechange = function() {
        if (req.readyState == 4) {
                                    if(req.responseJS.err == 1) {
                                    alert(req.responseJS.err_text);
                                    }else{
                                    alert(req.responseJS.result);
                                    jQuery.facebox.close();
                                    }
        }
    }

    req.open(null, 'http://www.avtoas.ru/upload.php', true);

    req.send( { q: value ,ajax: "instructor_vopros_do" } );
    
}
function changeImg(b,login,id,nomer){

var a = b.split(" ");
if(nomer == a.length) { nomer=0; }

document.getElementById(id).src ='/upload/instructor/' + login + '/' +  a[nomer] + '_mini.jpg';
nomer++;
setTimeout('changeImg("'+ b +'","'+ login +'","'+ id +'","'+ nomer +'")',2000);
return false;
}

$(document).ready(function(){

	$(".btn-slide").click(function(){
		$("#panel").slideToggle("slow");
	});
  	$("#corner").corner();

});



  function okno_vopros(val,val2,val3,papka_instructor,foto_type,ext){

         $(document).ready(function(){
           $("#confirm").dialog({
                     width:500,
                     height:200,
                     position: "center",
                     resizable: false,
                     buttons:{'Да': function(){ close_okno("#confirm"); resize_da(val,val2,val3,papka_instructor,foto_type,ext); },
                              'Нет': function(){ close_okno("#confirm"); alert('Фотография успешно загружена');
                              }},
                     close: function(){ close_okno("#confirm");
                     alert('Фотография успешно загружена');
                                      }
                     });
$("#foto_type").empty()
$("#confirm").empty().append('<div style="display:block;height:50px;">Вы хотите вручную создать миниатюру загружаемого изображения?</div><br><br> ');
         });
         glass();
         }
//--------------------------------------------------------------------------------------------------------
function resize_da(val,val2,val3,papka_instructor,foto_type,ext){

$(document).ready(function(){

                              $("#dialog").dialog({
                                                   width: 600,
                                                   height:400,
                                                   position: "center",
                                                   resizable: false,
                                                   close: function() {  close_okno("#dialog");
                                                                        alert('Фотография успешно загружена'); }
                                                   });

            $("#crop")
            .empty()
            .append('<img id="cropbox" src="/upload/instructor/'+ papka_instructor +'/' + val +'.jpg"/> ');

            $("#prew")
            .empty()
            .append('<img id="preview" src="/upload/instructor/'+ papka_instructor +'/' + val +'.jpg"/> ');

            $("#obrabotka").empty();
            var txt='<form name=y id=y method=post onsubmit="y.submit.disabled=true; return false;"><input type=submit name=submit value=Обрезать onclick=resize_hand("' + val + '"); return false;><input id=razmeri type=hidden name=razmeri><input id=ramka_w type=hidden name=ramka_w><input id=ramka_h type=hidden name=ramka_h><input id=foto_type type=hidden name=foto_type><input id=ext type=hidden name=ext></form>';
            document.getElementById('obrabotka').innerHTML= txt;

//<form name=y id=y method=post onsubmit="y.submit.disabled=true; return false;"><input type=submit name=submit value=Обрезать onclick="resize_hand(); return false;"><input id=razmeri type=hidden name=razmeri></form>
     document.getElementById('dialog').style.width="600";
     document.getElementById('dialog').width="600";
     document.getElementById('cropbox').width=val2;
     document.getElementById('cropbox').height=val3;
     document.getElementById('cropbox').style.width=val2;
     document.getElementById('cropbox').style.height=val3;
     //Если загружаем фото автомобиля, то размеры области просмотра 150*100
     if(foto_type != 0){
     var ramka_w=250;
     var ramka_h=150;
     var ratio=1.6;
     }else{
     var ramka_w=150;
     var ramka_h=150;
     var ratio=1;
     }
     document.getElementById('prew').width = ramka_w;
     document.getElementById('prew').height = ramka_h;
     document.getElementById('prew').style.width= ramka_w;
     document.getElementById('prew').style.height = ramka_h;
     $('input[name=ramka_w]').val(ramka_w);
     $('input[name=ramka_h]').val(ramka_h);
     $('input[name=foto_type]').val(foto_type);
     $('input[name=ext]').val(ext);

                              		jQuery('#cropbox').Jcrop({
                                                       boxWidth: 300,
                                                       boxHeight: 300,
					                                             aspectRatio: ratio,
                                                       onSelect: showPreview,
                                                       onSelect: updateCoords,
					                                             onChange: showPreview
			                                               	});

                              glass();
                              });
//});
}
function doski_add(cat){

$(document).ready(function(){

                              $("#doski_add").dialog({
                                                   width: 700,
                                                   height:400,
                                                   position: "center",
                                                   resizable: false,
                                                   close: function() {  close_okno("#doski_add");
                                                                         }
                                                   });
$("#doski_add").empty().append('<form enctype=multipart/form-data method=post id=doski name=doski onsubmit="return false;"><table style=font-size:12px;border:0 solid black;><tr valign=TOP><td>Заголовок объявления<br><input type=text name=head size=40>' +
                             '<br>Имя<br><input type=text name=name size=40>' +
                             '<br>Город<br><input type=text name=city size=40>' +
                             '<br>Телефон<br><input type=text name=tel size=40>' +
                             '<br>E-mail<br><input type=text name=email size=40>' +
                             '<br><br>Не показывать E-mail в объявлении <input type="checkbox" name="email_status" value="1">' +
                             '<br><br>Придумайте пароль для редактирования объявления.' +
                             '<br><br>Пароль <input type=password name=pass maxlength=16 size=16> </td>' +
                             '<td>Текст объявления <small>(Max количество символов : 500)</small><br> <textarea name=message rows=10 cols=35></textarea></td></tr>' +
                             '<tr><td style=text-align:center; colspan=2><input type=SUBMIT name=sumbit   value=Добавить объявление onclick=doski_add_do(this.form);></td></tr>' +
                             '<tr><td style=text-align:center; colspan=2><div id=result></div></td></tr></table>' +
                             '<input type=HIDDEN name=cat value='+ cat +'></form>');

                              glass();
                              });
}

function doski_add_do(value){
//a = document.getElementById('doski_add');
document.getElementById('result').innerHTML ='Ждите.... Идет отправка сообщения <br><img src=http://www.avtoas.ru/style/loader_2.gif>';
    var req = new JsHttpRequest();
    req.onreadystatechange = function() {
        if (req.readyState == 4) {
        document.getElementById('result').innerHTML='';
        if(req.responseJS.err == 1) {
                                    alert(req.responseJS.err_text);
                                    }else{
                                    alert('Ваше объявление успешно добавлено!');

                                    close_okno("#doski_add");
                                    }

        }
    }

    req.open(null, 'http://www.avtoas.ru/upload.php', true);

    req.send( { q: value ,ajax: "doski_add" } );

}
function doski_edit(val){
  var req = new JsHttpRequest();
    req.onreadystatechange = function() {
        if (req.readyState == 4) {
        $(document).ready(function(){

                              $("#doski_add").dialog({
                                                   width: 700,
                                                   height:400,
                                                   position: "center",
                                                   resizable: false,
                                                   close: function() {  close_okno("#doski_add");
                                                                         }
                                                   });
                              $("#doski_add").empty().append(req.responseJS.otvet);
                              glass();
                              });
        }
    }

    req.open(null, 'http://www.avtoas.ru/upload.php', true);

    req.send( { q: val ,ajax: "doski_edit" } );
}

function doski_edit_do(value){

document.getElementById('result').innerHTML ='Ждите.... Вносятся изменения... <br><img src=http://www.avtoas.ru/style/loader_2.gif>';
    var req = new JsHttpRequest();
    req.onreadystatechange = function() {
        if (req.readyState == 4) {
        document.getElementById('result').innerHTML='';
        if(req.responseJS.err == 1) {
                                    alert(req.responseJS.err_text);
                                    }else{
                                    alert('Ваше объявление успешно отредактированно!');

                                    close_okno("#doski_add");
                                    }

        }
    }

    req.open(null, 'http://www.avtoas.ru/upload.php', true);

    req.send( { q: value ,ajax: "doski_add", work: "edit" } );

}
			function updateCoords(c)
      {
        $('input[name=razmeri]').val(c.x +','+ c.y +',' + c.w + ',' + c.h);
        var koordinata= c.x +','+ c.y +',' + c.w + ',' + c.h;
        //alert(koordinata);
				$('#x').val(c.x);
				$('#y').val(c.y);
				$('#w').val(c.w);
				$('#h').val(c.h);
			};

			function checkCoords()
			{
				if (parseInt($('#w').val())) return true;
				alert('Пожалуйста, выделите обрезаемую часть изображения!.');
				return false;
   }

function showPreview(coords)
			{
 var wi,ha;
 var width=$('input[name=ramka_w]').val();
 var height=$('input[name=ramka_h]').val();

				if (parseInt(coords.w) > 0)
				{
					var rx = width / coords.w;
					var ry = height / coords.h;

     wi=document.getElementById('cropbox').width;
     ha=document.getElementById('cropbox').height;

					$('#preview').css({
						width: Math.round(rx * wi) + 'px',
						height: Math.round(ry * ha) + 'px',
						marginLeft: '-' + Math.round(rx * coords.x) + 'px',
						marginTop: '-' + Math.round(ry * coords.y) + 'px'
					});
				}
			}



function close_okno(val){
         //alert('Закрываем и обрезаем!');
         $(val).dialog('destroy');
         glass_off();

         }
function resize_hand(foto_name){
    foto_type=$('input[name=foto_type]').val();
    ext=$('input[name=ext]').val();
    var coords=document.getElementById('razmeri').value;
    var res = new JsHttpRequest();

    res.onreadystatechange = function() {
        if (res.readyState == 4) {
        //alert(res.responseJS.ramka_w);
        close_okno("#dialog");
        alert('Фотография успешно загружена');
        }
    }
    res.open(null, 'http://www.avtoas.ru/upload.php', true);
    res.send( { coords: coords , foto_name: foto_name , foto_type: foto_type, ext: ext, ajax: "resize" } );
         }



function location_select(pervii,vtoroy){
document.info.first.value=pervii;
doload(pervii, 'http://www.avtoas.ru/type.php', 'second_div');
doload(vtoroy, 'http://www.avtoas.ru/type.php', 'third_div');
}
function otziv_add(value){

  var req = new JsHttpRequest();
    req.onreadystatechange = function() {
        if (req.readyState == 4) {
        if(req.responseJS.err == 1) {
                                    alert(req.responseJS.err_text);
                                    }else{
                                    alert('Ваш отзыв успешно добавлен!');
                                    $("#panel").slideToggle("slow");
                                    document.getElementById('result_otziv').innerHTML=req.responseJS.result;
                                    }
                                    document.getElementById('otziv').value='Добавить отзыв';
			                              document.getElementById('otziv').disabled=false;

        }
    }

    req.open(null, 'http://www.avtoas.ru/upload.php', true);

    req.send( { val: value, ajax: "ajax_add_otziv" } );
}

function poisk_site(value) {
    var req = new JsHttpRequest();
	document.getElementById('result').innerHTML ='Ждите.... Идет поиск <br><img src=/style/loader_2.gif>';
    req.onreadystatechange = function() {
        if (req.readyState == 4) {
                                     document.getElementById('result').innerHTML =req.responseJS.result;
        }
    }
    req.open(null, 'http://www.avtoas.ru/upload.php', true);
    req.send( { q: value , ajax: "poisk_site" } );
}



function upload(value) {
    // Create new JsHttpRequest object.
    var req = new JsHttpRequest();
    // Code automatically called on load finishing.
	document.getElementById('result').innerHTML ='Ждите.... Идет загрузка <br><img src=/style/loader_2.gif>';
	document.getElementById('debug').innerHTML = "";
    req.onreadystatechange = function() {
        if (req.readyState == 4) {
            // Write result to page element (_RESULT becomes responseJS).
            if(req.responseJS.q == 1){

                                     okno_vopros(req.responseJS.q_name,req.responseJS.q_size_w,req.responseJS.q_size_h,req.responseJS.q_papka_instructor,req.responseJS.q_foto_type,req.responseJS.q_ext);
                                     document.getElementById('result').innerHTML ='';
                                     //alert('Фотография успешно загружена');
                                     }else{
                                     //document.getElementById('debug').innerHTML = req.responseText;

                                     alert(req.responseText.trim());
                                     document.getElementById('result').innerHTML= "";
                                     }



			      document.getElementById('add_foto').value='Загрузить фото';
			      document.getElementById('add_foto').disabled=false;
        }
    }
    // Prepare request object (automatically choose GET or POST).
    req.open(null, 'http://www.avtoas.ru/upload.php', true);
    // Send data to backend.
    req.send( { q: value , ajax: "upload" } );
}

function poisk(peremenaya,value) {
    var req = new JsHttpRequest();
	document.getElementById('poisk_result').innerHTML ='Ждите.... Идет поиск <br><img src=http://www.avtoas.ru/style/loader_2.gif>';
    req.onreadystatechange = function() {
        if (req.readyState == 4) {
            document.getElementById('poisk_result').innerHTML= req.responseJS.poisk_otvet;
			      document.getElementById('poisk_start').value='Искать -> ';
			      document.getElementById('poisk_start').disabled=false;

        }
    }
    req.open(null, 'http://www.avtoas.ru/upload.php', true);
    req.send( {  peremenaya : peremenaya , value : value , ajax: "poisk" } );
}

function poisk_school(peremenaya,value,school_type){
                        //alert(peremenaya + " - " + value + " - " + school_type);
  var req = new JsHttpRequest();
	document.getElementById('poisk_result').innerHTML ='Ждите.... Идет поиск <br><img src=http://www.avtoas.ru/style/loader_2.gif>';
    req.onreadystatechange = function() {
        if (req.readyState == 4) {
            document.getElementById('poisk_result').innerHTML= req.responseJS.poisk_otvet;
        }
    }
    req.open(null, 'http://www.avtoas.ru/upload.php', true);
    req.send( {  peremenaya : peremenaya , value : value , school_type : school_type , ajax: "poisk_school" } );
                        }
function ajax_instructor_podrobno(value){
glass();

    var req = new JsHttpRequest();
 req.onreadystatechange = function() {
        if (req.readyState == 4) {
        //req.responseJS.otvet
         $("#ajax_instructor_podrobno").dialog({
                                                   width: 1100,
                                                   height:550,
                                                   position: "center",
                                                   resizable: false,
                                                   close: function() {  close_okno("#ajax_instructor_podrobno");
                                                                         }
                                                   });
         $("#ajax_instructor_podrobno")
            .empty()
            .append('<iframe src="http://www.avtoas.ru/instructor_podrobno/' + value +'" frameborder=0 width=1060 height=500></iframe>');
        }
    }
    req.open(null, 'http://www.avtoas.ru/upload.php', true);
    req.send( { q: value , ajax: "ajax_instructor_podrobno" } );
}

function gorod(val){
 if(val == 1){
 document.getElementById('show_city_moscow').style.display="block";
 document.getElementById('show_city').style.display="none";
 document.getElementById('third').value=0;
 }
 if(val == 2){
 document.getElementById('show_city_moscow').style.display="none";
 document.getElementById('show_city').style.display="block";
 }
}

function test_modal(){
         alert('Тест модал');
         $("#ajax_instructor_podrobno").modal();
         $("#ajax_instructor_podrobno")
            .empty()
            .append(req.responseJS.otvet);
}

function tick() {
calcCharLeft(document.forms[0]);
if (!supportsKeys) timerID = setTimeout('tick()',1000);
}

function calcCharLeft(sig) {
clipped = false;
maxLength = 500;
if (document.getElementById('info').value.length > maxLength) {
document.getElementById('info').value = document.getElementById('info').value.substring(0,maxLength);
charleft = 0;
clipped = true;
} else {
charleft = maxLength - document.getElementById('info').value.length;
}
document.getElementById('msgCL').value = charleft;
return clipped;
}


function skolko(maxLength){

         if (tinyMCE.get('info').getContent().length > maxLength) {
                                                    alert('Лимит исчерпан!');
                                                    document.getElementById('info').value='asasas';
                                                    var txt = tinyMCE.get('info').getContent().substring(0,maxLength-5);
                                                    tinyMCE.activeEditor.setContent(txt);

                                                    }
         document.getElementById('msgCL').value = maxLength - tinyMCE.get('info').getContent().length;
         timerID = setTimeout('skolko(maxLength)',1000);
}



function clear()
{
 for (i=0;i<document.warrant_form.elements.length;i++)
 {
 	document.warrant_form.elements[i].value='';
 }
document.warrant_form.warrant.value='Оформить';

}

function exampl()
{
	document.warrant_form.city.value='г.Москва';
	document.warrant_form.obl.value='';
	document.warrant_form.marka.value='ВАЗ 2101';
	document.warrant_form.znak.value='A456HK 77';
	document.warrant_form.cvet.value='белый';
	document.warrant_form.nomer_vin.value='JHHMEC83200S110836';
	document.warrant_form.year_vipusk.value='1980';
	document.warrant_form.nomer_dvig.value='1213937';
	document.warrant_form.nomer_shassi.value='1311144';
	document.warrant_form.nomer_kuzov.value='JHHMEC83200S110836';

	document.warrant_form.pasport_seriya.value='77 KP';
	document.warrant_form.pasport_nomer.value='886366';


	document.warrant_form.tehpasport_seriya.value='77 BC';
	document.warrant_form.tehpasport_nomer.value='123987';
	document.warrant_form.vidano_gai.value='7 отд. МРЭО ГИБДД ЮАО';
	document.warrant_form.day_vidacha.value='21';
	document.warrant_form.mouth_vidacha.value='5';
	document.warrant_form.year_vidacha.value='1993';

	document.warrant_form.fio_vladelec.value='Иванов Иван Иванович';
	document.warrant_form.pasport_seriya_vladelec.value='СБ-VII';
	document.warrant_form.pasport_nomer_vladelec.value='598766';
	document.warrant_form.pasrort_vidan_vladelec.value="о/м м/о 'Южное Медведково 8 апреля 1993 г.'";
	document.warrant_form.adress_vladelec.value='г.Москва ул.МИРА, дом 563, кв. 8568';

	document.warrant_form.fio_doverennii.value='Александрову Александру Александровичу';
	document.warrant_form.adress_doverennii.value='г.Москва, ул Профсоюзная, дом 555, кв. 9856';

	document.warrant_form.srok.value='3';
	document.warrant_form.s_type.value='3';

}

function s_change(z){
	if (z==0)
	{

		document.getElementById('show_exmpl').style.display = 'none';
        document.getElementById('clear_exmpl').style.display = 'block';

	}else if(z==1) {

		document.getElementById('show_exmpl').style.display = 'block';
        document.getElementById('clear_exmpl').style.display = 'none';

	}
}

function ajax_warrant(value) {

    var req = new JsHttpRequest();
    req.onreadystatechange = function() {
        if (req.readyState == 4) {
        //alert(req.responseJS.poisk_otvet);
         width = out.body.scrollWidth > out.body.clientWidth ? out.body.scrollWidth : out.body.clientWidth;
         height = out.body.scrollHeight > out.body.clientHeight ? out.body.scrollHeight : out.body.clientHeight;
         h=document.getElementById('body').clientHeight;
         win1=window.open('','new','width=600,height=800,toolbar=0,left=' + (width-600)/2 + ',top=' + h/2 + ' ');
         win1.document.open();
         win1.document.write(req.responseJS.poisk_otvet);
        }
    }

    req.open(null, 'http://www.avtoas.ru/upload.php', true);

    req.send( { q : value , ajax: "warrant" } );
}



