$(document).ready(function()
{



	/*$(function() {     // Подлючение datepicker
		$("#birthdate").datepicker(
		{ yearRange:'1930:2005',
		monthNames: ['Январь','Февраль','Март','Апрель','Май','Июнь','Июль','Август','Сентябрь','Октябрь','Ноябрь','Декабрь'],
		monthNamesShort: ['Янв','Фев','Мар','Апр','Maй','Июн','Июл','Aвг','Сен','Окт','Ноя','Дек'],
		dayNamesMin: ['Вс','Пн', 'Вт', 'Ср', 'Чт', 'Пт', 'Сб'],
		dateFormat: 'dd.mm.yy',
		changeYear: true,
		changeMonth: true });
	});*/

  //  $(function() {
          $('#birthdate').mask("99.99.9999",{placeholder:" "});
          $("#light").lightBox();
  //    });

$("#sale").tooltip({tip: '#tooltip',effect: 'slide',offset: [5, -250]});
$("#how").tooltip({tip: '#tooltip1',effect: 'slide',offset: [5, -200]});
$("#bona").tooltip({tip: '#tooltip2',effect: 'slide',offset: [5, -150]});
$("#coin").tooltip({tip: '#tooltip3',effect: 'slide',offset: [5, -150]});
$("#howsale").tooltip({tip: '#tooltip4',effect: 'slide',offset: [5, -150]});

	//$(function()
	//{
  //     $(".light").lightBox();
//	});

	// Появление формы вопроса по товару
	// если в хеше есть send_question. (хеш - то что идет в адресной строке после #
    var loc = new String(document.location);
    if(loc.indexOf('#send_question')>-1)
    {
        show_question_form();
    }
});




/****************** Заказы ******************/

function repaintOrder()//Обновление корзины(та что в углу)
{
	$.post("/backend.php",{'action':'repaintOrder'},function(data){
			$("#order").html(data);
	},'html');
}
function addToWaitList(cod,elem)
{
	var td = $(elem).parent();
	$.ajax({
    url: '/backend.php',
    dataType : "html",
    type: "POST",
    data: {'action':'addToWait','cod':cod},
    beforeSend: function()
    {
    	td.html('<img src="/images/ajax-loader.gif" border="0"/><br/>загрузка...');
    },
    success: function (data, textStatus)
    {
        td.html(data);
    }
	});
}
function delFromWait(cod,elem)
{
	var td = $(elem).parent();
	$.ajax({
    url: '/backend.php',
    dataType : "html",
    type: "POST",
    data: {'action':'delFromWait','cod':cod},
    beforeSend: function()
    {
    	td.html('<img src="/images/ajax-loader.gif" border="0"/><br/>удаление...');
    },
    success: function (data, textStatus)
    {
        td.parent().remove();
    }
	});
}
function addToCorz(id)
{
 $.ajax({
        url: '/backend.php',
        dataType : "json",
        type: "POST",
        data: {'id':id,'col':$("#"+id).val(),'action':'addtocorz'},
        beforeSend: function()
        {
            $("#order").html('<img src="/images/ajax-loader.gif" border="0"/><br/>загрузка...');
        },
        success: function (data, textStatus)
        {
             repaintOrder();
             if ( data.col == 0 )  {
                msg = 'Не достаточно товара для резервирования';
                alert(msg);
             }
             else {
                
                $("#inorder").html('В корзине: '+data.col+' шт.');
                $("#item"+id).html('В корзине: '+data.col+' шт.');
             }
        }
         });

	/*$.post('/backend.php',{'id':id,'col':$("#"+id).val(),'action':'addtocorz'},function(data)
	{
		repaintOrder();
		$("#inorder").html('В корзине: '+data.col+' шт.');
		$("#item"+id).html('В корзине: '+data.col+' шт.');
	},'json'); */
	return false;
}

function checkminsum()
{
    var strsum;
    strsum = $("#fullsum").html();
    ind = strsum.indexOf(' руб.', 0);
    strsum = strsum.substr(0, ind);
    
    if ( strsum < 1000 ) {
      $("#prepare").fadeOut('fast');
      $("#lessmin").fadeIn('fast');
    }
    else {
      $("#lessmin").fadeOut('fast');
      $("#prepare").fadeIn('fast');
    }
}

function edit_col(el,col,id)
{
   $(el).parent().html('<input type="text" value="'+col+'" class="ordedit"><img src="/images/conf.png" border="0" class="edit" onclick="save_col(this,'+id+');">');
}


function save_col(el,vid)
{
	var t = $(el).parent();
	var col=t.find('input').val();
	$.post("/backend.php",{'id':vid,'col':col,'action':'edit_col'},
	function(data)
	{
		if(data.error==0)
		{
			t.parent().find('td.fsum').html(data.newprice+' руб.');
			t.html(data.col+' шт.<img src="/images/edit.png" onclick="edit_col(this,'+data.col+','+data.id+');"  class="edit" >');
			$("#fullsum").html(data.fullsum+' руб.');
			$("#fullcount").html(data.fullcount+' шт.');
                        checkminsum();
		}else
		{
			alert(data.error);
		}
	},'json');
	repaintOrder();
}

function removeFromOrder(id, el)
{
	$.post("/backend.php",{'id':id,'action':'removeFromOrder'},
	function(data)
	{
		if(data.error==0)
		{
                    $("#fullsum").html(data.fullsum+' руб.');
                    $("#fullcount").html(data.fullcount+'шт.');
                    if(el!=0)
                    {
                            $(el).parent().parent().remove();
                    }else
                    {
                            $("#item"+id).remove();
                    }
                    checkminsum();
		}else
		{
                    alert(data.error);
		}
	},'json');
	repaintOrder();
}

function is_busket_empty()
{
	  var total = $("#fullcount").text();
	//alert("gtgt" + total + "fr");
	var numtotal=total.replace(/\D/g, "");
	if (numtotal==0)
	{
		alert ("Ваша корзина пуста. Чтобы оформить заказ - наберите товаров в корзину!");
		return false;
	}
	else
	{
		return true;
	}
}

function checkDeliverPay(what)
{
    $.post("/backend.php", {'delivery':$("#delivery").val(), 'payment':$("#paytype").val(),'what':what,'action':'checkDelPay'},
            function(data)
            {
                switch (what)
                {
                 case 1:
                        $("#paytype").html(data);
                        if ( $("#delivery").val()!=0 && $("#delivery").val()!=3 && $("#delivery").val()!=4 )
                        {
                           $("#address_id").fadeIn("slow");
                        }
                        else
                        {
                           $("#address_id").fadeOut("slow");
                        }
                        break;
                 case 2:
                        $("#delivery").html(data);
                        if($("#paytype").val()==6){$("#nodiscount").fadeIn("slow");
                        }else{$("#nodiscount").fadeOut("slow");

                        }


                        break;
                }
            },'html');
}

function checkSendOrder()
{
    var err = "";
    var t = 0;
    if ($("#delivery").val()==0) err += "Вы не выбрали способ доставки\n";
    if ($("#paytype").val()==0) err += "Вы не выбрали способ оплаты\n";

    $(":radio[name='address_id']").each(function()
                                        {
                                           if ($(this).attr('checked'))
                                           {
                                                t = $(this).val();
                                           }
                                         });
    if( t==0 && ($("#delivery").val()!=0 && $("#delivery").val()!=3 && $("#delivery").val()!=4) )
    {
        err += "Вы не выбрали адрес доставки\n";
    }


$.ajax({
    url: '/backend.php',
    dataType : "text",
    type: "POST",
    data: {'action':'checkOrder','paytype':$("#paytype").val(), 'addr':t},
    async: false,
    cache: false,
    success: function(data, textStatus)
             {
               if ( data != 'SUCCESS')
                  err += data;
             },
    error: function()
           {
               err += "Ошибка проверки заказа";
           }
    });


    if (err == "")
    {
            return true;
    }else
    {
            alert(err);
            return false;
    }
}

function getAddr(typel)
{
  var t = $("#searchval").val();
  if(t=="")
	alert("Введите название населенного пунута или почтовый индекс");
  else {
	$.post('/backend.php',{'str':t,'action':'getAddr','typel':typel},
    function(data)
    {
       $("#addr_form").html(data);
       	if( parseInt(t))
		{
        	$("#index").val(t);
		}
    },'html');
  }
}

function addrShow(del)
{
	if(del!=0 && del!=3 && del!=4)
	{
		$("#address").fadeIn("slow");
	}else
	{
		$("#address").fadeOut("slow");
	}
}
function addrAbroad(show)
{
  if (show){
    $("#abroad").fadeIn("slow");
	$("#standard").fadeOut("slow");
  }
  else {
	$("#abroad").fadeOut("slow");
	$("#standard").fadeIn("slow");
	$("#abroad_text").val('');

  }
}
function addrAbroadAdd(show)
{
  if (show){
    $("#abroad").fadeIn("slow");
	$("#addr_link").fadeOut("slow");
	$("#abroad_text").val('');
  }
  else {
	$("#abroad").fadeOut("slow");
	$("#addr_link").fadeIn("slow");
  }
}

function addrStdShow(show)
{
  if (show){
    $("#address").fadeIn("slow");
	$("#addr_link").fadeOut("slow");
	$("#abroad_text").val('');
  }
  else {
	$("#address").fadeOut("slow");
	$("#addr_link").fadeIn("slow");
  }
}
function checkAddrForm()
{
	var err="";
	var comm = "";

  if ( !$("#abroad_text").val() || $("#abroad_text").val() == '')
  {
    if(!$("#city").val())err+='Вы не выбрали Населенный пункт\n';
//	if($("#street").val()==0 && !$("#street_text").val())err+='Вы не выбрали улицу\n';
	//if(!$("#house").val())err+='Вы не ввели Дом\n';
	//if(!$("#flat").val())err+='Вы не ввели Квартиру(офис)\n';
	//if(!$("#index").val())err+='Вы не ввели Индекс\n';

    if(err!="") alert(err);
  	else
  	{
        $.post('/backend.php',
  		{
  			'city':$("#city").val(),
  			'city_text':$("#city_text").val(),
  			'street':$("#street").val(),
  			'street_text':$("#street_text").val(),
  			'house':$("#house").val(),
  			'korp':$("#korp").val(),
  			'flat':$("#flat").val(),
  			'index':$("#index").val(),
			'comment':$("#comment").val(),
  			'action':'addAddress'
  		},function(data)
  		{
  			$("#address_id").html(data);
  			addrStdShow(0);
  		},'html');
   }
  }
  else {
        $.post('/backend.php',
  		{
  			'city':'',
  			'city_text':'',
  			'street':'',
  			'street_text':'',
  			'house':'',
  			'korp':'',
  			'flat':'',
  			'index':'',
			'comment':$("#abroad_text").val(),
  			'action':'addAddress'
  		},function(data)
  		{
  			$("#address_id").html(data);
  			addrAbroadAdd(0);
  		},'html');
  }

 // 	    setTimeout('document.location.reload(true)', 1000);

}

function saveAddrChanges()
{
	var err="";
	var comm = "";

	if ( !$("#abroad_text").val() || $("#abroad_text").val() == '')
	{
		if( !$("#city").val() ) err+='Вы не выбрали Населенный пункт\n';
	/*	if($("#street").val()==0 && !$("#street_text").val())err+='Вы не выбрали улицу\n';
		if(!$("#house").val())err+='Вы не ввели Дом\n'; */
		//if(!$("#flat").val())err+='Вы не ввели Квартиру(офис)\n';
		//if(!$("#index").val())err+='Вы не ввели Индекс\n';
         comm = $("#comment").val();
   }
    else comm = $("#abroad_text").val();


    if(err!="")
   	{
   		alert(err);
  	}else
  	{
  		$.post('/backend.php',
  		{
  			'city':$("#city").val(),
  			'city_text':$("#city_text").val(),
  			'street':$("#street").val(),
  			'street_text':$("#street_text").val(),
  			'house':$("#house").val(),
  			'korp':$("#korp").val(),
  			'flat':$("#flat").val(),
  			'index':$("#index").val(),
			'comment':comm,
			'addr_id':$("#addr_id").val(),
  			'action':'saveAddress'
  		},function(data)
  		{
  			$("#address_id").html(data);
  			addrShow(3);
  		},'html');
	}
}
function profilesaveAddrChanges()
{
	saveAddrChanges();
/*
    $.post('/backend.php',{'action':'getAddresses'},
 	function(data)
 	{
 		$("#user_addresses").html(data);
 	},'html');
*/
// ???

setTimeout('document.location.href="/profile/userinfo/"', 1000);

}
function removeFromDeal(item_id,elem)
{
	addToDeal(item_id,0);
	$(elem).parent().parent().slideToggle("slow");
}

function check_subsc()
{
	var t=0;

	$(":radio[name='address_id']").each(function(){
     if($(this).attr('checked'))
     {
     	t = $(this).val();
     }
     });
     if(t==0)
     {
     	err='Вы не выбрали адрес';
     	alert(err);
     	return false;
     }else
     {
     	if($("#agree").attr('checked'))
     	{
     		return true;
     	}else
     	{
     		err='Вы должны согласиться с условием';
	     	alert(err);
	     	return false;
     	}
     }


}

function group_select(group_id)
{
	if(!group_id)
	{
		alert('Выберите группу товаров');
		return 0;
	}
	$.post('/backend.php',{'action':'group_sel','gid':group_id},
 	function(data)
 	{
		if($("div#level"+data.level).html()!=null)
		{
			if(data.htm!='empty')
			{
				$("div#level"+data.level).replaceWith(data.htm);
				level=data.level;
				while($("div#level"+level).length)
				{
					level++;
					$("div#level"+level).remove();
				}
			}else
			{
				level=data.level;
				while($("div#level"+level).length)
				{
					$("div#level"+level).remove();
					level++;
				}
			}
		}else
		{
			if(data.htm!='empty')
			{
				$("#gr_sel").append(data.htm);
			}
		}
		$("#itemlist").html(data.items);
 	},'json');
}

function addToDeal(id,price)
{
	$.post('/backend.php',{'item_id':id,'price':price,'action':'addToDeal'},
    function(data)
    {
          $("#userdeal").html(data);
    },'html');
}

function show_question_form()
{
	$("#send_question").slideDown("slow");
}
function hide_question_form()
{
	$("#send_question").slideUp("slow");
}
function addr_edit(id, cityname, kladr)
{
//    cityname=cityname.substr(cityname.indexOf(' '));
	cityname=cityname.substr(0, cityname.indexOf(' '));
    $("#searchval").val(cityname);

    $("#addr_id").val(id);
    $.post('/backend.php',{'addr_id':id,'city_name':cityname,'action':'editAddr'},
    function(data)
    {
       $("#addr_form").html(data);
    },'html');
    $("#address").fadeIn("slow");
	if (kladr == '') $("#standard").fadeOut("fast");
	else $("#standard").fadeIn("fast");
}

function setDefaultAddr()
{
	$(".addr").each(
	function()
	{
		if($(this).attr("checked") == true)
		{
			var t=$(this).val();
			$.post('/backend.php',{'action':'setDefAddr','addr_id':$(this).val()},
			function(data)
			{
				alert('Основной адрес изменен');
			},'html');
		}
	});
}



function getStreets(city)
{
	$.post('/backend.php',
		   {'city':city,'action':'getStreet'},
			function(data)
			{
 			   	   $("#street").fadeOut("slow");
				   if(data != "")
				   {
					   $("#street").html(data);
				   }
				   else
				   {
                      $("#street").html(null);

				   }
				   $("#street").fadeIn("slow");
				   $("#street_text").val('');
 			},
			'html');
}

function setStreet()
{
	if ($("#street").val()==0)
	     $("#street_text").val('');
	else $("#street_text").val($("#street option:selected").text());
}

function validRegForm(step,typel)
{
    var err = "";
    switch (step)
    {
	    case 2:
		    if (typel=="ul"){
                        if($("#ulname").val()=="")err+='Вы не заполнили поле Наименование Организации\n';    
                        if($("#ulinn").val()=="")err+='Вы не заполнили поле ИНН\n';
                        if($("#ulkpp").val()=="")err+='Вы не заполнили поле КПП\n';                               
                        if($("#ulokpo").val()=="")err+='Вы не заполнили поле ОКПО\n';
                        if($("#ulrs").val()=="")err+='Вы не заполнили поле Расчетный счет\n';
                        if($("#ulbank").val()=="")err+='Вы не заполнили поле БИК\n';
                        if( !$("#city").val() && (!$("#abroad_text").val() || $("#abroad_text").val()=='') )err+='Вы не ввели юридический адресс\n';
                    }

                    if($("#fname").val()=="")err+='Вы не заполнили поле Имя\n';
		    if($("#fathername").val()=="")err+='Вы не заполнили поле Отчество\n';
		    if($("#surname").val()=="")err+='Вы не заполнили поле Фамилия\n';
		    if($("#phone").val()=="")err+='Вы не заполнили поле Телефон\n';
                    if($("#phone2").val()!="")if(!num.test($('#phone2').val()))
			   	{
			   		err+='Неверный ФАКС или ТЕЛЕФОН 2\n';
			   	}
		    if($("#login").val()=="")err+='Вы не заполнили поле Логин\n';
		    if($("#pass").val()=="")err+='Вы не заполнили поле Пароль\n';
		    if($("#conf_pass").val()!=$("#pass").val())err+='Пароль не совпадает с подтверждением\n';

		    if(err!="")
		    {
		    	alert(err);
		   		return false;
		    }else
		    {
			   	var datere=/([0-2]\d|3[01])\.(0\d|1[012])\.(\d{4})/;
			   	var dres=datere.test($('#birthdate').val());
			   	if(!dres)
			   	{
			   		if($('#birthdate').val()=="")
			   		{
			   		err+="";
			   		}
			   		else
			   		{
			   			err+='Неверная дата рождения\n';
			   		}
			   	}

			   	var tel=/^((8|\+7)[\- ]?)?(\(?\d{3,}\)?[\- ]?)?[\d\- ]{7,10}$/;
			   	var tres= tel.test($('#phone').val());
			   	if(!tres)
			   	{
			   		err+='Неверный телефон\n';
			   	}

			   	var re =/^[\.\-_A-Za-z0-9]+?@[\.\-A-Za-z0-9]+?\.[A-Za-z0-9]{2,6}$/;
			   	if($("#email").val()!="")
			   	{
		   			var res = re.test($('#email').val());
			   		if(!res)err+='Неверный E-mail\n';

			   	}
                                if (typel=="ul"){
                                
                                var num=/^[0-9]{10,12}$/;
			   	if(!num.test($('#ulinn').val()))
			   	{
			   		err+='Неверный ИНН\n';
			   	}
                               
                                 num=/^[0-9]{9}$/;
			   	if(!num.test($('#ulkpp').val()))
			   	{
			   		err+='Неверный КПП\n';
			   	}
                               
                                num=/^[0-9]{8,10}$/;
			   	if(!num.test($('#ulokpo').val()))
			   	{
			   		err+='Неверный ОКПО\n';
			   	}
                               
                                 num=/^[0-9]{20}$/;
			   	if(!num.test($('#ulrs').val()))
			   	{
			   		err+='Неверный Расчетный счет\n';
			   	}
                               
                                num=/^[0-9]{9}$/;
                                if(!num.test($('#ulbank').val()))
			   	{
			   		err+='Неверный БИК\n';
			   	}
                               
                                }
			   	if(err!="")
			   	{
			   		alert(err);
			   		return false;
			  	}else
			  	{
			  		return true;
			  	}
		    }
		    break;
		case 3:
                        var success = false;
			var del=$("#delivery").val();
                        err='';
			if(del!=0 && del!=3 && del!=4)
			{
                            if( !$("#city").val() && (!$("#abroad_text").val() || $("#abroad_text").val()=='') )err+='Вы не выбрали населенный пункт\n';
                            /*if($("#street").val()==0 && !$("#street_text").val())err+='Вы не выбрали улицу\n';
                            if(!$("#house").val())err+='Вы не ввели Дом\n'; */
                            /*if(!$("#index").val())err+='Вы не ввели Индекс\n';*/
			}
                        else
                            if (del==0) err += 'Вы не выбрали Способ доставки\n';

                        if (!document.getElementById('aggree').checked)
                            err += "Вы не выразили своего согласия на хранение и обработку Ваших персональных данных\n";

                        if (err != "") alert(err);
                        else success =  true;

                        return success;
			break;
	 }
}

/* useredit */

function useredit(param,elem)
{
	$.post('/backend.php',{'param':param,'action':'useredit'},
	function(data)
	{
		$(elem).parent().parent().find('td.edit').html(data);
		$(elem).replaceWith('<a href="#" onclick="usereditconf(\''+param+'\',this);" class="editlink"><img src="/images/conf.png" title="подтвердить" alt="подтвердить"/>&nbsp;подтвердить</a>');
		if(param=='birthdate')
		{
			$(function()
			{
				$("#birthdate").datepicker(
				{yearRange:'1930:2005',
				monthNames: ['Январь','Февраль','Март','Апрель','Май','Июнь','Июль','Август','Сентябрь','Октябрь','Ноябрь','Декабрь'],
				monthNamesShort: ['Янв','Фев','Мар','Апр','Maй','Июн','Июл','Aвг','Сен','Окт','Ноя','Дек'],
				dayNamesMin: ['Вс','Пн', 'Вт', 'Ср', 'Чт', 'Пт', 'Сб'],
				dateFormat: 'dd.mm.yy',
				changeYear: true,
				changeMonth: true});
			});
		}
	},'html');
}

function usereditconf(param,elem)
{
	var newval="";
	switch(param)
	{
		case 'name':
			newval = $("#firstname").val();
			break;
		case 'surname':
			newval = $("#lastname").val();
			break;
		case 'fathername':
			newval = $("#secondname").val();
			break;
		case 'gender':
		    if($(':radio[name=gender]:checked'))
		    {
                        newval = $(':radio[name=gender]:checked').val();
		    }else
		    {
		    	alert('Выберите пол');
		    	return false;
			}
            break;
        case 'email':
           	var re =/^[\.\-_A-Za-z0-9]+?@[\.\-A-Za-z0-9]+?\.[A-Za-z0-9]{2,6}$/;
		   	var res = re.test($('#email').val());
		   	if($('#email').val().length>0)
		   	{
		   		if(!res)
		   		{
		   			alert('Неверный E-mail');
		   			return false;
				}else
				{
					newval = $('#email').val();
				}
			}else
			{
				newval = $('#email').val();
			}
        	break;
        case 'birthdate':
        	newval = $("#birthdate").val();
        	break;
        case 'phone':
        	newval = $("#phone").val();
        	break;
        case 'phone2':
        	newval = $("#phone2").val();
        	break;
        case 'password':
			if($("#new_pass").val().length<4)
			{
				alert('Слишком короткий пароль');
				return false;
			}
			if($("#new_pass").val()!=$("#new_pass_conf").val())
			{
				alert('Пароль не вопадает с потверждением');
				return false;
			}else
			{
				newval = $("#new_pass").val();
			}
	}
	$.post('/backend.php',{'param':param,'newvalue':newval,'action':'usereditconf'},
	function(data)
	{
		if(data.error==0)
		{
			$(elem).parent().parent().find('td.edit').html(data.string);
			$(elem).replaceWith('<a href="#" onclick="useredit(\''+param+'\',this);" class="editlink"><img src="/images/edit.png" title="изменить" alt="изменить"/>&nbsp;изменить</a>');
		}
	},'json');
}

/* скрытие - отображение DIV  */
function showdiv(namediv)
{
  
   if (namediv.style.visibility == 'hidden')

    {
           namediv.style.visibility = 'visible';
           namediv.style.height ='auto';
           namediv.style.overflow='hidden';
        }
    else
    {
        namediv.style.visibility = 'hidden';
        namediv.style.height ='0px';
        namediv.style.overflow='hidden';
    }



}

function openClose(div_id)
{
    if (document.getElementById(div_id).style.visibility == 'hidden')
    {
    document.getElementById(div_id).style.visibility = 'visible';
    document.getElementById(div_id).style.height ='auto';
    } 
    else
    {
    document.getElementById(div_id).style.visibility = 'hidden';
    document.getElementById(div_id).style.height ='0px';
    } 
}
/*Тут у нас валидация формы с вашими вопросами*/



//модуль просмотра видео с youtube

function ShowMovie(div_id,link_video_on_youtube)
{
    /*
     *код для вставки в страницу:
     *  <div id="div_id" style="display:none;"></div>
     *  <div onclick="ShowMovie('div_id','link');" style="cursor: pointer;">
     *  Поcмотреть видео</div>
     *
    */

    if (document.getElementById(div_id).style.display=='none')
    {
        string="<table WIDTH='100%' HEIGHT='100%' >"
            +"<TR><TD>&nbsp</TD></TR>"
            +"<TR><TD ALIGN=CENTER><table ALIGN=CENTER>"
            +"<TR><TD ALIGN=CENTER id='mov'><div id='MOOOOVIE'>"
            +"<iframe width='640' height='390' src='"
            +link_video_on_youtube
            +"' frameborder='0' allowfullscreen></iframe>"
            +"</div></TD></TR>"
            +"<TR><TD style="
            +'" font-size:20px; color: white; background-color: black; opacity: 0.9; text-align: right; cursor: pointer;"'
            +' onclick="ShowMovie('+"'"+div_id+"'"+');">Закрыть</TD></TR>'
            +"</table></TD></TR>"
            +"<TR><TD>&nbsp</TD></TR>"
            +"</table>";
        myDiv=document.getElementById(div_id);
        myDiv.innerHTML=string;
        document.getElementById(div_id).style.visibility = 'visible';
        document.getElementById(div_id).style.height ='auto';
        document.body.style.overflowX='hidden';
        document.body.style.overflowY='hidden';
        document.getElementById(div_id).style.display='block';
        document.getElementById(div_id).style.opacity='0.3';
        document.getElementById(div_id).style.backgroundColor= 'black';
        document.getElementById(div_id).style.width= !window.opera?'100%':document.body.clientWidth;
        document.getElementById(div_id).style.height= !window.opera?'100%':document.body.clientHeight;
        document.getElementById(div_id).style.position= 'fixed';
        document.getElementById(div_id).style.zIndex='1000';
        document.getElementById(div_id).style.top= '0px';
        document.getElementById(div_id).style.left= '0px';
        document.getElementById(div_id).style.verticalAlign='middle';
        document.getElementById(div_id).style.textAlign= 'center';
        document.getElementById(div_id).style.filter='alpha(opacity=50)';
        document.getElementById(div_id).focus('mov');
         
    }
    else
    {
        string=" ";
        myDiv=document.getElementById(div_id);
        myDiv.innerHTML=string;

        document.getElementById(div_id).style.display='none';
        document.getElementById(div_id).style.visibility = 'hidden';
        document.getElementById(div_id).style.height ='0px';
        document.body.style.overflowX='auto';
        document.body.style.overflowY='auto';
    }
}


function refresh_div(name_funk,act,pid)
{

    $.post('/backend.php',{'action':name_funk,'fld':act},
    function(data)
    {
       
        if (data != 'error') {
              document.getElementById('#'+act+pid).innerHTML=data;
              document.getElementById('#'+act+pid).focus();
        
        }

    },'html');



}

function open_dialog(
                    output_div_idb,// id  окна куда выводится сообщение
                    name_funk,//наименование вызываемой функции
                    parametrs)// параметры вызываемой функции
{

    $.post('/backend.php',{'action':name_funk,'parametrs[]':parametrs},
    function(data)
    {
       if (data != 'error') {
              $("#"+output_div_idb).html(data);
        //      $("#"+output_div_id).focus();
        }
    },'html');


}

function dialog_form(
                    output_div_id ,// id открываемого окна
                    name_funk,//наименование вызываемой функции
                    parametrs,// параметры вызываемой функции
                    dwidth ,//Ширина окна
                    dheight,//Высота окна
                    parent_output_div_id,// id окна либо родительского Divа
                    parent_name_funk,// наименование родительской функции
                    parents_parametrs)// параметры родитьельской функции
{
 /*   var par_par='';

   for(var i=0; i<parents_parametrs.length; i++)
    {
        par_par = par_par +"'"+ parents_parametrs[i]+"'";
        if (i<parents_parametrs.length-1) par_par=par_par+",";
        }
*/
/* var div_htm="<table cellspacing=\"0\" cellpadding=\"0\" border=\"0\" class=\"pastel_cell\" style=\"width: 100%;\">\n\
<tr>\
	<td class=\"lu\" style=\"width: 4px\"></td>\
	<td class=\"u\" ></td>\
	<td class=\"ru\" style=\"width: 4px\"></td>\
</tr>\
<tr>\
	<td class=\"l\" style=\"width: 4px\"></td>\
	<td  style=\"text-align: center; \">\
<div style=\"text-align: right; padding: 4px;\" >\
<img  src=\"/images/closeX.gif\" value=\"Закрыть\" style=\"cursor: pointer; \" onclick=\"close_dialog_form('"+output_div_id+"','"+parent_output_div_id+"','"+parent_name_funk+"','"+parents_parametrs+"'); \"/></div><div align=center id='"+output_div_id+"_body'></div>\
		</td>\
	<td class=\"r\" style=\"width: 4px\">\
	</td>\
</tr>\
<tr>\
	<td class=\"ld\" style=\"width: 4px\"></td>\
	<td class=\"d\"></td>\
	<td class=\"rd\" style=\"width: 4px\"></td>\
</tr>\
</table>";*/

    var div_htm="<div style=\"text-align: right; padding: 4px;\" >\
<img  src=\"/images/closeX.gif\" value=\"Закрыть\" style=\"cursor: pointer; \" onclick=\"close_dialog_form('"+output_div_id+"','"+parent_output_div_id+"','"+parent_name_funk+"','"+parents_parametrs+"'); \"/></div><div align=center id='"+output_div_id+"_body'></div>";
 $("#"+output_div_id).html(div_htm);
   open_dialog(output_div_id+'_body',name_funk,parametrs);
 var   wwidth=$(window).width();
 var   wheight=$(window).height();
    if(wwidth<dwidth)wwidth=0;
    else wwidth=(wwidth-dwidth)/2-(wwidth-dwidth)%2;
    if(wheight<dheight)wheight=0;
    else wheight=(wheight-dheight)/2-(wheight-dheight)%2;

    $('#'+output_div_id).css("position","absolute");
    $('#'+output_div_id).css('top',wheight+'px');
    $('#'+output_div_id).css('left',wwidth+'px');
    $('#'+output_div_id).css('width',dwidth+'px');
    $('#'+output_div_id).css('zIndex','100');
    $('#'+output_div_id).css('text-align','center');
    $('#'+output_div_id).css('background-color','white');
    $('#'+output_div_id).css('border-radius','5px');
    $('#'+output_div_id).css('border','3px solid RGB(229, 237, 247)');
    $('#'+output_div_id+'_body').css('width','98%');
    $('#'+output_div_id+'_body').css('height',dheight+'px');
    $('#'+output_div_id+'_body').css('margin','5px');
    $('#'+output_div_id+'_body').css('background-color','white'); 
    $('#'+output_div_id+'_body').css('border','1px solid lightgrey');
    $('#'+output_div_id+'_body').css('scroll','yes');
    $('#'+output_div_id+'_body').css('overflow','auto');
     $('#'+output_div_id).css('display','block');
    
}

// закрытие диалоговога окна
function close_dialog_form(
                    output_div_id,// id закрываемого окна
                    parent_output_div_id,// id окна либо родительского Divа
                    parent_name_funk, // наивенование функции
                    parents_parametrs)// параметры функции
{

    $('#'+output_div_id).css('display','none');
    $('#'+output_div_id).html('');
//  var par_par='';
//    for(var i=0; i<parents_parametrs.length; i++)
 //   {
  //      par_par = par_par +"'"+ parents_parametrs[i]+"'";
   //     if (i<parents_parametrs.length-1) par_par=par_par+",";
    //    }
    var is_id=$('#'+parent_output_div_id+'_body').html();//проверка на существование
    if (is_id==null)
        open_dialog(parent_output_div_id,parent_name_funk,parents_parametrs);
    else
      open_dialog(parent_output_div_id+'_body',parent_name_funk,parents_parametrs);


} //close_dialog_form

function ShowMovie(div_id,link_video_on_youtube)
{
    /*
     *код для вставки в страницу:
     *  <div id="div_id" style="display:none;"></div>
     *  <div onclick="ShowMovie('div_id','link');" style="cursor: pointer;">
     *  Поcмотреть видео</div>
     *
    */

    if (document.getElementById(div_id).style.display=='none')
    {
        string="<table WIDTH='100%' HEIGHT='100%' >"
            +"<TR><TD>&nbsp</TD></TR>"
            +"<TR><TD ALIGN=CENTER><table ALIGN=CENTER>"
            +"<TR><TD ALIGN=CENTER id='mov'><div id='MOOOOVIE'>"
            +"<iframe width='640' height='390' src='"
            +link_video_on_youtube
            +"' frameborder='0' allowfullscreen></iframe>"
            +"</div></TD></TR>"
            +"<TR><TD style="
            +'" font-size:20px; color: white; background-color: black; opacity: 0.9; text-align: right; cursor: pointer;"'
            +' onclick="ShowMovie('+"'"+div_id+"'"+');">Закрыть</TD></TR>'
            +"</table></TD></TR>"
            +"<TR><TD>&nbsp</TD></TR>"
            +"</table>";
        myDiv=document.getElementById(div_id);
        myDiv.innerHTML=string;
        document.getElementById(div_id).style.visibility = 'visible';
        document.getElementById(div_id).style.height ='auto';
        document.body.style.overflowX='hidden';
        document.body.style.overflowY='hidden';
        document.getElementById(div_id).style.display='block';
        document.getElementById(div_id).style.opacity='0.3';
        document.getElementById(div_id).style.backgroundColor= 'black';
        document.getElementById(div_id).style.width= !window.opera?'100%':document.body.clientWidth;
        document.getElementById(div_id).style.height= !window.opera?'100%':document.body.clientHeight;
        document.getElementById(div_id).style.position= 'fixed';
        document.getElementById(div_id).style.zIndex='1000';
        document.getElementById(div_id).style.top= '0px';
        document.getElementById(div_id).style.left= '0px';
        document.getElementById(div_id).style.verticalAlign='middle';
        document.getElementById(div_id).style.textAlign= 'center';
        document.getElementById(div_id).style.filter='alpha(opacity=50)';
        document.getElementById(div_id).focus('mov');

    }
    else
    {
        string=" ";
        myDiv=document.getElementById(div_id);
        myDiv.innerHTML=string;

        document.getElementById(div_id).style.display='none';
        document.getElementById(div_id).style.visibility = 'hidden';
        document.getElementById(div_id).style.height ='0px';
        document.body.style.overflowX='auto';
        document.body.style.overflowY='auto';
    }
}
