
//function devUpdate()
//{
//  var devPrice = document.getElementById("deliveryPrice");
//  if (devPrice != null)
//  {
//    devPrice.innerHTML = "";
//    document.getElementById("totalPrice").innerHTML = "";
//  }
//}

function setCookie (name, value, exdays) {
  var exdate=new Date();
  exdate.setDate(exdate.getDate() + exdays);
  var  expires = exdate.toUTCString();
  document.cookie = name + "=" + escape(value) + "; expires=" + expires;
}

function getCookie(name) {
	var cookie = " " + document.cookie;
	var search = " " + name + "=";
	var setStr = null;
	var offset = 0;
	var end = 0;
	if (cookie.length > 0) {
		offset = cookie.indexOf(search);
		if (offset != -1) {
			offset += search.length;
			end = cookie.indexOf(";", offset);
			if (end == -1) {
				end = cookie.length;
			}
			setStr = unescape(cookie.substring(offset, end));
		}
	}
	return(setStr);
}






BasketStatusManager = {
  callbacks: [],

  addUpdateCallback: function (cb)
  {
    this.callbacks = this.callbacks.concat(cb);
  },

  fireUpdateCallbacks: function (status)
  {
    for (var i = 0; i < this.callbacks.length; ++i) {
      var cb = this.callbacks[i];
      cb.call(null, status);
    }
  }
};

function updateBasketStatus()
{
  BasketAction.getBasketStatus(
     function (provider, response) {
      if (!("exception" in response)){
        var status = response.result;
        BasketStatusManager.fireUpdateCallbacks(status);
      } else {
        alert("EXCEPTION"); // exception handling
      }
     });
}























BasketStatusManager.addUpdateCallback(function (status) {

  if (0 == status.count)
  {
    $("#basket_deliveryDiv").hide();
    document.getElementById('basket_statusKol').innerHTML = "Ваша корзина пуста";
    document.getElementById('basket_statusSum').innerHTML = "";
  } else {
    $("#basket_deliveryDiv").show();
    if (null != document.getElementById("sendOrder")){$("#basket_deliveryDiv").hide();}
    document.getElementById('basket_statusKol').innerHTML = "Количество товара в корзине: " + status.count.toString();
    var sumR = status.sum / 100;
    var sumK = status.sum % 100;
    document.getElementById('basket_statusSum').innerHTML = "На сумму: " + sumR.toString() + " руб " + sumK.toString() + " коп" ;
    document.getElementById('inputCount').value = status.count;
    document.getElementById('inputSum').value = status.sum;
    document.getElementById('inputWeight').value = status.weightSum;
    getDeliveryPrice();
  }
  if(document.getElementById('basketSum') != null)
  {
    document.getElementById('basketSum').innerHTML = sumR.toString()+'.'+sumK.toString()+ '&nbsp;';
    document.getElementById('basketWeightSum').innerHTML = status.weightSum.toString();
    document.getElementById('basketCount').innerHTML = status.count.toString();
    document.getElementById('price').value = status.sum;
  }
//  if(document.getElementById('deliveryMod') != null){getDeliveryPrice();}
});

function changeCityIOnIndex()
{
  var selOnIndex = document.getElementById("basket_deliveryCity");
  var selIdS = getCookie("selIdS");
  if (null == selIdS || 0 != selOnIndex.selectedIndex)
  {
    setCookie("selIdS",selOnIndex.selectedIndex,7);
    setCookie('city',selOnIndex.options[selOnIndex.selectedIndex].text,7);
  }
//  {
//    if (0 != selOnIndex.selectedIndex)
//    {
//      setCookie("selIdS",selOnIndex.selectedIndex,7);
//    }
    selIdS = getCookie("selIdS");
    var cityId = selOnIndex.options[selIdS].value;
    document.getElementById('inputCity').value = cityId;
    setCookie('cityId',cityId,7);

    selIdS = getCookie("selIdS");
    selOnIndex.options[selIdS].selected = true;
    if (null != document.getElementById("deliveryCity"))
      {
        var selOnBasket = document.getElementById("deliveryCity");
        selOnBasket.options[selIdS].selected = true;
      }
//    alert(document.getElementById('inputCity').value);
//  }
}

function changeCityIOnBasket()
{
  var selOnIndex = document.getElementById("basket_deliveryCity");
  var selOnBasket = document.getElementById("deliveryCity");
  var selIdS = getCookie("selIdS");
  if (null == selIdS || 0 != selOnBasket.selectedIndex)
  {
    setCookie("selIdS", selOnBasket.selectedIndex, 7);
    setCookie('city',selOnBasket.options[selOnBasket.selectedIndex].text,7);
  }
    selIdS = getCookie("selIdS");
    var cityId = selOnBasket.options[selIdS].value;
    document.getElementById("inputCity").value = cityId;
    setCookie("cityId", cityId, 7);
    //setCookie('city',selOnBasket.options[selOnBasket.selectedIndex].text,7);
    selOnIndex.options[selIdS].selected = true;
    selOnBasket.options[selIdS].selected = true;
//    alert(document.getElementById('inputCity').value);

}

function getDeliveryPrice()
{
  if (null != document.getElementById("deliveryCity"))
   {changeCityIOnBasket();}
   else{changeCityIOnIndex();}
  var cityId = document.getElementById("inputCity").value;
  var weight = document.getElementById("inputWeight").value;

  if (0 == cityId)
  {
    document.getElementById("basket_deliveryPrice").innerHTML = "Стоимость доставки: выберите город";
    if (null != document.getElementById("deliveryCity"))
    {
      document.getElementById("deliveryPrice").innerHTML = "выберите город";
    }
  }
  else
  {
//    if (cityId == 200)
//    {
//      document.getElementById("basket_deliveryPrice").innerHTML = "Стоимость доставки: н/д";
//      document.getElementById("deliveryPrice").innerHTML = "н/д";
//      document.getElementById("totalPrice").innerHTML = "н/д";
//
//      BasketAction.getDeliveryPriceRF(
//      parseInt(cityId), parseInt(weight),
//     function (provider, response) {
//      if (!("exception" in response)){
//        var price = response.result;
//        var rub = price / 100;
//        document.getElementById("basket_deliveryPrice").innerHTML = "Стоимость доставки: " + rub +" руб ";
//        if (null != document.getElementById("deliveryCity"))
//        {
//          document.getElementById("deliveryPrice").innerHTML = rub +" руб ";
//          document.getElementById("dP").value = price;
//
//          var totalPrice = price + sum;
//
//          document.getElementById("totalPrice").innerHTML = (totalPrice / 100).toString() +" руб ";
//          document.getElementById("fullPrice").value = totalPrice;
//        }
//      } else {
//        alert("Ошибка"); // exception handling
//      }
//     });
//
//
//
////      document.getElementById("fullPrice").value = "н/д";
//
//    } else {

    BasketAction.getDeliveryPriceRF(
      parseInt(cityId), parseInt(weight),
     function (provider, response) {
      if (!("exception" in response)){
        var deliveryprice = response.result;
        var rub = deliveryprice / 100;

        if (200 == cityId)
        {
            document.getElementById("basket_deliveryPrice").innerHTML = "Стоимость доставки: нет данных";
        }else
        {document.getElementById("basket_deliveryPrice").innerHTML = "Стоимость доставки: " + rub +" руб ";}


        if (null != document.getElementById("deliveryCity"))

         {

          if (200 == cityId)
          {

            document.getElementById("deliveryPrice").innerHTML = " нет данных";
            document.getElementById("dP").value = deliveryprice;
            document.getElementById("totalPrice").innerHTML =" нет данных";
            document.getElementById("fullPrice").value = parseInt(document.getElementById("price").value);
          } else {

            document.getElementById("deliveryPrice").innerHTML = rub +" руб ";
            document.getElementById("dP").value = deliveryprice;

            var sum = parseInt(document.getElementById("price").value);
            var totalPrice = deliveryprice + sum;

            document.getElementById("totalPrice").innerHTML = (totalPrice / 100).toString() +" руб ";
            document.getElementById("fullPrice").value = totalPrice;
          }
        }
      } else {
        alert("Ошибка"); // exception handling
      }
     });
  }
}

function inBasket(id)
{
    BasketAction.inBasket(
      id,
      function (provider, response) {
        if (!("exception" in response)){
          if (Ext.util.JSON.encode(response.result)){alert("*")}
        } else {
          alert("EXCEPTION"); // exception handling
        }
      });
}

function isblanс(elem)
{
  for(var i = 0; i < elem.length; i++) {
    var charElem = elem.charAt(i);
    if ((charElem != ' ') && (charElem != '\n') && (charElem != '')) return false;
  }
  return true;
}

function isValidEmail (email)
{
 return (/^([a-z0-9_\-]+\.)*[a-z0-9_\-]+@([a-z0-9][a-z0-9\-]*[a-z0-9]\.)+[a-z]{2,4}$/i).test(email);
}

function sendOrder()
{

  var return_value = true;
  var error_msg_notBlanc = "Следующие поля не должны быть пустыми: \n";

  var signupOrder = Ext.query(".signupOrder");
  for (var i = 0; i < signupOrder.length; ++i){
    var element = Ext.get(signupOrder[i]);
    if (isblanс(element.getAttribute("value"))){error_msg_notBlanc += element.getAttribute("name")+"\n"; return_value=false}
  }

  if(!return_value){
    alert(error_msg_notBlanc)
  } else {
    var email = document.getElementById("email").value;
    if (isValidEmail(email)){
      var fn = document.getElementById("fn").value;
      var sn = document.getElementById("sn").value;
      var mn = document.getElementById("mn").value;
      // var email = document.getElementById("email").value;
      var phone = document.getElementById("phone").value;
      var recomendNumber = document.getElementById("recomendNumber").value;
      var zipcode = document.getElementById("zipcode").value;
      var country = document.getElementById("country").value;
      //var region = document.getElementById("region").value;
      var city = document.getElementById("city").value;
      var street = document.getElementById("street").value;
       var house = document.getElementById("house").value;
      var аpartment = document.getElementById("аpartment").value;
      var deliveryPrice = document.getElementById("inputDelP").value;
      var rub = deliveryPrice / 100;
      var kop = deliveryPrice % 100;
      var totalPrice = document.getElementById("inputTotalP").value;
      var content ="";
      content += "Заказчик: " + sn.toString() + " " + fn.toString() + " " + mn.toString() + "\n\n";
      content += "Адрес доставки: \n";
      content += "Индекс: "+ zipcode.toString() + "\n";
      content += "Страна: "+ country.toString() + "\n";
//      content += "Регион: "+ region.toString() + "\n";
      content += "Город: "+ city.toString() + "\n";
      content += "Улица: "+ street.toString() + "\n";
      content += "Дом: "+ house.toString() + "\n";
      content += "Квартира: "+ аpartment.toString() + "\n\n";
      content += "Контактная информация:\n";
      content += "Телефон "+ phone.toString() + "\n";
      content += "email "+ email.toString() + "\n\n";
      content += "Номер лицевого счёта рекомендателя: " + recomendNumber.toString() + "\n\n";
      if (200 == getCookie('cityId')){
      content += "Cтоимость доставки в выбранный город: нет данных \n";
      content += "Стоимость заказа без учёта доставки: " +  (totalPrice / 100).toString() +" руб " + "\n";
      } else
      {
      content += "Cтоимость доставки в выбранный город: " +  rub.toString() +" руб " + "\n";
      content += "Стоимость заказа с учётом доставки: " +  (totalPrice / 100).toString() +" руб " + "\n";
      }
       BasketAction.sendOrder(
           content, email.toString(),
       function (provider, response) {
         if (!("exception" in response)){
           var status = response.result;
           alert("Заказ отправлен");
           location.href="?page=basketPreview";
         } else {
           alert("При отпавке заказа произошла непредвиденная ошибка. Проверьте, правильно ли вы указали свой e-mail."); // exception handling
         }
       });
    } else { alert("Введите корректный e-mail") }
  }
}

function updateCount(x){
  var elName = "prodCount"+x;
  alert(document.getElementsByName(elName).value);
}

Ext.onReady(function() {

//  changeCityIOnIndex();
//  devUpdate();
  Ext.Direct.addProvider(
      new Ext.direct.RemotingProvider(
          ShopRouterDescription));

  updateBasketStatus();
  var addArray = Ext.query(".basketAddGroup");
  for (var i = 0; i < addArray.length; ++i) {
    var groupEl = Ext.get(addArray[i]);
    var btn = groupEl.child(".addButton");

    btn.on('click', function(){
      var data = {
        javaClass : 'eshop.BasketItem',
        id : parseInt(this.child(".prodId").getAttribute("value")),
        name : this.child(".prodName").getAttribute("value"),
        count : parseInt(this.child(".prodCount").getAttribute("value")),
        price : parseInt(this.child(".prodPrice").getAttribute("value")),
        weight : parseInt(this.child(".prodWeight").getAttribute("value"))
      };

      BasketAction.secondAdd(
          data,
          function (provider, response) {
            if (!("exception" in response)){
             // alert(Ext.util.JSON.encode(response.result));
              updateBasketStatus();
            } else {
              alert("EXCEPTION"); // exception handling
            }
          });
    }, groupEl);
  }


});


function buttonToSend()
{
  var deliveryPrice = document.getElementById("dP").value;
  var totalPrice = document.getElementById("fullPrice").value;
  setCookie("delivery",deliveryPrice,1);
  setCookie("total",totalPrice,1);
  location.href="?page=basketForSend"
}

function toFromD(idButton)
{
  var return_value = true;
  var error_msg_notBlanc = "Следующие поля не должны быть пустыми: \n";
  var signupOrder = Ext.query(".signupOrder");
  for (var i = 0; i < signupOrder.length; ++i){
    var element = Ext.get(signupOrder[i]);
    if (isblanс(element.getAttribute("value"))){error_msg_notBlanc += element.getAttribute("name")+"\n"; return_value=false}
  }

  if(!return_value){
    alert(error_msg_notBlanc)
  } else {
    var email = document.getElementById("emailD").value;
    if (isValidEmail(email)){
      var fn = document.getElementById("fnD").value;
      var sn = document.getElementById("snD").value;
      var mn = document.getElementById("mnD").value;
      var city = document.getElementById("cityD").value;
      var phone = document.getElementById("phoneD").value;
      var regNum = document.getElementById("regNumberD").value;
      var fnRecom = document.getElementById("fnrecomenderD").value;
      var snRecom = document.getElementById("snrecomenderD").value;
      var lsRecom = document.getElementById("LSrecomenderD").value;
      var bd = document.getElementById("bd").value;
      var pl = document.getElementById("programLevel").value;

      var content = "";
      content += "Фамилия: "+ fn.toString() + "\n ";
      content += "Имя: " + sn.toString() + "\n ";
      content += "Отчество: " + mn.toString() + "\n ";
      content += "Дата рождения: " + bd.toString() + "\n ";
      content += "Город: " + city.toString() + "\n ";
      content += "Телефон: " + phone.toString() + "\n ";
      content += "email: " + email.toString() + "\n ";
      content += "Лицевой счет: " + regNum.toString() + "\n\n";
      content += "Рекомендатель:" + "\n ";
      content += "Фамилия: "+ fnRecom.toString() + "\n ";
      content += "Имя: " + snRecom.toString() + "\n ";
      content += "Лицевой счет: " + lsRecom.toString() + "\n\n";
      content += "Программа: " + pl.toString() + "\n\n";


      BasketAction.sendMail(
          parseInt(idButton), content.toString(), email.toString(),
          function (provider, response) {
            if (!("exception" in response)){
              alert("Заявка на изменение статуса рассылки отправлена");
            } else {
              alert("При отпавке заявки произошла непредвиденная ошибка. Пожалуйста, повторите попытку позже."); // exception handling
         }
          });
    } else { alert("Введите корректный e-mail") }
  }
}


