var hoverObj = null;
var tm = null;
function Hide(e)
{
  var obj = $('#popup_menu');
  if (obj.css('display') == 'block')
  {
    clearTimeout(tm);
    tm = setTimeout(function()
    {
      var ofs  = obj.offset();
      var w    = obj.width();
      var h    = obj.height();
      var hide = false;
      hide = e.pageX < ofs.left || e.pageX > (ofs.left + w);
      hide = hide || e.pageY < (ofs.top - 40) || e.pageY > (ofs.top + h);
      if (hide)
      {
        $('#popup_menu').fadeOut('fast');  
      }
      
    }, 400);
    
  }
  
  
  
   //if
} //checkHover


function Init()
{
  $._indicator = function(show)
  {
    show ? DialogShow('<img src="/img/load.gif"/>', null, 38, 300,38) : DialogHide();
  };

  $('.item_1').hover(
  function()
  {
    var obj = $(this);
    var subObj = $('td[pid=' + obj.attr('id') + ']');
    clearTimeout(tm);
    
    if (subObj.length)
    {
      var html = '';
      var hgt  = 0;
      subObj.each(function()
      {
        html += $(this).html();
        hgt += 24;
      });
      
      var ofs = obj.offset();
      hgt += 14;
      $('#popup_content').html(html);
      $('#popup_menu').css({left:ofs.left + 'px', top:(ofs.top + 40) + 'px', height:hgt + 'px'}).fadeIn('fast');
      
      $('#popup_menu, #popup_menu > *').mouseout(Hide);            
    };
  }, Hide);
}

$._url = 'index.php';

function MSG(msg)
{
  alert(msg);
}

function ItemAdd(zap_id)
{
  $._json(function(data)
  {
    _w('basket', 'заказано позиций - ' + data);
    MSG('Отправлено в корзину ' + data + ' позиций');
  }, 'ItemAdd', zap_id);
}

function ItemDel(zap_id)
{
  $._json(function(data)
  {    
    OrderStep1();
  }, 'ItemDel', zap_id)
}

function OrderStep1()
{
  _w('content_main', _c(_t(tplOrderStep, 'active1', 'active')));
  
  $._json(function(data)
  {    
    if (data) _wa('content_main', _c(_t(tplOrderItems, 'item', data)));
    else _w('content_main', '<h3 class="title3">Корзина пуста...</h3>');
  }, 'OrderGet');
}

function OrderStep2()
{
  _w('content_main', _c(_t(tplOrderStep, 'active2', 'active')));
  $._json(function(data)
  {    
    if (data)
    {
      var ur_data;
      var ur_sdata = '';
      if ((isset(data['info_ur'])) && (data['info_ur'] != 'null'))
      {        
        eval('ur_data=' + data['info_ur'] + ';');
        ur_sdata = _c(tplUrData);
        //_c(_t(tplUrData, ur_data));
        //alert(ur_data);
      }          
      _wa('content_main', _c(_t(tplUserForm, data, 'ur_data', ur_sdata)));
      if (ur_sdata.length) _map(ur_data);      
    }    
    else _wa('content_main', tplAuthForm); 
  }, 'UserGet');  
}

function OrderStep3()
{
  _w('content_main', _c(_t(tplOrderStep, 'active3', 'active')));
  $._json(function(data)
  {
    if (isset(data))
    {
      var ur_report = '';
    
      if ((isset(data[0]['info_ur'])) && (data[0]['info_ur'] != 'null'))
      {
        eval('ur_report=' + data[0]['info_ur'] + ';');
        ur_report = _t(tplUrReport, ur_report);
      }
      
      _wa('content_main', _c(_t(tplOrderReport, data[0], 'ur_report', ur_report, 'item', data[1])));
    }
    else
    {
      MSG("Вы не прошли регистрацию, или не заказали товар");
      OrderStep1();
    }
  }, 'FullOrderGet');  
}

function Recalc()
{
  var list = {};
  $('input', '#content_main').each(function()
  {
    list[$(this).attr('id')] = $(this).val();
  })
  
  $._json(function(data)
  {
    OrderStep1();
  }, 'Recalc', list);
}

function LogIn()
{
  $._json(function(data)
  {
    if (data) OrderStep2();
    else MSG('неправильный логин или пароль');
  }, 'AjaxLogIn', $('#inlogin').val(), $('#inpassword').val());
}

function RegisterShow(is_ur)
{
  _w('form_register', (is_ur) ? tplURRegister : tplRegister);
  $('#form_register').show('slow');
}

function LogOut()
{
  $.cookie('cpassword_md5', null);
  $.cookie('clogin', null);
  $._json(null, 'UsrLogOut');
  OrderStep2();
}

function UserUpdate()
{
  var name  = $('#name').val();
  var info  = $('#info').val();
  var mail  = $('#mail').val();
  var phone = $('#phone').val();
  var info_ur = $('#bik').length ? _rmap(['org_name', 'dolj', 'city', 'address', 'ur_address',
    'fac_address', 'phone', 'inn', 'kpp', 'rschet', 'vbanke', 'kschet', 'bik']) : null;
  
  $._json('register.php', function(data)
  {
    isset(data['err']) ? _map(data['err']) : OrderStep2();			
  }, 'UserUpdate', name, phone, mail, info, info_ur);
}

function OrderConfirm()
{
  $._json(function(data)
  {
    if (data) _w('content_main', '<h3 class="title3">Номер заявки №' + data + '. В ближайшее время наши менеджеры свяжутся с Вами.</h3>');
    else _w('content_main', 'Заявка не обработана. Попробуйте повторить оформление.');
  }, 'OrderConfirm');
}

g_light = null;
function HighLight(obj)
{
  if (isset(g_light)) g_light.removeAttr('style');
  g_light = $(obj);
  g_light.css('background', '#eeaaaa');
}

function HRemove()
{
  if (isset(g_light)) g_light.removeAttr('style');
  g_light = null;
}

function ItemShow(zap_id)
{
  document.location.assign('index.php?cmd=ItemShow&a0=' + zap_id);
}

function VinSend()
{
  var map = _rmap(['marka', 'model', 'prodYear', 'engType', 'vin',
    'detail', 'addinfo', 'fio', 'firm', 'phone', 'email']);
  var need = ['marka', 'engType', 'vin', 'detail', 'fio', 'phone'];
  for(var i = 0; i < need.length; i++)
  {
    if (map[need[i]].length == 0)
    {
      alert('Пожалуйста, заполните все поля отмеченные *');
      return;
    }
  }
  
  $._json(function(data)
  {
    if (data)
    {
      alert('Запрос успешно отправлен');
      document.location.assign('index.php');
    }    
  }, 'VinSend', map);
}

function DialogShow(content, ok, szX, top, szY)
{
 var szX2 = Math.ceil(szX/2);
 $('body').append(_t(tplDlg, 'top', top, 'szX', szX, 'szY', szY,
    'szX2', szX2, 'content', content));
}

function DialogHide()
{
  $('.dlg').remove();
}

function DialogClose()
{
  $('.dlg').remove();
}
