function showHide (param)  {
  if (document.getElementById(param).style.display == 'none')
  document.getElementById(param).style.display = '';
  else document.getElementById(param).style.display = 'none';
  return true;
}

function setCookie(name, value) {
  var expdate = new Date();
  expdate.setTime(expdate.getTime() + (1000*60*60*24*365));
  var argv = setCookie.arguments;
  var argc = setCookie.arguments.length;
  var expires = (argc > 2) ? argv[2] : expdate;
  var path = (argc > 3) ? argv[3] : null;
  var domain = (argc > 4) ? argv[4] : null;
  var secure = (argc > 5) ? argv[5] : false;

  document.cookie = name + "=" + escape(value) +
    ((expires == null) ? "" : ("; expires=" +
      expires.toGMTString())) +
    ((path == null) ? "" : ("; path=" + path)) +
    ((domain == null) ? "" : ("; domain=" + domain)) +
    ((secure == true) ? "; secure" : "");
}

function getCookie(name) {
  var p = name + "=";
  var si = document.cookie.indexOf(p);
  if (si == -1) return null;
  var ei = document.cookie.indexOf(";", si + p.length);
  if (ei == -1) ei = document.cookie.length;
  return unescape(document.cookie.substring(si + p.length, ei));
}

function transliterate(cyr_str) {
  var tr = {
  "Ґ": "G", "Ё": "YO", "Є": "E", "Ї": "YI", "І": "I", 
  "і": "i", "ґ": "g", "ё": "yo", "№": "#", "є": "e", 
  "ї": "yi", "А": "A", "Б": "B", "В": "V", "Г": "G", 
  "Д": "D", "Е": "E", "Ж": "ZH", "З": "Z", "И": "I", 
  "Й": "Y", "К": "K", "Л": "L", "М": "M", "Н": "N", 
  "О": "O", "П": "P", "Р": "R", "С": "S", "Т": "T", 
  "У": "U", "Ф": "F", "Х": "H", "Ц": "TS", "Ч": "CH", 
  "Ш": "SH", "Щ": "SHCH", "Ъ": "'", "Ы": "YI", "Ь": "", 
  "Э": "E", "Ю": "YU", "Я": "YA", "а": "a", "б": "b", 
  "в": "v", "г": "g", "д": "d", "е": "e", "ж": "zh", 
  "з": "z", "и": "i", "й": "y", "к": "k", "л": "l", 
  "м": "m", "н": "n", "о": "o", "п": "p", "р": "r", 
  "с": "s", "т": "t", "у": "u", "ф": "f", "х": "h", 
  "ц": "ts", "ч": "ch", "ш": "sh", "щ": "shch", "ъ": "'", 
  "ы": "yi", "ь": "'", "э": "e", "ю": "yu", "я": "ya"
  };
  
  for (var inp in tr) {
    var res = tr[inp];
    cyr_str = cyr_str.split(inp).join(res);
  }
  
  return cyr_str;
}

function getSelected() {
  var t = '';
  if(window.getSelection){
    t = window.getSelection();
  }else if(document.getSelection){
    t = document.getSelection();
  }else if(document.selection){
    t = document.selection.createRange().text;
  }
  return t;
}

function doLoad(URL, data) {
  data.is_ajax = true;
  if (URL == null || URL == undefined || URL == false || URL == '') URL = location.href;
  $.ajax({
    "cache": false,
    "data": (data),
    "dataType": "json",
    "type": "post",
    "url": (URL),
    "success": function(data, textStatus) {
      $.each(data, function(k, val) {
        if (k != 'js') {
          $(k).html(val).decHTMLifEnc();
          $(k).val(val);
        }
      });
      if (data.js) eval(data.js);
    }
  });
}

function doLoadForm(form) {
  form.ajaxSubmit({
    "success": function (data) {
      $.each(data, function(k, val) {
        if (k != 'js') $(k).html(val).decHTMLifEnc();
      });
      if (data.js) eval(data.js);
    },
    "dataType": "json",
    "type": "post",
    "data": {"is_ajax": "1"}
  });
}

$(document).ready(function() {
  // добавляем окошко загрузки
  $('body').append('<div id="loading">Загрузка...</div>');
  $('body').append('<pre id="debug"></div>');
  // показать при загрузке ajax-контента
  $("#loading").bind("ajaxSend", function(){
    $(this).fadeIn('fast');
  }).bind("ajaxComplete", function(){
    $(this).fadeOut('fast');
  });
});

function getAbsolutePos(el) {
  var r = { x: el.offsetLeft, y: el.offsetTop };
  if (el.offsetParent) {
    var tmp = getAbsolutePos(el.offsetParent);
    r.x += tmp.x;
    r.y += tmp.y;
  }
  return r;
}

function getMousePos(event) { 
  var x = y = 0; 
  if (document.attachEvent != null) { // Internet Explorer & Opera 
    x = window.event.clientX + (document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft); 
    y = window.event.clientY + (document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop); 
  } else if (!document.attachEvent && document.addEventListener) { // Gecko 
    x = event.clientX + window.scrollX; 
    y = event.clientY + window.scrollY; 
  } else { 
  } 
  return {x:x, y:y};
}

// по окончанию набора в поле
var timeouts = new Array();

function onInputEnd(e, callback, timeout, timeouted) {
  if (!timeout) timeout = 1000;
  if (!timeouted) {
    if (timeouts[e.target.id]) clearTimeout(timeouts[e.target.id]);
    timeouts[e.target.id] = setTimeout(function() { onInputEnd(e, callback, timeout, true) }, timeout);
  } else {
    callback();
  }
}

// скрывать уведомления по прошествию 3 сек
$(function() {
  var last_err_inf_cont = null;
  var err_inf_counter = 0;
  setInterval(function() {
    if (($('#err_inf').html() != last_err_inf_cont || err_inf_counter > 0)
    && $('#err_inf > div:visible').length > 0) err_inf_counter++;
    if (err_inf_counter > 3) {
      $('#err_inf > div').fadeOut(200);
      err_inf_counter = 0;
    }
    last_err_inf_cont = $('#err_inf').html();
  }, 1000);
});


document.onkeydown = documentOnKeyDown;
function documentOnKeyDown(e) {
  if (!e) e = window.event;
  var k = e.keyCode;
  if (k == 27) {
    if ($('.popupWndBg:visible').length > 0) $('.popupWndBg, .popupWndCont').fadeOut(200);
  }
}

$(document).ready(function() {
  $('#login_form a.submit').click(function() {
    $('#login_form').submit();
    return false;
  });
  
  $('#mainmenu>li').mouseenter(function() {
    $(this).find('ul:first').show();
  }).mouseleave(function() {
    $(this).find('ul:first').hide();
  });
  
  // добавляем маркеры
  $('#categories li > ul').each(function() {
    $(this).parent().find('a:first').prepend('<span></span>');
  });
  
  // находим в структуре товаров текущий элемент
  if ($('#cid').val() > 0) {
    var $elm = $('#categories li#c'+$('#cid').val());
    if ($elm.length)  {
      $elm.find('a:first').addClass('sel');
      $elm.find('span:first').addClass('sel');
      $elm.parents('li').each(function() {
        $(this).find('span:first').addClass('sel');
      })
      $elm.parents('ul').slideDown(200);
      $elm.find('ul:first').slideDown(200);
    }
  }
  
  $('#categories a span').click(function(e) {
    $(this).parent().parent().find('ul:first').slideToggle(200);
    $(this).toggleClass('sel');
    return false;
  });
  
  // находим главном меню текущий элемент
  $('#mainmenu a').each(function() {
    if (location.href.indexOf($(this).attr('href')) != -1) {
      $(this).parents('li').each(function() {
        $(this).find('a:first').addClass('sel');
      })
    }
  });
  
  /*$('#login_form input[name=login], #login_form input[name=password], #searchform input.s').focus(function() {
    if ($(this).val() == $(this).attr('title')) $(this).attr('value', '');
  }).blur(function() {
    if ($(this).val() == '') $(this).attr('value', $(this).attr('title'));
  });*/
  
  // подсказки в формах
  $('#login_form input[name=login], #login_form input[name=password], #searchform #s').focus(function() {
    $('label[for='+$(this).attr('id')+']').hide();
  }).blur(function() {
    if ($(this).val() == '') $('label[for='+$(this).attr('id')+']').show();
  }).change(function() {
    if ($(this).val() != '') $('label[for='+$(this).attr('id')+']').hide();
  }).mouseover(function() {
    if ($(this).val() != '') $('label[for='+$(this).attr('id')+']').hide();
  });
  
  $('#login_form input[name=login], #login_form input[name=password], #searchform #s').each(function() {
    if ($(this).val() != '') $('label[for='+$(this).attr('id')+']').hide();
  });
  
  
  // убираем нижний бордер в таблице товаров
  $('table.products tr:last td').addClass('last');
  
 
  // добавить в корзину
  $('#add_to_basket').click(function() {
    $('#err_inf').load('/'+$('#ln').val()+'/basket/', {
      "add_id": $('#product_id').val(),
      "add_count": 1
    }, function() {
      /*setTimeout(function() {
        $('#err_inf>div').fadeOut(200);
      }, 3000)*/
      
    });
    return false;
  });
  
  // обелопушиваем формы
  $('.text, textarea').focus(function() {
    $(this).addClass('focused');
    $('label[for='+$(this).attr('id')+']').addClass('b');
  }).blur(function() {
    $(this).removeClass('focused');
    $('label[for='+$(this).attr('id')+']').removeClass('b');
  });
  $('.required').append('<span class="star"> *</span>');
  
  // просмотр картинок
  $('.thumbnail').click(function() {
    $('#full_image_container').stop();
    $('#full_image_container').animate({'opacity': '0.3'});
    $('#full_image').attr('src', '/image.php?id='+$(this).attr('id').substr(5)+'&w=280');
    return false;
  });
  $('#full_image').load(function() {
    $('#full_image_container').stop();
    $('#full_image_container').animate({'height': $(this).height()+'px', 'opacity': '1'});
  });

});


