/* некоторые функции используют jQuery */

// каталог и добавление в корзину
var id_add = 0;
var xmlHttp = false;
if (!xmlHttp && typeof XMLHttpRequest != 'undefined') {
    xmlHttp = new XMLHttpRequest();
}
function add_cart(item_id) {
    // Создать URL для подключения
    var url = "/add_cart.php?id="+item_id;
    id_add = item_id;
    // Открыть соединение с сервером
    xmlHttp.open("POST", url, true);
    // Установить функцию для сервера, которая выполнится после его ответа
    xmlHttp.onreadystatechange = fill_cart;
    // SПередать запрос
    xmlHttp.send(null);
}
function fill_cart() {
    if (xmlHttp.readyState == 4) {
        var response = xmlHttp.responseText;
        document.getElementById("basket").innerHTML = response;
        if (id_add != 0) {
              alert("Товар добавлен.");
        }
    }
}


// корзина
// пересчёт
function ReLoadOrder(id) {
    // Создать URL для подключения
    var new_qnt = $(id).attr('value');
    if (new_qnt < 1) {
        alert ('Количество товара должно быть положительным');
    } else {
        var url = "/inc/cart.php?id="+$(id).attr('id').substring(4)+"&new_qnt="+new_qnt+'&'+Math.random();
        // Открыть соединение с сервером
        xmlHttp.open("GET", url, true);
        // Установить функцию для сервера, которая выполнится после его ответа
        xmlHttp.onreadystatechange = fill_order;
        // SПередать запрос
        xmlHttp.send(null);
    }
}
// очистка корзины
function cartClear() {
    // Создать URL для подключения
    var url = "/cart/clear";
    // Открыть соединение с сервером
    xmlHttp.open("POST", url, true);
    // Установить функцию для сервера, которая выполнится после его ответа
    xmlHttp.onreadystatechange = function () {
        window.location = window.location;
    };
    // SПередать запрос
    xmlHttp.send(null);
}
// удаление позиции из корзины
function cartRemove(id) {    
    $.post('/cart/' + id).success(function(){
        window.location = window.location;
    })
}

// вывод результата
function fill_order() {
    if (xmlHttp.readyState == 4) {
        var response = xmlHttp.responseText;
        document.getElementById("order").innerHTML = response;
        add_cart(0);
    }
}

// оформление заказа
	function On_Change_City()
	{
	  menuNum = document.getElementById("cityId").selectedIndex;
	  if (menuNum == 0) {
		document.getElementById("othercityblock").style.display = "none";
		document.getElementById("othercityblock").disabled = true;
		document.getElementById("formDomId").style.display = "none";

		document.getElementById("d1").disabled = false;
		document.getElementById("d2").disabled = false;
		document.getElementById("d3").disabled = false;
		document.getElementById("delivery_typeId").value = 0;

		document.getElementById("type_payId").value = 0;
		document.getElementById("p1").disabled = false;
	  }
	  if (menuNum == 1) {
		document.getElementById("othercityblock").style.display = "none";
		document.getElementById("othercityblock").disabled = true;
		document.getElementById("formDomId").style.display = "";

		document.getElementById("d1").disabled = false;
		document.getElementById("d2").disabled = false;
		document.getElementById("d3").disabled = true;
		document.getElementById("delivery_typeId").value = 0;

		document.getElementById("type_payId").value = 0;
		document.getElementById("p1").disabled = false;
	  }
	  if (menuNum == 2) {
		document.getElementById("othercityblock").style.display = "";
		document.getElementById("othercityblock").disabled = false;
		document.getElementById("formDomId").style.display = "none";

		document.getElementById("d1").disabled = true;
		document.getElementById("d2").disabled = true;
		document.getElementById("d3").disabled = false;
		document.getElementById("delivery_typeId").value = 0;

		document.getElementById("type_payId").value = 0;
		document.getElementById("p1").disabled = true;
	  }
	}
function OnChangeDelivery() {
	menuNum = document.getElementById("delivery_typeId").selectedIndex;
	if (menuNum == 1) {
		document.getElementById("delivery_blockId").style.display = "none";
	}
	else {
		document.getElementById("delivery_blockId").style.display = "";
	}
}

function checkForm() {
	  var FormCorrect = true;
	  ErrorStr = '';
	  if (document.getElementById("nameId").value == "") {
		 FormCorrect = false;
		 ErrorStr = '- ФИО\n';
	  }
	  if (!(/\d{3,}/.test(document.getElementById("phoneId").value))) {
		 FormCorrect = false;
		 ErrorStr = ErrorStr + '- Телефон\n';
	  }
	  if (!(/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(document.getElementById("mailId").value))) {
		FormCorrect = false;
		ErrorStr = ErrorStr + '- e-mail\n';
	  }
	  menuNumPay = document.getElementById("type_payId").selectedIndex;
	  if (menuNumPay == 0) {
		FormCorrect = false;
		ErrorStr = ErrorStr + '- Способ оплаты\n';
	  }
	  if ((menuNumPay == 2)&&(document.getElementById("pay_infoId").value == "")) {
		FormCorrect = false;
		ErrorStr = ErrorStr + '- Платежные реквизиты\n';
	  }
	  menuNumCity = document.getElementById("cityId").selectedIndex;
	menuNumDostavka = document.getElementById("delivery_typeId").selectedIndex;
	if (menuNumDostavka == 0) {
	  FormCorrect = false;
	  ErrorStr = ErrorStr + '- Способ доставки\n';
	}
		if (menuNumDostavka != 1) {
			if (menuNumCity == 0) {
				FormCorrect = false;
				ErrorStr = ErrorStr + '- Город доставки\n';
			}
		    if (document.getElementById("adressId").value == "") {
				FormCorrect = false;
				ErrorStr = ErrorStr + '- Адрес доставки\n';
			 }
			if ((menuNumCity == 2)&&(document.getElementById("othercityId").value == "")) {
				FormCorrect = false;
				ErrorStr = ErrorStr + '- Другой город\n';
			 }
		}
	if (FormCorrect == false)
	  {
	alert("При заполнении формы обнаружены ошибки!\nПроверьте правильность заполнения:\n"+ErrorStr);
	  }
	  return FormCorrect;
}
function ChangeTypePay() {
	menuNumPay = document.getElementById("type_payId").selectedIndex;
	if (menuNumPay == 2) {
		document.getElementById("pay_info_blockId").style.display = "";
	}
	else {
		document.getElementById("pay_info_blockId").style.display = "none";
	}
}

$(document).ready(function(){
    $('.smallphoto').click(function (event) {
        event.preventDefault();

        // запоминаем старое изображение
        var tmp_img = $('#photo1 img').attr('src');
        var tmp_href = $('#photo1').attr('href');

        // заменяем его новым
        $('#photo1 img').attr('src', $(this).attr('src'))
        $('#photo1').attr('href', $(this).parent().attr('href'));

        // вставляем в освободившееся место
        $(this).attr('src', tmp_img);
        $(this).parent().attr('href', tmp_href);
    });

    //setup before functions
    var typingTimer;                //timer identifier
    var doneTypingInterval = 1000;  //time in ms, 1 second for example

    //on keyup, start the countdown
    $("input[id^=qnt_]").live('keyup', function(){
        typingTimer = setTimeout(ReLoadOrder(this), doneTypingInterval);
    });

    //on keydown, clear the countdown
    $("input[id^=qnt_]").keydown('keydown', function(){
        clearTimeout(typingTimer);
    });

    // полноразмерные фотографии в галерее
    $('a[rel=lightbox]').lightBox({
        imageLoading:  '/images/lightbox/lightbox-ico-loading.gif',
        imageBtnClose: '/images/lightbox/lightbox-btn-close.gif',
        imageBtnPrev:  '/images/lightbox/lightbox-btn-prev.gif',
        imageBtnNext:  '/images/lightbox/lightbox-btn-next.gif',
        imageBlank:    '/images/lightbox/lightbox-blank.gif',
        txtImage:      'Фото',
        txtOf:         'из'
    });

    $('a.RemoveFromCart').live('click', function($event){
        $event.preventDefault();
        cartRemove($(this).attr('id'));
    });
});
