///
/// version #11
////////////////////////////////////////////////////////////
///////////    functions for one form c parametr 'nameForm'
////////////////////////////////////////////////////////////
function checkit(nameForm) {

	var rest = 0;
	formName = document.forms[nameForm];
	count = formName.elements['count'];
	itemID = formName.elements['itemID'];
	typeID = formName.elements['typeID'];
	catID = formName.elements['parentID'];

  if (count.value > 0) {
     rest = 1;
  }
  else {
    alert(lang[10]);
  }

  if (rest == 1) {

    var params = "count=" + count.value + "&itemID=" + itemID.value + "&catID=" + catID.value + "&typeID=" + typeID.value;

  	 $(document).ready(function(){
         /* -- send to Ajax -- */
       $.ajax({
           type: "POST",
           data: params,
           cashe: false,
           url: "/ajax/add.php",
           dataType: "json",
           beforeSend: function (){
              $("body").css({cursor:"wait"});
              $("input.inp_curs").css({cursor:"wait"});
           },
           success: function(data, textStatus){
           	  addBasketResult (data);
           },
           complete: function(data, textStatus){
              $("body").css({cursor:"auto"});
              $("input.inp_curs").css({cursor:"auto"});
           }

         });
      });

  }
  return false;
}

/* для функции checkit */
$(document).ready(function(){
  $("div.onsubmit").find("form").submit( function () {
    return false;
  } );
 $("input.newbuy").click(function(){ 	var nameForm2 = $(this).attr("id");    checkit(nameForm2); 	return false; });
});




   /* -- function added to basket --  */

function addBasketResult (ResObj) {

  var tip = ResObj.typeID;

  var plateDiv = "plateAj"+ResObj.itemID + tip;
  var formDiv = "formAj"+ResObj.itemID + tip;
  var blockDiv = "blockAj"+ResObj.itemID + tip;

  switch (ResObj.error) {
    case 0:
      document.getElementById("basketAjCount").innerHTML = ResObj.basket_count;
      document.getElementById("basketAjSum").innerHTML = ResObj.basket_sum + ' ' + lang[4];

     $("#"+formDiv).find("input:image").attr("onClick","");

     $("#"+plateDiv).show("slow", function() {
       setTimeout(function() {
          $("#"+plateDiv).hide("slow", function() {


                         $("#"+formDiv).hide("slow", function() {
      	                           $("#"+blockDiv).show("slow");
      	                  });

     	   });
        }, 2000);
     } );


       break;
     case 1:
           document.location.replace("http://komus.ru/nocookies.php");
       break;
     case 2:
             alert('error:2 ' + ResObj.itemID);
       break;
     case 3:
             alert('error:3 ');
       break;
       case 4:
             alert(lang[9] + ' error:4 ');
       break;
  }
}

/////////////////////////////////////////////////////////////////////////////
$(document).ready(function(){

  repeatList = setTimeout('void(0)',1);
 /// опускаем 1 в поле count на пиксель
	if ($.support.cssFloat) {   //
	          $("td.LeftBack").css("padding-top","1px");
	}
	else {		   // $("td.LeftBack").css("top","1px");
	}

 // обрабатываем клики по кнопке Считать упаковками

 function checkedToggle (elem){
 	 if ($(elem).is(":checked")) $(elem).attr('checked',''); else $(elem).attr('checked','checked');
 }

 $("td.boxPack").click(function(){ 	 var elemCh = $(this).parents("#HeaderPlayContainer").find("input[name='boxPack']");
     checkedToggle(elemCh);
 	 elemCh.click();
     checkedToggle(elemCh); });


 $("input[name='boxPack']").click(function(){      if ($(this).is(":checked")){
        var valPack = $(this).attr("value");
        var xCount =  $(this).parents("#cardProduct").find(":text[@name^='count']").attr("value");
        if (xCount == 0) xCount = 1;
        var diffCount = Math.ceil( xCount /  valPack);
        var resultCount = diffCount * valPack;
        if (resultCount < valPack) resultCount = valPack;

        $(this).parents("#cardProduct").find("input.countPack").attr("value", valPack);
        $(this).parents("#cardProduct").find(":text[@name^='count']").attr("value", resultCount);
         packPrice ( $(this).parents("#cardProduct").find("input.countfrom").get(0) );
      }
      else {
       $(this).parents("#cardProduct").find("input.countPack").attr("value", 1);
        packPrice ( $(this).parents("#cardProduct").find("input.countfrom").get(0) );
      }
      $(this).blur();
 });




 // делаем четные строки белыми
 $("div.checkTableMini").find("td.LineJS:odd").attr("class","middBG_odd LineJS");


 /// событие для кнопки увеличения count
	$("div.formItem div.arrowUp")
	  .mouseup( function(){
	      plusStop(this);
          selectedSum (this);
          packPrice (this);
	    })
	  .mousedown(function(){

         elCount = $(this).parents("div.formItem").find(":text[@name^='count']");
         var count_val = elCount.attr("value");
         var countPack = $(this).parents("div.formItem").find("input.countPack").attr("value");
         if ( parseInt(countPack) > 1) { var countPackVal = parseInt(countPack); } else { var countPackVal = 1; }
         var count_val_plus = countPackVal + parseInt(count_val);
         repeatList = setTimeout('calculateList(1,  elCount)',222);
         if (count_val_plus>0) $(elCount).attr("value", count_val_plus); else  $(elCount).attr("value", countPackVal);

         return false;

	}).mouseout(function(){
		 plusStop(this);
		});
 /// событие для кнопки уменьшения count
	$("div.formItem div.arrowDown")
	  .mouseup( function(){
	           plusStop(this);
               selectedSum (this);
               packPrice (this);
	     })
	  .mousedown(function(){

         elCount = $(this).parents("div.formItem").find(":text[@name^='count']");
         var count_val = elCount.attr("value");
         var countPack = $(this).parents("div.formItem").find("input.countPack").attr("value");
         if (countPack > 1) { var countPackVal = parseInt(countPack); } else { var countPackVal = 1; }
         var count_val_min = parseInt(count_val) - countPackVal;
         repeatList = setTimeout('calculateList(2, elCount)',222);
         if (count_val_min>countPackVal - 1) $(elCount).attr("value", count_val_min); else  $(elCount).attr("value", countPackVal);


         return false;

	}).mouseout(function(){
		  plusStop(this);
		});

 //////////////////////////////////////////////
 /////    увеличение комплектов
 //////////////////////////////////////////////

 $("div.checkTable a.SPlus").click(function(){ 	var SVal_prev = $(this).parents("td.BlockBack").find("div.SVal").text();
 	var SVal = ( SVal_prev * 1 ) + 1;
 	if (SVal == 51) SVal = 50;
 	$(this).parents("td.BlockBack").find("div.SVal").text(SVal);
 	$(this).parents("div.checkTable").find(":text[@name^='count']").each(function(){ 		 var count_el_v = $(this).val();
 		 var count_one_compl = Math.ceil (count_el_v / SVal_prev);
 		 var count_el_v =  count_one_compl * SVal;
 		 $(this).attr("value", count_el_v)
 		});
 	 selectedSum (this);

 	return false; });
 /// уменьшение комплектов
  $("div.checkTable a.SMin").click(function(){
 	var SVal_prev = $(this).parents("td.BlockBack").find("div.SVal").text();
 	var SVal = ( SVal_prev * 1 ) - 1;
 	if (SVal == 0) SVal = 1;
 	$(this).parents("td.BlockBack").find("div.SVal").text(SVal);
 	$(this).parents("div.checkTable").find(":text[@name^='count']").each(function(){
 		 var count_el_v = $(this).val();
 		 var count_one_compl = Math.ceil (count_el_v / SVal_prev);
 		 var count_el_v =  count_one_compl * SVal;
 		 $(this).attr("value", count_el_v)
 		});
 	 selectedSum (this);

 	return false;
 });


 /////////////////////////////////////////////////////////////////////////////
 /// выбрать все чекбоксы - selected all checkbox
 /////////////////////////////////////////////////////////////////////////////
    $("div.checkTable td.LineJS").find(":checkbox.action").each(function(){    	  if ($(this).is(":checked")){          $(this).parents("td.LineJS").attr("class","middBG_active LineJS");
         }
         selectedSum (this);
    });



    $("div.checkTable").find("input[name='tuggle']").click(function(){
	      if ( $(this).is(":checked") ) {

	        $(this).parents("div.checkTable").find(":checkbox.action").each(function(){
             if (!$(this).is(":disabled")){
   	             this.checked = "checked";
                $(this).parents("td.LineJS").attr("class","middBG_active LineJS");
             }
             });
             $(this).parents("div.checkTable").find("input[name='tuggle']").attr("checked","checked");
	      }
	      else {
              $(this).parents("div.checkTable").find(":checkbox.action").each(function(){
                 this.checked = "";
                 if ( $(this).parents("div.checkTableMini").parents("td.LineJS").is(":odd") ) {
                //    $(this).parents("td.LineJS").attr("class","middBG_odd LineJS");
                 }
                 else {
                     $(this).parents("td.LineJS").attr("class","middBG LineJS");
                     $("div.checkTableMini").find("td.LineJS:odd").attr("class","middBG_odd LineJS");
                 }
              });
              $(this).parents("div.checkTable").find("input[name='tuggle']").attr("checked","");
	      }


         selectedSum (this);

	});

	  /* -- выделяем строки -- */
    $("td.LineJS td.click").click(function(){
       if ( $(this).parents("td.LineJS").find(":checkbox.action").is(":checked") ) {
           $(this).parents("td.LineJS").find(":checkbox.action").attr("checked","");

           var  varChTableMini = $(this).parents("div.checkTableMini").find("td.LineJS").index($(this).parents("td.LineJS"));
           if ((parseInt(varChTableMini))%2==0 || varChTableMini == -1) { // "Четное число"
               $(this).parents("td.LineJS").attr("class","middBG LineJS");
           }
           else { // "Нечетное число"
               $(this).parents("td.LineJS").attr("class","middBG_odd LineJS");
           }
       }
       else {
          if (!$(this).parents("td.LineJS").find(":checkbox.action").is(":disabled")){            $(this).parents("td.LineJS").find(":checkbox.action").attr("checked","checked");
            $(this).parents("td.LineJS").attr("class","middBG_active LineJS");
          }
       }

           selectedSum (this);



    });
    $("td.LineJS td.ch_click").click(function(){
       if ( $(this).parents("td.LineJS").find(":checkbox.action").is(":checked") ) {
          if (!$(this).parents("td.LineJS").find(":checkbox.action").is(":disabled")){
             $(this).parents("td.LineJS").find(":checkbox.action").attr("checked","checked");
             $(this).parents("td.LineJS").attr("class","middBG_active LineJS");
          }
       }
       else {
          $(this).parents("td.LineJS").find(":checkbox.action").attr("checked","");
           var  varChTableMini = $(this).parents("div.checkTableMini").find("td.LineJS").index($(this).parents("td.LineJS"));
           if ((parseInt(varChTableMini))%2==0 || varChTableMini == -1) { // "Четное число"
               $(this).parents("td.LineJS").attr("class","middBG LineJS");
           }
           else { // "Нечетное число"
               $(this).parents("td.LineJS").attr("class","middBG_odd LineJS");
           }
       }
          selectedSum (this);
    });
  ///////////////////////////////////
});
//// функция для вывода - выбранных товаров на сумму
function selectedSum (sel){
     /*-----------------------------------*/
       var itogo = 0;
       $(sel).parents("div.checkTable").find(":checkbox.action").each(function(){
  	      if ( $(this).is(":checked") ) {
  	         var count_tmp = $(this).parents("td.LineJS").find("input.countfrom").attr("value");
  	         var sum_tmp =  $(this).parents("td.LineJS").find("input.priceyour").attr("value");
  	         itogo = itogo + ( count_tmp * sum_tmp );
  	      }
       });
      itogo = itogo / 100;
      $(sel).parents("div.checkTable").find("#buttonsBlock").text(itogo + " Т.");
      // alert (itogo);
     /*----------------------------------*/
}

////  функция для остановки изменения count
function plusStop(el) {
         if (repeatList > 0) clearTimeout(repeatList);
}

 //// функция расчета цены в зависимости от упаковки
function packPrice (el){
         var pack_qty = $(el).parents("div.formItem").find("input.pack_qty").attr("value");
        //elCount = $(el).parents("div.formItem").find(":text[@name^='count']");
         //var count_val = elCount.attr("value");

          var count_val = $(el).parents("div.formItem").find("input.countfrom").attr("value");

         var tip = $(el).parents("div.formItem").find("input.typeID").attr("value");
         var item = $(el).parents("div.formItem").find("input.itemID").attr("value");


//         if (pack_qty < 1) pack_qty = 1;
         if (pack_qty > 1) {              $("#Price" + item + tip).load("/ajax/pricePack.php", "pack_qty=" + pack_qty + "&itemID=" + item + "&count=" + count_val );
         }
}

 ////  функция для изменения count
function calculateList(tip, elCount) {


	var count_val = elCount.attr("value");

    var countPack = $(elCount).parents("div.formItem").find("input.countPack").attr("value"); // значение кратно упаковкам

    if ( parseInt(countPack) > 1) { var countPackVal = parseInt(countPack); } else { var countPackVal = 1; }

	if (tip==1)	{
 	  var count_val_plus = parseInt(count_val) + countPackVal;
      repeatList=setTimeout('calculateList(1, elCount)',222);
      if (count_val_plus>0) $(elCount).attr("value", count_val_plus); else  $(elCount).attr("value", countPackVal);
    }
   else if (tip==2)  {
     var count_val_min = parseInt(count_val) - countPackVal;
      repeatList=setTimeout('calculateList(2, elCount)',222);
      if (count_val_min>countPackVal - 1) $(elCount).attr("value", count_val_min); else  $(elCount).attr("value", countPackVal);
     }
}


///////////////////////////////////////////////////////////
$(document).ready(function(){


$("input.countfrom").change( function() {
      selectedSum (this);
      packPrice (this);
});

  //   события для отправки формы
  $("div.checkTable :image, div.checkTable :submit").click(function(){

  var flagCh=0;
  $(this).parents("div.checkTable").find(":checkbox.action").each(function(){  	   if ( $(this).is(":checked") ) flagCh = 1;  });

  if (flagCh == 0) {  // если не выбраны чекбоксы  	alert(lang[11]);
  	return false;  }
  else {    var name_submit  = $(this).attr("name");
    switch (name_submit) {
      case 'addbasket':
         return true;
     break;
     case 'addfav':
         return true;
     break;
     case 'delline':
         return true;
     break;
     case 'delfav':
         if (confirm (lang[12]) ) return true;
         else return false;
     break;
   }
  }
 });






});


 /* -- favorites send ajax -- */

$(document).ready(function(){


 $("div.ItemFavBlock a").click(function(){
        var myHref = $(this).attr("href");
        var it = $(this).parent().parent();


        $.ajax({
           type: "POST",
           data: "myHref=" + myHref,
           cashe: false,
           url: "/ajax/add_fav.php",
           dataType: "json",
           beforeSend: function (){
              $("body").css({cursor:"wait"});
           },
           success: function(data, textStatus){
           	  addFavResult (data, it);
           },
           complete: function(data, textStatus){
              $("body").css({cursor:"auto"});
           }

         });

     });


});

  /* -- function added favorites -- */

function addFavResult (ResObj, it) {

 switch (ResObj.error) {
     case 0:

      $(it).after('<div style="position: absolute;"><div class="plateAjaxFav"><img src="/img/emp.gif" width="140" height="20" alt="" border="0"></div></div>');

      $(it).next().children().show("slow", function() {
      	 setTimeout(function() {
         $(it).next().children().hide("slow");
          }, 2000);
      	});
       $(it).children("span:first").hide();

       $(it).children("span:first").next().show('');

     break;
     case 1:
           document.location.replace("http://komus.ru/nocookies.php");
       break;
     case 3:
             alert('error =3 ');
       break;
       case 4:
             alert(lang[9]);
       break;
   }
}


/* +++++++++++++++++++++++++++++++++++  scroll menu ++++++++++++++++++++++++ */
/*function myScroll(elmy){

    if ($.browser.opera) {
      $('html,body').scrollTo(elmy, 1000);
    } else {
      var targetOffset = $(elmy).offset().top;
      $('html,body').animate({"scrollTop": targetOffset}, 1000);
    }

}   */

function myScrollH (targetOffset){   $('html,body').animate({"scrollTop": targetOffset}, 1000);
}

function screenHeight(){
  return $.browser.opera? window.innerHeight : $(window).height();
}

$(function(){

  $(".close-spry-menu").live("click", function(){    $("#MenuBar1").find("a.MenuBarItemSubmenuHover").removeClass("MenuBarItemSubmenuHover");
    $("#MenuBar1").find("ul.MenuBarSubmenuVisible").removeClass("MenuBarSubmenuVisible");
    return false;  });


  $("#MenuBar1").find(".menuscroll").hover(
  function(){  	var hei_scrW = $('html,body').scrollTop();  	var hei_browser = screenHeight();
  	var hei_el = $(this).height();
  	var y_el = $(this).offset().top;
  	var hei_sum = hei_el + y_el - hei_scrW;
  	var hei_target = hei_sum - hei_browser + 32 + hei_scrW;

   	/*alert(hei_browser + " " + hei_el + " " + y_el + " " + hei_sum);*/

    opentime2 = window.setTimeout(function(){
      if (hei_browser < hei_sum) {
        myScrollH(hei_target);
      }
    }, 200);
  }, function(){
    clearTimeout(opentime2);
  });


  $("#search-example").click(function(){  	 var txt_ex = $(this).text();
  	 $("#query_ac_main").attr("value", txt_ex);  });

});
