var payForm_detectedCountry = '';
var payForm_detectedCity	= '';
var all_ta = false;

$(document).ready(function() {
    $("input[name='personType']").change(function(){
        val = $("input[name='personType']:checked").val();
        if (val == 'physical')
            $('#jurid').hide('slow');
        else
            $('#jurid').show('slow');
    });
});

function strToInt(s)
{
    return isNaN(v = parseInt(s)) ? 0 : v;
}

function strToFloat(s)
{
    return isNaN(v = parseFloat(s)) ? 0 : v;
}

function getAllTA()
{
    var i = 1;
    while(true)
    {
        var curr = document.getElementById("type[" + i.toString() + "]");
		
        if (curr == null)
            break;
			
        if (!(curr.value == "A" || curr.value == "C"))
            return false;
			
        i++;
    }
	
    return true;
}

function setDeliveryDefaults(detectedCountry, detectedCity)
{
    all_ta = getAllTA();
	
    payForm_detectedCountry = detectedCountry;
    payForm_detectedCity	= detectedCity;
	
    var countryList = document.getElementById("country");
    var regionList = document.getElementById("region");
	
    if (countryList != null && regionList != null)
    {
        var detectedCountryIndex = getCountryIndex(payForm_detectedCountry);
        var detectedAddressIndex = getRegionIndex(payForm_detectedCity);
		
        countryList.selectedIndex 	= detectedCountryIndex;
        regionList.selectedIndex 	= detectedAddressIndex;
		
        updateRegion();
    }
}

// Меняет адрес доставки
function updateRegion()
{
    var countryList 		= document.getElementById("country");
    var regionList 			= document.getElementById("region");
	
    var detectedCountryIndex = getCountryIndex(payForm_detectedCountry);
    var detectedAddressIndex = getRegionIndex(payForm_detectedCity);
    var otherCityIndex 		 = getRegionIndex("Иной город (цену сообщит менеджер)");
	
    // Проставляем определенный регион доставки, если выбрали определенную страну
    if (countryList.selectedIndex == detectedCountryIndex && detectedAddressIndex >= 0)
        regionList.selectedIndex = detectedAddressIndex;
	
    if (countryList.options[countryList.selectedIndex].text == "Россия")
        regionList.disabled = false;
    else
    {
        regionList.selectedIndex = otherCityIndex;
        regionList.disabled = true;
    }
	
    updateDeliveryKind(); // Способ доставки зависит от региона доставки
}

// Меняет способ доставки
function updateDeliveryKind()
{
    var countryList  	 	= document.getElementById("country");
    var regionList 			= document.getElementById("region");
    var region 				= regionList.options[regionList.selectedIndex].text;
    var deliveryKindList 	= document.getElementById("deliveryKind");

    switch(region)
    {
        case "Москва":
            deliveryKindList.length = 2;
            deliveryKindList.options[0] = new Option("Курьером по Москве", "mkad", true, true);
            deliveryKindList.options[1] = new Option("Самовывоз со склада в Москве", "person");
            deliveryKindList.selectedIndex = 0;
            break;
        case "Московская область":
            deliveryKindList.length = 2;
            deliveryKindList.options[0] = new Option("Экспресс ЕМС", "ems", true, true);
            deliveryKindList.options[1] = new Option("Самовывоз со склада в Москве (зарезервировать товар)", "person");
            deliveryKindList.selectedIndex = 0;
            break;
        case "Санкт-Петербург":
            deliveryKindList.length = 2;
            deliveryKindList.options[0] = new Option("Курьером по Санкт-Петербургу", "spb", true, true);
            deliveryKindList.options[1] = new Option("Самовывоз со склада в Санкт-Петербурге (зарезервировать товар)", "person");
            deliveryKindList.selectedIndex = 0;
            break;
        default:
           if (countryList.options[countryList.selectedIndex].text == "Россия")
           {
               deliveryKindList.length = 4;
               deliveryKindList.options[0] = new Option("Экспресс ЕМС", "ems", true, true);
               deliveryKindList.options[1] = new Option("Первым классом почтой (до 2 кг)", "post");
               deliveryKindList.options[2] = new Option("Самовывоз со склада в Москве (зарезервировать товар)", "person");
               deliveryKindList.options[3] = new Option("Транспортной компанией", "tcomp");
           }
           else
           {
               deliveryKindList.length = 1;
               deliveryKindList.options[0] = new Option("Экспресс ЕМС", "ems", true, true);
               deliveryKindList.selectedIndex = 0;
           }
           break;
    }
	
    updatePayKind(); // От способа доставки зависит способ оплаты
}

// Меняет способ оплаты
function updatePayKind()
{
    var countryList  	 	= document.getElementById("country");
    var regionList 			= document.getElementById("region");
    var deliveryKindList 	= document.getElementById("deliveryKind");
    var deliveryKind 		= deliveryKindList.value;
    var payKindList		 	= document.getElementById("payKind");
	
    switch(deliveryKind)
    {
        case "mkad":
        case "spb":
            payKindList.length = 2;
            payKindList.options[0] = new Option("Оплата курьеру", "PayCash");
            payKindList.options[1] = new Option("Оплата через банк", "PayBank", true, true);
            payKindList.selectedIndex = 1;
            break;
				
        case "person":
            var region = regionList.options[regionList.selectedIndex].text;
				
            if (region == "Москва" ||
                region == "Московская область" ||
                region == "Санкт-Петербург")
                {
                payKindList.length = 2;
                payKindList.options[0] = new Option("Оплата наличными при получении товара", "PayCashRezerv");
                payKindList.options[1] = new Option("Оплата через банк", "PayBank", true, true);
                payKindList.selectedIndex = 1;
            }
            else
            {
                payKindList.length = 1;
                payKindList.options[0] = new Option("Оплата наличными при получении товара", "PayCashRezerv", true, true);
                payKindList.selectedIndex = 0;
            }
            break;
				
        case "ems":
            if (countryList.options[countryList.selectedIndex].text == "Россия")
            {
                payKindList.length = 2;
                payKindList.options[0] = new Option("Оплата наложенным платежом", "PayPost");
                payKindList.options[1] = new Option("Оплата через банк", "PayBank", true, true);
                payKindList.selectedIndex = 1;
            }
            else
            {
                payKindList.length = 1;
                payKindList.options[0] = new Option("Электронные системы перевода", "ECommerce", true, true);
                payKindList.selectedIndex = 0;
            }
            break;
				
        case "post":
            payKindList.length = 2;
            payKindList.options[0] = new Option("Оплата наложенным платежом (до 5 т.р.)", "PayPost");
            payKindList.options[1] = new Option("Оплата через банк", "PayBank", true, true);
            payKindList.selectedIndex = 1;
            break;
				
        case "tcomp":
            payKindList.length = 1;
            payKindList.options[0] = new Option("Оплата через банк", "PayBank", true, true);
            payKindList.selectedIndex = 0;
            break;
    }
	
    updatePrice();
}

function goodsInfo()
{
    this.weight = 0;
    this.cost = 0;
    this.deliveryAction = false;
	
    var i = 1;
    while(true)
    {
        var currWeight = document.getElementById("weight[" + i.toString() + "]");
        var currPrice = document.getElementById("price" + i.toString());
        var currDeliveryAction = document.getElementById("deliveryAction[" + i.toString() + "]");
		
        if (currWeight == null || currPrice == null || currDeliveryAction == null)
            break;
        else
        {
            var currCount = strToInt(document.getElementById("cartcnt[" + i.toString() + "]").value);
            if (currCount > 0)
            {
                this.weight += strToFloat(currWeight.value) * currCount;
                this.cost += strToFloat(currPrice.innerHTML) * currCount;
				
                if (currCount >= currDeliveryAction.value)
                    this.deliveryAction = true;
            }
        }
        i++;
    }
}

function getRequestUri(goodsCost, goodsWeight)
{
    var country			= document.getElementById("country").value.replace(/=/g, '%3D').replace(/&/g, '%26');
    var region 			= document.getElementById("region").value.replace(/=/g, '%3D').replace(/&/g, '%26');
    var deliveryKind 	= document.getElementById("deliveryKind").value;
    var payKind			= document.getElementById("payKind").value;

    if(country == '0')
        reqString = "getData=true&country=" + country + "&region=" + region +
        "&payKind=" + payKind + "&deliveryKind=" + deliveryKind + "&weight=" + goodsWeight +
        "&goodsCost=" + goodsCost;
    else
        reqString = "getData=true&country=" + country + "&payKind=" + payKind +
        "&deliveryKind=" + deliveryKind + "&weight=" + goodsWeight + "&goodsCost=" + goodsCost;

    return 'getCostDost/request.php?' + reqString;
}

var _payForm_updateCounter = 0; // Счетчик обновлений. Начало обновления +1 , Конец обновления -1

function beginLoad()
{
    if (_payForm_updateCounter == 0)
    {
        $("#orderTableResults").hide("slow");
        $("#orderTableResultsLoader").show("slow");
    }
    _payForm_updateCounter++;
}

function endLoad()
{
    _payForm_updateCounter--;
							
    if (_payForm_updateCounter == 0)
    {
        $("#orderTableResultsLoader").hide("slow");
        $("#orderTableResults").show("slow");
    }
}

function updateVisibility()
{
    var regionList = document.getElementById("region");
    var payKindList	= document.getElementById("payKind");
    var reg		  = /city/;
	
    if (regionList == null || payKindList == null)
        return;
	
    // Показываем поле "Населенный пункт", если не указан город
    if (regionList.value == '0' || reg.test(regionList.value) == false)
        $("#settlementGroup").show("slow");
    else
        $("#settlementGroup").hide("slow");
	
    // Показываем поле "Индекс", если город - не Москва
    if (regionList.options[regionList.selectedIndex].text != 'Москва')
        $("#indexGroup").show("slow");
    else
        $("#indexGroup").hide("slow");
}

function updatePrice()
{
    var deliveryKindList = document.getElementById("deliveryKind");
    var regionList = document.getElementById("region");
    var payKindList	= document.getElementById("payKind");
	
    if (deliveryKindList == null || regionList == null || payKindList == null)
        return;
		
    var ginfo = new goodsInfo();
	
    var goodsCost = ginfo.cost;
    var weight	  = ginfo.weight;
    var deliveryAction = ginfo.deliveryAction;
		
    // Предварительная проверка
    switch(deliveryKindList.value)
    {
        case "post":
            if (weight > 2) // Вес больше 2кг
            {
                window.alert("При отправке Первым Классом вес посылки не может превышать 2кг");
                deliveryKindList.selectedIndex = 0; // Выставляем EMS
            }
            if (payKindList.value == "PayPost" && goodsCost > 5000)
            {
                window.alert("При отправке Первым Классом и оплате наложенным платежом стоимость вложений не может превышать 5000 рублей");
                payKindList.selectedIndex = 1; // Выбираем Банковский перевод
            }
            break;
    }
	
    updateVisibility();
		
    if (goodsCost > 0 && weight > 0)
    {
        beginLoad();
	
        var orderNote 	 	= document.getElementById("orderNote");
        var deliveryKind 	= document.getElementById("deliveryKind").value;

        requestUri = getRequestUri(goodsCost, weight);
					
        jQuery.getJSON(
            requestUri,
            function(msg)
            {
                var deliveryCost 		= ""; // Цена доставки
                var totalCost 			= ""; // Общая стоимость
                var deliveryTimeMessage = ""; // Время доставки
                var deliveryNote 		= ""; // Сообщение для пользователя
							
                if (msg.error == "undefined")
                {
                    deliveryCost 	= msg.price + " руб.";
                    totalCost 		= goodsCost + strToFloat(msg.price) + " руб.";
								
                    if (deliveryKind == "post")
                    {
                        if (goodsCost > 9000)
                        {
                            deliveryCost += '<span style="text-decoration:none;vertical-align:super;">*</span>';
                            deliveryNote = "* Стоимость посылки превышает 9000 руб. Для надежности рекомендуем Вам сменить способ доставки на ЕМС";
                        }
                    }
                    else
                    if (deliveryKind == "tcomp")
                    {
                        deliveryCost += '<span style="text-decoration:none;vertical-align:super;">*</span>';
                        deliveryNote = "* Стоимость доставки: 250 руб. + тариф транспортной компании от 300 руб";
                    }
									
                    if (msg.minDeliveryTime == 'undefined' || msg.maxDeliveryTime == 'undefined')
                        deliveryTimeMessage = "не определены";
                    else
                    {
                        if (msg.minDeliveryTime == msg.maxDeliveryTime)
                            deliveryTimeMessage = msg.minDeliveryTime.toString() + " дня";
                        else
                            deliveryTimeMessage = 	"От " + msg.minDeliveryTime.toString() +
                            " до " + msg.maxDeliveryTime.toString() + " дней";
                    }
                }
                else
                {
                    deliveryCost = "не определено";
                    totalCost	 = goodsCost + " руб.";
                    deliveryNote = msg.error;
                    deliveryTimeMessage = "не определены";
                }
							
                var regionList = document.getElementById("region");
                if (deliveryAction && regionList.options[regionList.selectedIndex].text == 'Москва')
                {
                    deliveryCost = '0 руб.<span style="text-decoration:none;vertical-align:super;">*</span>';
                    deliveryNote = "* Стоимость доставки по акции";
                }
							
                document.getElementById("deliveryCostValue").value	= msg.price;
                document.getElementById("deliveryCost").innerHTML 	= deliveryCost;
                document.getElementById("totalCost").innerHTML 		= totalCost;
                document.getElementById("deliveryTime").innerHTML 	= deliveryTimeMessage;
                document.getElementById("orderNote").innerHTML 		= deliveryNote;

                endLoad();
							
                return false;
            }
            );
    }
	
    return false;
}

// Возвращает индекс страны в списке стран
function getCountryIndex(name)
{
    var countryList = document.getElementById("country");
    if (countryList != null)
        for (var i=0; i<countryList.options.length; i++)
            if (countryList.options[i].text == name)
                return i;
    return -1;
}

// Возвращает индекс города/региона доставки в соответствующем списке
function getRegionIndex(name)
{
    var regionList = document.getElementById("region");
    if (regionList != null)
        for (var i=0; i<regionList.options.length; i++)
            if (regionList.options[i].text == name)
                return i;
    return -1;
}
