var productImageBase = "images/products/";
var backColourNameArray = new Array("full", "bw", "none");
var drilledholeImageBase = "images/drilledhole/";
var foldingImageBase = "images/folding/";
var doorhangerImageBase = "images/doorhanger/";
var orderTotalAud = 0;
var postcodeIsValid = null;

function GetQuantity()
{
	var qty = document.getElementById(ID_quantity);
	if (qty == null) // Fixed quantity instead of text box
	{
		qty = document.getElementById(ID_ctlQuantityList);
	}
	return qty.value;
}

function GetPageCount()
{
	var pageCount = "1";
	var pageCountControl = document.getElementById(ID_pageCount);
	if (pageCountControl != null)
	{
		pageCount = pageCountControl.value;
	}
	return pageCount;
}

function UpdateQuantity()
{
	var designcount = parseInt(document.getElementById(ID_designcount).value, 10);
	var quantity = GetQuantity();
	var qtyHidden = document.getElementById("qtyhidden");
	if (qtyHidden != null)
	{
		qtyHidden.value = GetQuantity();
	}
	var ctltotal_quantity = document.getElementById(ID_total_quantity);
	ctltotal_quantity.innerHTML = quantity * designcount;
}

function ChangeDesignCount()
{
	UpdateQuantity();	
	RefreshQuote();
}

function ChangeFrontColour()
{
	RefreshQuote();
}

function ChangeQuantity()
{
	UpdateQuantity();
	RefreshQuote();
}

function ChangePageCount()
{
	RefreshQuote();
}

function ChangeBackColour()
{
	ChangeBackColourImage();
	RefreshQuote();
}

function ChangeBackColourImage()
{
	return; // Images removed for new discount products
	var frm = document.forms[0];
	var prodid = document.getElementById(ID_prodid).value;
	var prodFamily = document.getElementById(ID_prodfamily).value;
	var backColourId = GetOptionGroupValue("_ctl0:ctlContentMain:backcolour");

	var imgurl = productImageBase + prodFamily + "/" + prodid + "_back_" + backColourNameArray[backColourId-1] + ".jpg";
	var backImage = document.getElementById(ID_backimage);
	backImage.src = imgurl;
}

function ChangePaper(speedIndexMin)
{
	speedIndexMin = parseInt(speedIndexMin, 10);

	var prodSpeedControl = document.getElementById(ID_ctlProdSpeedList);
	if (parseInt(prodSpeedControl.value, 10) < speedIndexMin)
	{
		prodSpeedControl.value = speedIndexMin;
	}

	RefreshQuote();
}

function ChangeEnvelopeWindow()
{
	RefreshQuote();
}

function ChangeFridgeMagnet()
{
	RefreshQuote();
}

function ChangeDrilledHole()
{
	ChangeDrilledHoleImage();
	RefreshQuote();
}

function ChangeDrilledHoleImage()
{
	var frm = document.forms[0];
	var drilledholeName = GetListValue(ID_ctlDrilledHoleList);
	var foldName = "";

	var imgurl = drilledholeImageBase + drilledholeName + ".jpg";
	var drilledholeImage = document.getElementById("drilledholeimage");
	if (drilledholeImage != null)
	{
		drilledholeImage.src = imgurl;
	}
}

function ChangePerforation()
{
	RefreshQuote();
}

function ChangeFolding()
{
	ChangeFoldingImage();
	RefreshQuote();
}

function ChangeFoldingImage()
{
	var frm = document.forms[0];
	var foldingId = GetListValue(ID_ctlFoldingList);
	var foldName = "";

	switch (foldingId)
	{
		case "1":
			foldName = "none";
			break;
		case "2":
			foldName = "half";
			break;
		case "4":
			foldName = "z";
			break;
		case "8":
			foldName = "tri";
			break;
		case "16":
			foldName = "concertina";
			break;
		case "32":
			foldName = "fourpanel";
			break;
		case "64":
			foldName = "gate";
			break;
		case "128":
			foldName = "rolled";
			break;
	}

	var imgurl = foldingImageBase + "fold_" + foldName + ".jpg";
	var foldImage = document.getElementById("foldingimage");
	foldImage.src = imgurl;
}

function ChangeDoorHanger()
{
	ChangeDoorHangerImage();
}

function ChangeDoorHangerImage()
{
	var frm = document.forms[0];
	var doorhangerId = GetListValue(ID_ctlDoorHangerList);

	var imgurl = doorhangerImageBase + doorhangerId + "_Hole.jpg";
	var doorhangerImage = document.getElementById("doorhangerImage");
	if (doorhangerImage != null)
	{
		doorhangerImage.src = imgurl;
	}
}

function ChangeProductionSpeedDesc()
{
	var prodSpeed = document.getElementById(ID_ctlProdSpeedList).value;

	var desc = ProdSpeedDesc[prodSpeed];
	var descDiv = document.getElementById("prodSpeedDesc");
	descDiv.innerHTML = desc;
}

function ChangeProductionSpeed()
{
	ChangeProductionSpeedDesc();	
	RefreshQuote();
}

function ChangeDelivery()
{
	RefreshQuote();
}

function SelectDeliveryInternational()
{
	var delivery_international = document.getElementById(ID_ctlDelivery_International);
	delivery_international.checked = true;
}

function SelectDeliveryAustralia()
{
	var frm = document.forms[0];
	var delivery_aust = document.getElementById(ID_ctlDelivery_Australia);
	delivery_aust.checked = true;
	
	var countryId = document.getElementById(ID_CountryID);
	countryId.value = 'AU';
}

function ChangeCurrency()
{
	var currencyConvert = document.getElementById(ID_currencyConvert);
	var totalConverted = document.getElementById("TotalConverted");
	var conversion = currencyConvert.options[currencyConvert.selectedIndex].value;

	if (conversion == "0")
	{
		totalConverted.innerHTML = "";
	}
	else
	{
		totalConverted.innerHTML = FormatCurrency(orderTotalAud * conversion);
	}
}

function ChangeProof()
{
	RefreshQuote();
}

function ChooseSoftwareUsedReprint()
{
	var softUsed = document.getElementById(ID_SoftwareUsedID);
	softUsed.value = "16";
}

function UploadFileOnChange()
{
	var uploadRadio = document.getElementById(ID_transfer_upload);
	uploadRadio.checked = true;
}

/*
** Validation
*/
function ValidatePostcode()
{
	var postCode = document.getElementById(ID_postcode).value;

	return IsPostcodeValid(postCode);
}

function ValidatePostcodeCallback(responseData)
{
	if (responseData.error != null)
	{
		alert("Error when validating postcode\n\n" + responseData.error.Message + "\n" + responseData.error.Type);
		return;
	}

	postcodeIsValid = responseData.value;
	VAM_FieldChanged("postcode");
}

function ValidateUploadFile(cond)
{
	var isValid = true;
	var frm = document.forms[0];
	var fileTransferId = GetOptionGroupValue("_ctl0:ctlContentMain:FileTransferMethod");

	if (fileTransferId != "2")
	{
		return isValid;
	}

	var uploadFileName = document.getElementById(ID_ctlUploadFile);
	if (uploadFileName.value.length == 0)
	{
		isValid = false;
	}

	return isValid;
}

function ValidatePaymentMethod(cond)
{
	var frm = document.forms[0];
	var payId = GetOptionGroupValue("_ctl0:ctlContentMain:PaymentMethodID");

	if (payId == "")
	{
		return false;
	}
	else
	{
		return true;
	}
}

function ValidateCCName(cond)
{
	var frm = document.forms[0];
	var payId = GetOptionGroupValue("_ctl0:ctlContentMain:PaymentMethodID");

	if (payId == "4") // Direct deposit
	{
		return true;
	}

	var ccName = document.getElementById(ID_CCName);

	if (ccName.value.length == 0)
	{
		return false;
	}
	else
	{
		return true;
	}
}

function ValidateCCNumber(cond)
{
	var frm = document.forms[0];
	var payId = GetOptionGroupValue("_ctl0:ctlContentMain:PaymentMethodID");

	if (payId == "4") // Direct deposit
	{
		return true;
	}

	var ccNumber = document.getElementById(ID_CCNumber);

	if (ccNumber.value.length == 0)
	{
		return false;
	}
	else
	{
		return true;
	}
}

function RefreshQuoteAll()
{
	ChangePaper();
	ChangeProductionSpeedDesc();
	UpdateQuantity();
	ChangeBackColourImage();
	ChangeFoldingImage();
	ChangeDoorHangerImage();
	ChangeDrilledHoleImage();
	RefreshQuote();
}

function RefreshQuote()
{
	if (isQuote) { return; }

	var frm = document.forms[0];

	var prodid = document.getElementById(ID_prodid).value;
	var qty = GetQuantity();
	var designCount = parseInt(document.getElementById(ID_designcount).value, 10);
	var frontColourId = GetOptionGroupValue("_ctl0:ctlContentMain:frontcolour");
	var backColourId = GetOptionGroupValue("_ctl0:ctlContentMain:backcolour");

	if (frontColourId == "" || backColourId == "")
	{
		return; // Get the price after valid colour options are entered
	}

	var paperTypeId = GetOptionGroupValue("_ctl0:ctlContentMain:paper");
	var foldingOption = document.getElementById(ID_ctlFoldingList).value;
	var envWindowOption = document.getElementById(ID_ctlEnvelopeWindowList).value;
	var deliveryMethod = GetDeliveryMethod();
	var countryId = document.getElementById(ID_CountryID).value;
	var postCode = document.getElementById(ID_postcode).value;
	var prodSpeed = document.getElementById(ID_ctlProdSpeedList).value;
	var hasFridgeMagnet = false;
	var fridgemagnetrequired = document.getElementById(ID_fridgemagnet_required);
	if (fridgemagnetrequired != null) { hasFridgeMagnet = fridgemagnetrequired.checked; }
	var hasDrilledHole = false;
	var drilledholelist = document.getElementById(ID_ctlDrilledHoleList);
	if (drilledholelist != null) { hasDrilledHole = !(drilledholelist.value == "None"); }
	var perforationType = "";
	var perfcontrol = document.getElementById(ID_perforation);
	if (perfcontrol != null) { perforationType = perfcontrol.value; }
	
	var pageCount = GetPageCount();
	var proofOption = document.getElementById(ID_ctlProofList).value;
	var artworkType = GetArtworkType();
	/*
	alert("QuoteEngine.GetQuote(prodid='" + prodid + "'\n" +
	"qty='" + qty + "'\n" +
	"frontColourId='" + frontColourId + "'\n" +
	"backColourId='" + backColourId + "'\n" +
	"paperTypeId='" + paperTypeId + "'\n" +
	"foldingOption='" + foldingOption + "'\n" +
	"deliveryMethod='" + deliveryMethod + "'\n" +
	"countryId='" + countryId + "'\n" +
	"postCode='" + postCode + "'\n" +
	"prodSpeed='" + prodSpeed + "'\n" +
	"proofOption='" + proofOption + "'\n" +
	"pageCount='" + pageCount + "'\n");
	*/
	//var agentId = document.getElementById(ID_agentidvalue).value;
	//TheOnlinePrinter.WebUI.QuoteEngine.GetQuote(prodid,qty,frontColourId,backColourId,paperTypeId,foldingOption,deliveryMethod,countryId,postCode,prodSpeed,proofOption,pageCount,designOnlineUsed,agentId,RefreshQuoteCallBack);

	InitCalculator(prodid, qty, frontColourId, backColourId, paperTypeId, foldingOption,
			deliveryMethod, countryId, postCode, prodSpeed, proofOption, pageCount, artworkType, designCount,
			envWindowOption, hasFridgeMagnet, hasDrilledHole, perforationType);
	var quoteData = Calculate();
	RefreshQuoteCallBack(quoteData);
}

function RefreshQuoteCallBack(data)
{
////	if (responseData.error != null)
////	{
////		alert("Error when updating prices\n\n" + responseData.error.Message + "\n" + responseData.error.Type);
////		return;
////	}

////	var data = responseData.value;

	// post values
	var formPrintPrice = document.getElementById("printingprice");
	var formAdminCharge = document.getElementById("adminprice");
	var formProofCharge = document.getElementById("proofprice");
	var formUrgencyCharge = document.getElementById("urgencyprice");
	var formFreightCharge = document.getElementById("freightprice");
	var formOrderTotal = document.getElementById("ordertotalprice");
	formPrintPrice.value = data.SubTotal;
	formProofCharge.value = data.Proof;
	formUrgencyCharge.value = data.Urgency;
	formFreightCharge.value = data.Freight;
	formOrderTotal.value = data.Total;
	orderTotalAud = data.Total;

	// calculator values
	var calcPrintPrice = document.getElementById(ID_CalcPrintPrice);
	var calcAdminCharge = document.getElementById(ID_CalcAdminCharge);
	var calcProofCharge = document.getElementById(ID_CalcProofCharge);
	//var calcUrgencyCharge = document.getElementById(ID_CalcUrgencyCharge);
	var calcFreightCharge = document.getElementById(ID_CalcFreightCharge);
	var calcOrderTotal = document.getElementById(ID_CalcOrderTotal);
	var calcCostPerUnit = document.getElementById(ID_CalcCostPerUnit);
	var calcSubTotal = document.getElementById(ID_CalcSubTotal);
	var calcDiscountAmount = document.getElementById(ID_CalcDiscountAmount);

	calcPrintPrice.innerHTML = FormatCurrency(data.SubTotal + data.Urgency);
	calcAdminCharge.innerHTML = FormatCurrency(data.Admin);
	calcProofCharge.innerHTML = FormatCurrency(data.Proof);
	//calcUrgencyCharge.innerHTML = FormatCurrency(data.Urgency);
	calcFreightCharge.innerHTML = FormatCurrency(data.Freight);
	calcOrderTotal.innerHTML = FormatCurrency(data.Total);
	calcCostPerUnit.innerHTML = FormatCurrency(data.CostPerUnit);
	if (calcSubTotal != null)
	{
		calcSubTotal.innerHTML = FormatCurrency(data.SubTotal + data.Admin + data.Proof + data.Urgency);
	}
	if (calcDiscountAmount != null)
	{
		calcDiscountAmount.innerHTML = FormatCurrency(data.DiscountPrice);
	}

	ChangeCurrency();
}

function GetDeliveryMethod()
{
	var delivInternational = document.getElementById(ID_ctlDelivery_International);
	if (delivInternational.checked)
	{
		return 3; // International = 3
	}
	else
	{
		var ausDeliv = document.getElementById(ID_ctlDeliveryMethodList);
		return ausDeliv.value;
	}
}

function DuplicateContactAddress()
{
	var contactFirstName = document.getElementById(ID_ContactFirstName);
	var contactLastName = document.getElementById(ID_ContactLastName);
	var contactCompany = document.getElementById(ID_ContactCompany);
	var contactAddress1 = document.getElementById(ID_ContactAddress1);
	var contactAddress2 = document.getElementById(ID_ContactAddress2);
	var contactSuburb = document.getElementById(ID_ContactSuburb);
	var contactState = document.getElementById(ID_ContactState);
	var contactPostcode = document.getElementById(ID_ContactPostcode);
	var contactPhone = document.getElementById(ID_ContactPhoneNumber);
	var contactEmail = document.getElementById(ID_ContactEmailAddress);

	var deliveryFirstName = document.getElementById(ID_DeliveryFName);
	var deliveryLastName = document.getElementById(ID_DeliveryLastName);
	var deliveryCompany = document.getElementById(ID_DeliveryCompany);
	var deliveryAddress1 = document.getElementById(ID_DeliveryAddress1);
	var deliveryAddress2 = document.getElementById(ID_DeliveryAddress2);
	var deliverySuburb = document.getElementById(ID_DeliverySuburb);
	var deliveryState = document.getElementById(ID_DeliveryState);
	// set based on quote page - var deliveryPostcode = document.getElementById(ID_DeliveryPostcode);
	var deliveryPhone = document.getElementById(ID_DeliveryPhoneNumber);
	var deliveryEmail = document.getElementById(ID_DeliveryEmailAddress);

	deliveryFirstName.value = contactFirstName.value;
	deliveryLastName.value = contactLastName.value;
	deliveryCompany.value = contactCompany.value;
	deliveryAddress1.value = contactAddress1.value;
	deliveryAddress2.value = contactAddress2.value;
	deliverySuburb.value = contactSuburb.value;
	deliveryState.value = contactState.value;
	deliveryPhone.value = contactPhone.value;
	deliveryEmail.value = contactEmail.value;
}

function FormatCurrency(amount)
{
	if (amount == null) return "0.00";

	return amount.toFixed(2).toString();
}

function GetListValue(listName)
{
	var listControl = document.getElementById(listName);
	if (listControl == null) { return ""; }
	return listControl.options[listControl.selectedIndex].value;
}

function GetOptionGroupValue(groupname)
{
	var collection = document.getElementsByName(groupname);

	if (collection == null) return null;

	if (typeof(collection.length) == "undefined")
	{
		return collection.value;
	}

	for (i = 0; i < collection.length; i++)
	{
		if (collection[i].checked)
			return collection[i].value;
	}

	return "";
}

function GetArtworkType()
{
	var artworkType = GetOptionGroupValue("_ctl0:ctlContentMain:artworkType");
	
	switch (artworkType)
	{
		case "artwork_usedesignonline":
			return ArtworkType.DesignOnline;
		case "artwork_upload":
			return ArtworkType.UploadOther;
		case "artwork_reprintexact":
			return ArtworkType.ReprintJobExact;
		case "artwork_reprintchange":
			return ArtworkType.ReprintJobWithChanges;
		case "artwork_designedonline":
			return ArtworkType.AlreadyDesignedOnline;
		default:
			return ArtworkType.Unknown
	}
}
