$(document).ready(function(){
                             $("#menu_ul ul:first").each(function(){
                                                                           $(this).addClass("sf-vertical");
                                                                           });



                             $("input[type='text'],input[type='password'], select, textarea").addClass("idle");
                             $("input[type='text'],input[type='password'], select, textarea").focus(function(){
                                                                                $(this).addClass("activeField").removeClass("idle");
                                                                                }).blur(function(){
                                                                                                   $(this).removeClass("activeField").addClass("idle");
                                                                                                  });


$("#inputArea input[type='submit']").click(function() {
  $("input").css("border","1px solid #85b1de").prev().css("color","black");


                                                                           if($("input[name=slovo\[\]]").val() == '') { $("input[name=slovo\[\]]").css("border","1px solid red").prev().css("color","red"); var error=true; }
                                                                           if($("input[name=email]").val() == '') { $("input[name=email]").css("border","1px solid red").prev().css("color","red"); var error=true; }


                                                                           if(error == true){
                                                                                    dialog("<center>Заполнены не все обязательные поля</center>");
                                                                                    return false;
                                                                                            }

                                                                                            send_progress(document.getElementById('progress'));


                                                                                            return false;
                                                      });



                             });



// Простой диалог с кнопкой "ЗАКРЫТЬ"
function dialog(value,w,h){
 $("#dialog").empty().append("<center>" + value + "</center>");
 $("#dialog").dialog({ buttons:{ "Закрыть": function() {$(this).dialog("close");}},
                                  width: w,
                                  modal:true,
                                  resizable: false,
                                  draggable: false,
                                  close: function(){ $("#dialog").dialog("destroy");}
                                  });
}

// Всплывающие подсказки
$(document).ready(function(){
                             $("#order_site textarea").css("height","100");
                             $("#order_site input[type='text'],#order_site textarea").click(function(){ $(this).prev().append("<div id='podskazka' style='width:300px;display:block;position:absolute;left:780px;margin-top:15px;'><div style='position:absolute;margin-left:-10px;display:block;'>-</div> " + $(this).attr("title") + "</div>");   })
                                                                .blur(function(){ $(this).prev().find("div").empty(); });
                             });

// Рассчет стоимости продвижения сайта
function send_progress(value) {
    $("#inputArea input[type='submit']").attr("disabled", true);
    var req = new JsHttpRequest();
    req.onreadystatechange = function() {
        if (req.readyState == 4) {
           if(req.responseJS.q == 1){
                               //alert(req.responseJS.otvet);
                               dialog("<center>Запрос на расчет стоимости отправлен!</center>");
                               $("#inputArea form").each(function() { this.reset();});
                               }else{
                               dialog("<center>Ошибка!Запрос на расчет стоимости не отправлен!</center>");
                               }
                               $("#inputArea input[type='submit']").attr("disabled", false);
        }
    }
    req.open(null, '/upload.php', true);

    req.send( { q: value , ajax: "send_progress" } );
}
// Аренда сайта
function site_lease(value){
       var req = new JsHttpRequest();
       req.onreadystatechange = function() {
       if (req.readyState == 4) {
                                 dialog(req.responseJS.otvet);
                                 if(req.responseJS.ok)
                                 balans_now(req.responseJS.balans_now);
                                 }else{
                                       
                                       }
       }
       req.open(null, '/upload.php', true);

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

}
// Покупка домена
function site_buy(value){
       var req = new JsHttpRequest();
       req.onreadystatechange = function() {
       if (req.readyState == 4) {
                                 dialog(req.responseJS.otvet);
                                 if(req.responseJS.ok)
                                 balans_now(req.responseJS.balans_now);
                                 }else{

                                       }
       }
       req.open(null, '/upload.php', true);

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

}



var out = {
	ten: document.getElementById('ten'),
	body: document.getElementById('body')
    };

function glass_on()
{
	with(out.ten.style)
	{
		display = 'block';
        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;
	}
}
function glass_off(){
         out.ten.style.display = "none";
         }




  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 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 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 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 location_load(value,res){

       var req = new JsHttpRequest();
       req.onreadystatechange = function() {
       if (req.readyState == 4) {
                                if(req.responseJS.second){
                                 $("#second_div").empty().html(req.responseJS.second);
                                 $("#third_div").empty().html(req.responseJS.third);
                                 }
                                 if(req.responseJS.third){
                                 $("#third_div").empty().html(req.responseJS.third);
                                 }
                                 }
       }
       req.open(null, '/upload.php', true);

       req.send( { q: value , number_div: res, ajax: "user_location" } );

return true;

}
// Выбор местоположения для фор регистрации и т.д.
function location_select(first,second,third){
       $(document).ready(function(){
       location_load(first,"second_div");
       });
       $(document).ready(function(){
       location_load(second,"third_div");
       });
       }
// Добавление товара в корзину
function shop_basket(value,col){
       var req = new JsHttpRequest();
       req.onreadystatechange = function() {
       if (req.readyState == 4) {
                                 if(col == undefined){
                                                      dialog("<center>Товар добавлен в корзину!</center>","500","200");
                                                      }
                                 shop_col_now(req.responseJS.col);
                                 shop_sum_now(req.responseJS.sum);
                                 }
       }
       req.open(null, '/upload.php', true);

       req.send( { q: value , c: col, ajax: "shop_basket" } );

}
// Окно с содержимым корзины
function dialog_basket(value,w,h){
 $("#dialog").empty().append("<center>" + value + "</center>");
 $("#dialog").dialog({ buttons:{ "Закрыть": function() {$(this).dialog("close");},
                                 "Пересчитать": function() { },
                                 "Оформить": function() {$(this).dialog("close"); site_order(); }},
                                  width: w,
                                  modal:true,
                                  resizable: false,
                                  draggable: false,
                                  close: function(){ $("#dialog").dialog("destroy");}
                                  });
}
//Оформление заказа
function site_order(){
 $("#dialog").empty().append("<center>Вы готовы к оформлению заказа?</center>");
 $("#dialog").dialog({ buttons:{ "Нет": function() {$(this).dialog("close");},
                                 "Да": function() {$(this).dialog("close"); shop_order_form(); }},
                                  width: 300,
                                  modal:true,
                                  resizable: false,
                                  draggable: false,
                                  close: function(){ $("#dialog").dialog("destroy");}
                                  });
}
//Итоговая форма оформления заказа
function shop_order_form(){

var req = new JsHttpRequest();
       req.onreadystatechange = function() {
       if (req.readyState == 4) {
                                 if(req.responseJS.q == false){
                                                               dialog("Корзина пуста.<br>Дальнейшие действия невозможны.");
                                                               return false;
                                                               }
                                 $("#dialog").empty().append("<center>" + req.responseJS.q +"</center>");
                                 $("#dialog").dialog({ buttons:{ "Нет": function() {$(this).dialog("close");},
                                                                  "Да": function() {$(this).dialog("close"); shop_order_form_ok(); }},
                                  width: 300,
                                  modal:true,
                                  resizable: false,
                                  draggable: false,
                                  close: function(){ $("#dialog").dialog("destroy");}
                                  });
                                 }
       }
       req.open(null, '/upload.php', true);

       req.send( { ajax: "shop_order_form" } );
}
//Добавление заказа в базу данных заказа
function shop_order_form_ok(){
       var req = new JsHttpRequest();
       req.onreadystatechange = function() {
       if (req.readyState == 4) {
                                //alert(req.responseJS.otv);
                                $("#dialog").empty().append("Ваш заказ отправлен на обработку . В ближайшее время с Вами свяжется наш специалист для уточнения способа доставки и оплаты товара.<br><br>Подробную информацию по раннее сделанным заказам, Вы можете получить в личном кабинете, в разделе 'Заказы'.");
                                $("#dialog").dialog({ buttons:{ "Закрыть": function() {$(this).dialog("close"); window.location.reload(); }},
                                  width: 700,
                                  modal:true,
                                  resizable: false,
                                  draggable: false,
                                  close: function(){ $("#dialog").dialog("destroy"); window.location.reload(); }
                                  });
                                 }
       }
       req.open(null, '/upload.php', true);

       req.send( { ajax: "shop_order_form_ok" } );

}

// Пересчитать в рорзине товар
function shop_basket_input(value){
    col= $("#col" + value).val();
    shop_basket(value,col);
    $(this).dialog("close");
    shop_basket_show();
}

//Отобразить корзину в диалоговом окне
function shop_basket_show(value){
       var req = new JsHttpRequest();
       req.onreadystatechange = function() {
       if (req.readyState == 4) {
                                //alert(req.responseJS.q);
                                dialog_basket(req.responseJS.q,"700");
                                 }
       }
       req.open(null, '/upload.php', true);

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

}
// Функция удаляет из корзины элементы, по нажатию крестика в диалоговом окне
function shop_basket_products_del(value){
       $("#tr" + value).fadeOut("slow",function(){ $(this).empty(); });
       var req = new JsHttpRequest();
       req.onreadystatechange = function() {
       if (req.readyState == 4) {
                                //alert(req.responseJS.q);
                                shop_col_now(req.responseJS.col);
                                shop_sum_now(req.responseJS.sum);
                                $("#summa_all").text(req.responseJS.sum);
                                //dialog(req.responseJS.q,"700");
                                 }
       }
       req.open(null, '/upload.php', true);

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

}

// Количество товара
function shop_col_now(value){
$("#shop_col_now").fadeOut("slow",function(){ $(this).empty().append(value).fadeIn("slow"); });
}
// Общая сумма товара
function shop_sum_now(value){
$("#shop_sum_now").fadeOut("slow",function(){ $(this).empty().append(value).fadeIn("slow"); });
}
// Изменение порядка сортировки товара
function shop_catalog_sort(){
       var a=$("#sort option:selected").val()
       var req = new JsHttpRequest();
       req.onreadystatechange = function() {
       if (req.readyState == 4) {
                                  window.location.reload();
                                 }
       }
       req.open(null, '/upload.php', true);

       req.send( { q: a , ajax: "shop_catalog_sort" } );
                             }

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, '/upload.php', true);
    req.send( { q: value , ajax: "poisk_site" } );
}

