var xmlHttp = createXmlHttpRequestObject();

function createXmlHttpRequestObject(){
	var xmlHttp;
	try{
		xmlHttp = new XMLHttpRequest();
	}
	catch(e){
		var XmlHttpVersions = new Array("MSXML2.XMLHTTP.6.0",
										"MSXML2.XMLHTTP.5.0",
										"MSXML2.XMLHTTP.4.0",
										"MSXML2.XMLHTTP.3.0",
										"MSXML2.XMLHTTP",
										"Microsoft.XMLHTTP");
		for(var i=0; i<XmlHttpVersions.length && !xmlHttp; i++){
			try{
				xmlHttp = new ActiveXObject(XmlHttpVersions[i]);
			}
			catch(e){}
		}
	}
	if(!xmlHttp)
		alert("Ошибка создания объекта XMLHttpRequest.");
	else
		return xmlHttp;
}

function ClubCardClick(){
	cardinfoDiv = document.getElementById("cardinfo");
	cardinfoDiv.innerHTML = "";
	if(xmlHttp){
		var cardNumberValue = document.getElementById("clubCard").value;
		if(!cardNumberValue)
			alert("Укажите номер клубной карты.");
		else{
			var skidValue = document.getElementById("skidinp").value;
			var stdosValue = Number(document.getElementById("stdosinp").value);
			var sumskidValue = Number(document.getElementById("sumskidinp").value);
			var totalPriceValue = Number(document.getElementById("totalpriceinp").value);
			var totalPriceSaleValue = Number(document.getElementById("totalpricesaleinp").value);
			var discountforclubcardValue = document.getElementById("discountforclubcard").value;
			totalPriceValue = totalPriceValue + sumskidValue - stdosValue; 
			try{
				xmlHttp.open("GET", "clubCard.php?cardNumber=" + cardNumberValue + "&totalPrice=" + totalPriceValue + "&totalPriceSale=" + totalPriceSaleValue + "&skid=" + skidValue + "&stdos=" + stdosValue + "&discountforclubcard=" + discountforclubcardValue, true);
				xmlHttp.onreadystatechange = handleRequestStateChangeClubCard;
				xmlHttp.send(null);
			}
			catch(e){
				alert("Невозможно соединиться с сервером:\n" + e.toString());
			}
		}
	}
}

function handleRequestStateChangeClubCard(){
	if(xmlHttp.readyState == 4){
		if(xmlHttp.status == 200){
			try{
				handleServerResponseClubCard();
			}
			catch(e){
				alert("Ошибка чтения ответа: " + e.toString());
			}
		}
		else{
			alert("Возникли проблемы во время получения данных:\n" + xmlHttp.statusText);
		}
	}
}

function handleServerResponseClubCard(){
	var xmlResponse = xmlHttp.responseXML;
	if(!xmlResponse || !xmlResponse.documentElement)
		throw("Неверная структура XML:\n" + xmlHttp.responseText);
	var rootNodeName = xmlResponse.documentElement.nodeName;
	if(rootNodeName == "parsererror")
		throw("Invalid XML structure");
	
	xmlRoot = xmlResponse.documentElement;
	clubCardElement = xmlRoot.getElementsByTagName("clubCard");
	cardinfoDiv = document.getElementById("cardinfo");
	
	if(clubCardElement.item(0).firstChild.data != "No"){
		currentDiscountsElement = xmlRoot.getElementsByTagName("currentDiscounts");
		amountOfDiscountsElement = xmlRoot.getElementsByTagName("amountOfDiscounts");
		totalPriceElement = xmlRoot.getElementsByTagName("totalPrice");
		nextDiscountsElement = xmlRoot.getElementsByTagName("nextDiscounts");
		nextDiscountsPlusElement = xmlRoot.getElementsByTagName("nextDiscountsPlus");
		missingAmountElement = xmlRoot.getElementsByTagName("missingAmount");
		
		skidtxtDiv = document.getElementById("skidtxt");
		skidtxtDiv.innerHTML = "Ваша скидка по клубной карте " + currentDiscountsElement.item(0).firstChild.data + "%:<br>";
		skidinpInput = document.getElementById("skidinp");
		skidinpInput.value = currentDiscountsElement.item(0).firstChild.data;
		sumskidDiv = document.getElementById("sumskid");
		sumskidDiv.innerHTML = "-" + amountOfDiscountsElement.item(0).firstChild.data + " руб.<br>";
		sumskidinpInput = document.getElementById("sumskidinp");
		sumskidinpInput.value = amountOfDiscountsElement.item(0).firstChild.data;
		sumtotalDiv = document.getElementById("sumtotal");
		sumtotalDiv.innerHTML = totalPriceElement.item(0).firstChild.data + " руб.";
		totalpriceInput = document.getElementById("totalpriceinp");
		totalpriceInput.value = totalPriceElement.item(0).firstChild.data;
		discountforclubcardInput = document.getElementById("discountforclubcard");
		discountforclubcardInput.value = true;
		if(nextDiscountsElement.item(0).firstChild.data == 15)
			cardinfoDiv.innerHTML = "У Вас максимальная скидка - 15%.";
		else
			cardinfoDiv.innerHTML = "После текущего заказа скидка по клубной карте - " + nextDiscountsElement.item(0).firstChild.data + "%, до скидки " + nextDiscountsPlusElement.item(0).firstChild.data + "% остается - " + missingAmountElement.item(0).firstChild.data + " руб.<br>";
		clubCardInput = document.getElementById("clubCard");
		clubCardInput.readOnly = true;
		newcardInput = document.getElementById("newcardinp");
		newcardInput.disabled = true;
		ServiceDelivery();
	}
	else{
		cardinfoDiv.innerHTML = "Такой клубной карты не существует или скидка по ней меньше текущей!<br>";
	}
}

function ServiceDelivery(){
	servicedeliveryTable = document.getElementById("servicedelivery");
	servicedeliveryTable.className = "hidden";
	
	if(xmlHttp){
		var totalPriceValue = document.getElementById("totalpriceinp").value;
		var stdosValue = document.getElementById("stdosinp").value;
		var totalWeightValue = document.getElementById("totalweightinp").value;
		var totalPriceWithoutDosValue = Number(totalPriceValue) - Number(stdosValue);
		try{
			xmlHttp.open("GET", "serviceDelivery.php?totalPriceWithoutDos=" + totalPriceWithoutDosValue + "&totalWeight=" + totalWeightValue, true);
			xmlHttp.onreadystatechange = handleRequestStateChangeServiceDelivery;
			xmlHttp.send(null);
		}
		catch(e){
			alert("Невозможно соединиться с сервером:\n" + e.toString());
		}
	}
}

function handleRequestStateChangeServiceDelivery(){
	if(xmlHttp.readyState == 4){
		if(xmlHttp.status == 200){
			try{
				handleServerResponseServiceDelivery();
			}
			catch(e){
				alert("Ошибка чтения ответа: " + e.toString());
			}
		}
		else{
			alert("Возникли проблемы во время получения данных:\n" + xmlHttp.statusText);
		}
	}
}

function handleServerResponseServiceDelivery(){
	var xmlResponse = xmlHttp.responseXML;
	if(!xmlResponse || !xmlResponse.documentElement)
		throw("Неверная структура XML:\n" + xmlHttp.responseText);
	var rootNodeName = xmlResponse.documentElement.nodeName;
	if(rootNodeName == "parsererror")
		throw("Invalid XML structure");
	
	xmlRoot = xmlResponse.documentElement;
	for(var i=1; i<=5; i++){
		dostavkaDataElement = xmlRoot.getElementsByTagName("dostavkaData" + i);
		if(dostavkaDataElement.length > 0){
			dosSpan = document.getElementById("dosspan" + i);
			dosSpan.innerHTML = dostavkaDataElement.item(0).firstChild.data;
		
			dosRadio = document.getElementById("dosradio" + i);
			dosRadio.value = dostavkaDataElement.item(0).firstChild.data;
			if(dosRadio.checked == true){
				sumdosDiv = document.getElementById("sumdos");
				sumdosDiv.innerHTML = dostavkaDataElement.item(0).firstChild.data + " руб.<br>";
				stdosInput = document.getElementById("stdosinp");
				totalpriceInput = document.getElementById("totalpriceinp");
				totalpriceValue = Number(totalpriceInput.value) - Number(stdosInput.value);
				stdosInput.value = dostavkaDataElement.item(0).firstChild.data;
				
				stdosValue = Number(stdosInput.value);
				newTotalPrice = totalpriceValue + stdosValue;
				sumtotalDiv = document.getElementById("sumtotal");
				sumtotalDiv.innerHTML = newTotalPrice + " руб.";
				totalpriceInput.value = newTotalPrice;
			}
		}
		
		freeDostavkaDataElement = xmlRoot.getElementsByTagName("freeDostavkaData" + i);
		if(freeDostavkaDataElement.length > 0){
			dosFree = document.getElementById("dosfree" + i);
			if(freeDostavkaDataElement.item(0).firstChild.data != "No")
				dosFree.className = "";
			else
				dosFree.className = "hidden";
		}
	}
	
	servicedeliveryTable = document.getElementById("servicedelivery");
	servicedeliveryTable.className = "";
	
	//UpdateServiceDelivery(deliveryServiceElement.item(0).firstChild.data, costOfDeliveryElement.item(0).firstChild.data);
}
