$(document).ready(function(){
    setPlusClick();
    setMinusClick();
    setClearOrder();
    setDiscountChange();
    calculate();
    setDeleteClick();
    setHighlite();    
    
    /*changeRestore();*/
    showRestoreLink();
    
    saveOrder();
    loadOrder();
    historyOrder();
    orderQuantityFocus();
    orderQuantityBlur();
    checkNumber();
});


function showRestoreLink(){
   $(".orderinvis").removeClass("orderinvis");
}

function saveOrder(){
   $("#savelink").click(function(){
       $.post(
            "/scripts/ajax/ajaxrecoveryorder.php",
            {
            recoveryaction: "save"
            },
            function(txt){
                 if (txt == "error") $(".recoveryfield").val("Ошибка сохранения: нет товаров");
                 else $(".recoveryfield").val(txt);
            }
       );

       return false;
   })
}

function loadOrder(){
   $("#restorelink").click(function(){
       var uniquecode = $(".recoveryfield").val();
       var currentcatid = $("#currentcatid").html();
       $.post(
            "/scripts/ajax/ajaxrecoveryorder.php",
            {
            recoveryaction: "load",
            uniquecode: uniquecode,
            callback_category: currentcatid
            },
            function(txt){
                 if (txt == "error1") {
                    $(".recoveryfield").val("Ошибка загрузки");
                    /*$("#ordergap").html("Передан пустой идентификатор");*/
                 }
                 else if (txt == "error2") {
                    $(".recoveryfield").val("Ошибка загрузки");
                    /*$("#ordergap").html("Неправильный идентификатор, или товаров нет в наличии");*/
                 }
                 else {
                    $(".order_one_item").remove();
                    $("#ordergap").html(txt);
                    calculate();
                    reMark();
                    
                    /*обновим обработчик количества товаров*/
                    rebindQuantity();
                 }
            }
       );

       return false;
   })
}

/*переотметить товары текущей директории если они есть в загруженой корзине*/
function reMark(){
   $(".one_item_id","#ordergap").each(function(){
        var item = $(this).html();
        $("#id"+item+" .item_name").addClass("marked");
   })
}


function historyOrder(){
   $("#historylink").click(function(){
       var uniquecode = $(".recoveryfield").val();
       $(this).attr("href","/orderhistory/" + uniquecode);
   })
}


/*поскольку еще не все так хорошо с поддержкой focus и blur при помощи live, обновим обработчики для количества товара*/
function rebindQuantity(){
    $(".order_quantity").unbind();
    checkNumber();
    orderQuantityBlur();
    orderQuantityFocus();
}


function in_array(needle, haystack) {	
  	var found = false, key;
  	for (key in haystack) {
  		if (haystack[key] == needle) {
  			found = true;
  			break;
  		}
  	}
  	return found;
}


/*фильтрция ввода, только цифры, backspace, tab, delete, стрелки влево, вправо*/
function checkNumber(){
    
    /*не позволять вводить недопустимые символы*/

    /* // версия с символами
    var c = String.fromCharCode(pressedkey);
    if (!/[0-9.%'`abcdefghi\b\t]/.test(c)) return false;
    */
    /* Opera не отрабатывает keydown поэтому используем также keypress, но уже с другими кодами символов*/
    
    $(".order_quantity").keydown(function(event){
         var pressedkey = (event.which) ? event.which : event.keyCode;
         if (!in_array(pressedkey,['8','9','37','39','46','48','49','50','51','52','53','54','55','56','57','96','97','98','99','100','101','102','103','104','105'])) return false;
    })

    $(".order_quantity").keypress(function(event){
         var pressedkey = (event.which) ? event.which : event.keyCode;
         if (!in_array(pressedkey,['8','9','37','39','46','48','49','50','51','52','53','54','55','56','57'])) return false;
    })    
       
    /*при отжатии клавиши (когда значение в поле уже изменено) сохранять значение*/
    $(".order_quantity").keyup(function(event){
         var pressedkey = (event.which) ? event.which : event.keyCode;
         if (!in_array(pressedkey,['8','9','37','39','46','48','49','50','51','52','53','54','55','56','57','96','97','98','99','100','101','102','103','104','105'])) return false;
         else{

             changePosition($(this));
             // если значение текущей строки не пустое, послать post запрос с установкой количества
             if($(this).val()){
                   var quantity = $(this).val();
                   var itemid = $(this).parent().parent().parent().siblings(".one_item_id").html();
                   $.post(
                        "/scripts/ajax/ajaxsetquantity.php",
                        {
                        quantity: quantity,
                        itemid: itemid
                        },
                        function(txt){
                            /* установить количество также в на поле товаров iquant*/
                            $(".iquant","#id"+itemid).text(quantity);
                        }
                   );
             };
         }
    })
}

/*изменить цену в строке, и общую сумму и цену*/
function changePosition(quantity_field){
    var quantity = quantity_field.val();
    /*var itemid = quantity_field.parent().parent().parent().siblings(".one_item_id").html();*/
    var price = quantity_field.data("savedprice");
    quantity_field.parent().parent().next().html(parseFloat(price*quantity).toFixed(2));
    calculate();
}

/*по выставлению фокуса на форму ввода высчитать базовую цену, сохраняем в свойствах объекта*/
function orderQuantityFocus(){
    $(".order_quantity").focus(function(){
         var quantity = $(this).val();
         var cur_price = $(this).parent().parent().next().html();
         $(this).data("savedprice",cur_price/quantity);
    })
}



/*по потере фокуса проверять на пустое значение и выставлять 1, сохраненную в свойствах цену удаляем*/
function orderQuantityBlur(){
    $(".order_quantity").blur(function(){
         if (!$(this).val()){
             $(this).val(1);
             $(this).parent().parent().next().html(parseFloat($(this).data("savedprice")).toFixed(2));
             $(this).removeData("savedprice");
             
             // послать post запрос с установкой количества в 1
             var quantity = 1;
             var itemid = $(this).parent().parent().parent().siblings(".one_item_id").html();
             $.post(
                  "/scripts/ajax/ajaxsetquantity.php",
                  {
                  quantity: quantity,
                  itemid: itemid
                  },
                  function(txt){
                      /* установить количество также в на поле товаров iquant*/
                      $(".iquant","#id"+itemid).text(quantity);                  
                      calculate();
                  }
             );

             
         }
    })
}



/*
function changeRestore(){
    $("#restorelinkblock a").click(function(){
         var showblock = $(this).attr("rel");
         var toggle = false;
         if ($(this).hasClass("selectedlink")) {
             $("#restorelinkblock a").removeClass("selectedlink");
             toggle = true;
         }
         else {
             $("#restorelinkblock a").removeClass("selectedlink");
             $(this).addClass("selectedlink");
         }
             
         $("#saveorder, #loadorder, #orderhistory").addClass("orderinvis");
         if (!toggle){
             $("#" + showblock).removeClass("orderinvis");
         }

         return false;
    });
}
*/


function setHighlite(){
    $(".one_item").hover(
    	      function () {
    	        $(this).children("td:eq(1), td:eq(3)").addClass("tmpmarked");
    	      }, 
    	      function () {
    	    	  $(this).children("td:eq(1), td:eq(3)").removeClass("tmpmarked");
    	      }
    );
	
}

function setPlusClick(){
    $(".plus").click(function(){
       var cur_discount = parseInt($("#currentdiscount").text());      /*получаем значение текущей ссылки*/
    
       /*var item = $(this).parent().parent().attr("id"); */               /*получаем id товара*/
       var item = $(this).parent().siblings("td:first").children("span").text();   /*получаем id товара*/
       var itemname = $("#id"+item+" .item_name").addClass("marked").text();   /*добавляем товар в выбранные*/
       
       var q = $(this).siblings(".iquant");    /*находим количество товара*/
       if (q.text()==="") q.text("1");
       else q.text(parseInt(q.text())+1);

       var price = $(this).parent().siblings(".itemprice");    /*узнаем цену*/
       var discountprice = price.text();  /*текущая цена со скидкой, или просто текущая цена в случае фиксированной цены*/
       /*var baseprice = price.text();*/

       /*Узнаем фиксированна ли цена*/
       if (price.hasClass("fixedprice")) var fixedpriceclass = " fixedprice";
       else var fixedpriceclass = "";       
       
       /* ситуация когда цена равна 0 или строке */
       if (isNaN(discountprice)) discountprice = 0;
              
       /* Если цена фиксированна, то базовую цену берем без манипуляций со скидкой*/
       if (price.hasClass("fixedprice"))  var baseprice = discountprice;
       else var baseprice = parseFloat((100*discountprice)/(100-cur_discount)).toFixed(2); /*базовая цена (без скидки)*/
 			 
       var newprice = parseFloat(discountprice * q.text()).toFixed(2); /*цена за все количество товаров с учетом скидки*/

       var hasdecsr = 0;
       if ($("#id"+item+" .item_name a").length) hasdecsr = 1;
       
       var in_order = $("#orderlist").contents().find(".order_item_name[id=oid" + item + "]");
       if (in_order.length) {
            in_order.siblings(".quantandprice").contents().find(".order_quantity").val(q.text());
            in_order.siblings(".quantandprice").children(".order_itemprice").text(newprice);
       }
       else{
            if (!$(".order_one_item").length) $("#ordergap").html("");
            var cntitem = $(".order_one_item").length + 1;
            var additem = "<div class='order_one_item'>";
                additem += "   <span style='display:none' class='one_item_id'>" + item + "</span>";
                additem += "   <div class='order_number'>" + cntitem + ".</div>";
                additem += "   <div class='quantandprice'>";
                additem += "        <div class='orderdelete'><img src='/images/orderdelete.png' class='orderdeleteimg'></div>";
                additem += "        <div class='order_iquant'>";
                additem += "           <form name='quantityform' class='order_quantityform' action=''>";
                additem += "           <input type='text' name='quantity' class='order_quantity' value='" + q.text() + "'>";
                additem += "           </form>";
                additem += "        </div>";
                additem += "        <div class='order_itemprice" + fixedpriceclass +"'>" + newprice + "</div>";
                additem += "   </div>";
                additem += "   <div class='order_item_name' id='oid" + item + "'>";
                if (hasdecsr) additem +=  "<a href='/catalog/itemshow/" + item + "' target='_blank'>" + itemname + "</a><br>";
                else additem += itemname + "<br>";
                additem +=    "</div>";
                additem += "</div>";
            /*alert(additem);*/
            $("#ordergap").append(additem);
            /*обновим обработчик количества товаров*/
            rebindQuantity();
       }
       
       calculate();


       $.post(
            "/scripts/ajax/ajaxorder.php",
            {
            item: item,                      /*можно было бы посылать id и количество и делать выборку из базы, но из сессий быстрее */
            quantity: q.text(),
            itemname: itemname,
            baseprice: baseprice,
            hasdecsr: hasdecsr
            },
            function(txt){
                 return false;
            }
       );

       return false;
       
    });
} 

function setMinusClick(){
    $(".minus").click(function(){
       var cur_discount = parseInt($("#currentdiscount").text());
       
       /*
       var item = $(this).parent().parent().attr("id");
       */
       var item = $(this).parent().siblings("td:first").children("span").text();     /*получаем id товара*/
       
       var q = $(this).siblings(".iquant");
       var price = $(this).parent().siblings(".itemprice").text();
       /*var baseprice = price.text();*/
       
       /* ситуация когда цена равна 0 */
       if (isNaN(price)) price = 0;       
       
       if (!parseInt(q.text()) || parseInt(q.text())==1){
           $("#id"+item+" .item_name").removeClass("marked");
           q.text("");
           var newprice = parseFloat(price).toFixed(2);
       }
       else {
           q.text(parseInt(q.text())-1);
           var newprice = parseFloat(price * q.text()).toFixed(2);
       }

       var in_order = $("#orderlist").contents().find(".order_item_name[id=oid" + item + "]");
       if (in_order.length) {
            if (q.text()=="") in_order.parent().remove();
            else{
                in_order.siblings(".quantandprice").contents().find(".order_quantity").val(q.text());
                in_order.siblings(".quantandprice").children(".order_itemprice").text(newprice);
            }
            
       }
       
       reorder();
       calculate();

       $.post(
         "/scripts/ajax/ajaxunorder.php",
         {
         item: item,
         quantity: q.text()
         },
         function(txt){
             return false;
         }
       );
       
       return false;
              
    });
}

function setDiscountChange(){
    $("#discountval").change(function(){
        var discount = $("#discountval").val();
        var cur_discount = parseInt($("#currentdiscount").text());
        $.post(
          "/scripts/ajax/ajaxsetdiscount.php",
          {
          discount: discount
          },
          function(txt){
          	 var get_discount = 0;
          	 if (txt) get_discount = txt;
          	 $(".itemprice").each(function(){
          	     if ($(this).hasClass("fixedprice")) return;          	 
            	   var cur_price = $(this).text();
             		 var new_price = $(this).text(parseFloat((100-get_discount)*cur_price/(100-cur_discount)).toFixed(2));
          	 });

          	 $(".order_itemprice").each(function(){
          	     if ($(this).hasClass("fixedprice")) return;
            	   var cur_price = $(this).text();
             		 var new_price = $(this).text(parseFloat((100-get_discount)*cur_price/(100-cur_discount)).toFixed(2));
             });
             
             $("#currentdiscount").text(get_discount);

             calculate();
        	 
          }
        );
      
     });
	
}

function setClearOrder(){
    $("#clearorder a").click(function(){
       $("#ordergap").html("Нет товаров в заказе");
       $.post(
         "/scripts/ajax/ajaxclearorder.php",
         {
         
         },
         function(txt){
            $(".marked").removeClass("marked");
            $(".iquant").text("");
           
            calculate();
            return false;
         }
       );
       return false;
    });
}

function setDeleteClick(){
    $(".orderdelete").live("click",function(){
       var item = $(this).parent().siblings("span").text();
       var removeitem = $(this).parent().parent();
       $.post(
         "/scripts/ajax/ajaxremoveitem.php",
         {
         item: item
         },
         function(txt){
            $(removeitem).remove();
            $("#id"+item+" .item_name").removeClass("marked");
            $("#id"+item+" .plusminus .iquant").text("");
            reorder();
            calculate();
            return false;
         }
       );
       return false;
    });
}


function reorder(){
    var i=1;
    if ($(".order_number").length){
        $(".order_number").each(function(){
             $(this).text(i++ +".");
        });
    }
    else $("#ordergap").html("Нет товаров в заказе");
}


function calculate(){
  	var summ = 0;
      var allquan = 0;
      $(".order_itemprice").each(function(){
            if ($(this).text()!==""){
                summ = summ + parseFloat($(this).text());
            }
      });
      $(".order_quantity").each(function(){
            if ($(this).val()!==""){
                allquan = allquan + parseInt($(this).val());
            }
      });
      $("#posnumber").text(allquan + " ");
      $("#summ").text(summ.toFixed(2) + " ");
}

