//---------------------------------------------------------------------------
// by Athari http://snowlands.org.ru/a1
//---------------------------------------------------------------------------
var ids = new Array();
var count=0;
//---------------------------------------------------------------------------
function gel (id)
{
  if (document.getElementById)
    return document.getElementById(id);
  else if (document.all)
    return document.all[id];
  return null;
}
//---------------------------------------------------------------------------
function gel2 (id)
{
  return ids[id];
}
//---------------------------------------------------------------------------
function gtag (ctl, tag)
{
  return ctl.getElementsByTagName(tag);
}
//---------------------------------------------------------------------------
function nprod (n, d)
{
  var el = gel('prod'+n),
      val = parseInt(el.value);
  if (isNaN(val)) val = 0;
  val += d;
  if (val > 99)   val = 99;
  if (val < 0)    val = 0;
  el.value = val;
  el.style.background = el.value > 0 ? "#FFD988" : "white";
  recalc();
}
//---------------------------------------------------------------------------
function chk (n)
{
  var el = gel('prod'+n);
  if (isNaN(parseInt(el.value)))
    el.value = "0";
  el.style.background = el.value > 0 ? "#FFD988" : "white";
  recalc();
}
//---------------------------------------------------------------------------
function recalc ()
{
  var priceall = 0,
      numall = 0,
      lst = "",
      edt = gtag(document, 'input'),
      prevsec = "";
   count_before=count;
   count=0;
  for (var i=0; i<edt.length; ++i) {
    if (edt[i].id.substring(0, 4) == 'prod') {
	//console.log(edt[i].id);
      var price = parseInt($('#'+edt[i].id.replace("prod", "pr")).text()),
          num = parseInt(edt[i].value),
          sec = $('#'+edt[i].className.replace(/sum sid/, 'sec')).text();
      if ((num > 0)||((edt[i].id=='prod10000')&&(count>0))){
        priceall += price * num;
        numall += num;
        if (sec != prevsec) {
          prevsec = sec;
          lst += "<tr><td class=red>" + sec + "<td><td>";
        }
		if (edt[i].id!='prod10000')	//посчитаем кол-во заказанного без учета набора
			count++;
        prod_sel = gel('sel'+edt[i].id.replace(/prod(\d+)/, '$1'));
        prod_name = prod_sel ? " ("+prod_sel.value+")" : "";
		lst += "<tr class='item' itemid='"+edt[i].id+"'><td>" + edt[i].name.replace(/^\d+\|/, '') + prod_name + "<td class=center>" + num + "<td class=center>" + price;
      }
    }
  }
 
  gel('price').innerHTML = priceall;
  if (priceall)
    lst += "<tr><td class=red>Итого:<td class='red center'>" + /*numall +*/ "<td class='red center'>" + priceall;
  gel('list').innerHTML = lst == "" ? "<p>Вы ничего не заказали" :
      "<table><tr><td class='red thead'>Ваш заказ:<td class='red thead center'>Кол-во<td class='red thead center'>Цена" +
      lst +
      "<\/table>";
	  
   add_buttons();

   //Если в заказе нет набора - добавим...
  if ((count_before==0)&&(count>0))
	$('#prod10000').val(1).change();
  //Если в заказе только набор - удалим его
  if ((count==0)&&($('#prod10000').val()>0))
	$('#prod10000').val(0).change(); 
}
//---------------------------------------------------------------------------
function favorite ()
{
  var title = "Империя суши: доставка суши",
      url = "http://" + window.location.hostname + "/";
  if (window.external) {
    window.external.AddFavorite(url, title);
    location.href = "/?mode=fav";
    return false;
  }
  else {
    location.href = "/?mode=fav";
    return true;
  }
}
//---------------------------------------------------------------------------
function approve_order ()
{

  var code = parseInt(gel('phone_code').value).toString();
  var num  = parseInt(gel('phone_num').value).toString();
  var price = parseInt(gel('price').innerHTML);
  var err = "";

  if (price == 0) {
    err += "\nВы ничего не заказали.";
  }
  else if (price < 500) {
    err += "\nМинимальная цена заказа 500 руб.";
  }
  else if (code == "" || isNaN(parseInt(code)) || code.length < 3) {
    err += "\nНе указан или указан неверно код телефона.\nДля прямого городского номера вводите 812";
  }
  else if (num == "" || isNaN(parseInt(num)) || num.length < 7) {
    err += "\nВы не указали или ввели неверно номер телефона.";
  }
   if (err != "") {
    alert(err.substring(1));
   }
  return err == "";
}
//---------------------------------------------------------------------------
function reset_order ()
{
  if (confirm('Отменить заказ?')) {
    var edt = gtag(document, 'input');
    for (var i=0; i<edt.length; ++i)
      if (edt[i].id.substring(0, 4) == 'prod')
        edt[i].value = "0";
  }
  recalc();
  return false;
}
//---------------------------------------------------------------------------
    function initme () {
      var edt = gtag(document, 'input');
      for (var i=0; i<edt.length; ++i) {
        if (edt[i].id.substring(0, 4) == 'prod') {
          ids[edt[i].id.replace(/prod(\d+)/, 'pr$1')] = gel(edt[i].id.replace(/prod(\d+)/, 'pr$1'));
          ids[edt[i].className.replace(/sum sid/, 'sec')] = gel(edt[i].className.replace(/sum sid/, 'sec'));
        }
      }
      var b = gel('wrapper'),
          b1 = gel('header'), b2 = gel('content'), b3 = gel('footer');
      var h = window.innerHeight ? window.innerHeight : document.documentElement.clientHeight;
      if (b.offsetHeight < h) {
        b.style.height = h+'px';
        b2.style.height = (b.offsetHeight-b1.offsetHeight-b3.offsetHeight-20)+'px';
      }
      document.body.style.fontSize = 'medium';
      document.body.style.fontSize = '';
    }
//---------------------------------------------------------------------------
function popup_img (url, w, h)
{
  var x = (screen.availWidth-w)/2,
      y = (screen.availHeight-h)/2;
  window.open(url, 'popup_image', 'width='+w+',height='+h+',left='+x+',top='+y+',menubar=no,scrollbars=no,status=no,toolbar=no');
  return false;
}
//---------------------------------------------------------------------------
function init_img ()
{
  var img = document.getElementsByTagName('img')[0],
      w = img.width + 64,
      h = img.height + 136,
      l = (screen.availWidth - w) / 2;
      t = (screen.availHeight - h) / 2;
  window.resizeTo(w, h);
  window.moveTo(l, t);
}
//---------------------------------------------------------------------------

function add_buttons()
{
 $('#check .item').each(function(){
	$(this).find('td:eq(1)').append('<a href="#">+</a>').prepend('<a href="#">-</a>');
 })
 $('#check .item a').click(function(){
    _item=$('#'+$(this).parents('tr').attr('itemid'));
	if ($(this).text()=='+')
		_item.next().click()
	else
		_item.prev().click()
	return false;
 })

}
