
try {
	//browser detection
	var strUserAgent = navigator.userAgent.toLowerCase(); 
	var isIE = strUserAgent.indexOf("msie") > -1; 
	var isNS6 = strUserAgent.indexOf("netscape6") > -1; 
	var isNS4 = !isIE && !isNS6  && parseFloat(navigator.appVersion) < 5; 

	//regular expressions
	var reValidNumberChars = /\d/;
	var reValidMoneyChars = /[\d\.]/;
	var reValidDateChars = /[\d\\]/;
	var reValidNumberString = /^\d*$/;
	var reValidMoneyString1 = /^\d*\.\d*$/;
	var reValidMoneyString2 = /^\d*$/;
	var reValidDateString = /^\d\d\d\d\-\d\d\-\d\d$/;
	var rePeriod = /\./;
	var reKeyboardChars = /[\x00\x03\x08\x0D\x16\x18\x1A]/;
	var reClipboardChars = /[cvxz]/i;

	var ButtonClicked=false;

} catch(exception) {
	alert("This application does not support your browser version.");
}

var xmlhttp;
var xmlhttp_reset = false;

if (xmlhttp == null)
{
	try 
	{
		xmlhttp = new XMLHttpRequest();
		xmlhttp_reset = true;
	}
	catch (e)
	{
		try 
		{
			xmlhttp = new ActiveXObject("Msxml2.XMLHTTP.3.0");
		}
		catch (ee)
		{
			try 
			{
				xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
			}
			catch (eee)
			{
				try
				{
					xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
				}
				catch(eeee)
				{
					xmlhttp = null;
				}
			}
		}
	}
}


function ButtonHandler()
{
	if (ButtonClicked) {
		return false;
	} else {
		ButtonClicked=true;
		return true;
	}
}

function DeleteItem(sPage)
{
	ShowConfirmation('../../Includes/Confirm.aspx?msg=140000&param=' + sPage);
}

function DeleteItem_Run(sPage)
{
	window.opener.open("../" + sPage,"_self","");
}

function PlaceOrder(SpecialOrderId, ProductLetter) 
{
	if (!isValidDate(window.document.forms["EstimateDetailsForm"].NeededBy.value)) {
		window.alert("Please enter a valid 'Needed By' date - YYYY-MM-DD");
		ButtonClicked=false;
		return false;
	} else if (window.document.forms["EstimateDetailsForm"].PoNumber != null && window.document.forms["EstimateDetailsForm"].PoNumber.value != "") {
		
		window.document.forms["EstimateDetailsForm"].action='../PendingEstimates/PlaceOrder.aspx?orderid='+SpecialOrderId+'&productletter='+ProductLetter;
		window.document.forms["EstimateDetailsForm"].submit();
		
		OpenNotification("../../Includes/Notification.aspx?Msg=The Order has been placed, for order status check the Work In Progress for details");
		
		return false;
	} else {
		window.alert("Please enter a Purchase Order Number");
		ButtonClicked=false;
		return false;
	}
}

function GeneratePurchaseOrders() 
{
	if (aSuppliers != null) 
	{
		for (i=0; i<aSuppliers.length; i++)
		{
			//var aInput = window.document.forms["thisForm"].all("NeededBy_"+aSuppliers[i]);
			
			// because firefox doesn't understand the above statement :@
			var aInput = window.document.forms["thisForm"].elements["NeededBy_"+aSuppliers[i]];
						
			if (aInput != null) 
			{
				if (!isValidDate(aInput.value)) 
				{
					window.alert("Please enter a valid 'Needed By' date - YYYY-MM-DD");
					ButtonClicked = false;
					return false;
				}
			}
		}
				
		window.document.forms['thisForm'].action='GenerateOrders.aspx?';
		window.document.forms['thisForm'].submit();
		
		OpenNotification("../../Includes/Notification.aspx?Msg=The Order has been placed, for order status check the Work In Progress for details");
		
		//ShowProgressBarSub2();
		
		return false;
	} else {
		window.alert("ERROR: no suppliers detected for order!");
		return false;
	}
}

function ReturnEstimate()
{
	if (!(isValidMoney(window.document.forms["EstimateDetailsForm"].CostA.value) && isValidMoney(window.document.forms["EstimateDetailsForm"].CostB.value) && isValidMoney(window.document.forms["EstimateDetailsForm"].CostC.value))) {
		window.alert("Please enter valid Costs.");
		return false;
	}
	window.document.forms['EstimateDetailsForm'].action='ReturnEstimate.aspx';
	window.document.forms['EstimateDetailsForm'].submit();
	return false;
}

// ===============================================
//	Affiliate estimate request functions
// ===============================================

function AffiliateCancelQuotation(orderid)
{
	ShowConfirmation('../../Includes/Confirm.aspx?msg=110000&param=' + orderid);
	ButtonClicked = false;
}

function AffiliateCancelQuotation_Run(orderid)
{
	window.opener.open("../Affiliate/Quotations/CancelQuotation.aspx?orderid="+orderid,"_self");
}

function AffiliateFileQuotation(orderid)
{
	ShowConfirmation('../../Includes/Confirm.aspx?msg=250000&param=' + orderid);
	ButtonClicked = false;
}

function AffiliateFileQuotation_Run(orderid)
{
	window.opener.open("../Affiliate/Quotations/FileQuotation.aspx?orderid="+orderid,"_self");
}

function AffiliateArchieveQuotation(orderid)
{
	ShowConfirmation('../../Includes/Confirm.aspx?msg=260000&param=' + orderid);
	ButtonClicked = false;
}

function AffiliateArchieveQuotation_Run(orderid)
{
	window.opener.open("../Affiliate/Quotations/ArchieveQuotation.aspx?orderid="+orderid,"_self");
}

function SelectQuotationSuppliers()
{
	window.document.forms['SelectSuppliersForm'].action='SubmitQuotationToSuppliers.aspx';
	window.document.forms['SelectSuppliersForm'].submit();
	return false;
}

function ChooseQuotation(SpecialOrderId, SpecialOrderRequestId, SupplierId)
{
	window.document.forms['QuotationDetailsForm'].action='SelectQuotation.aspx?orderid='+SpecialOrderId+'&requestid='+SpecialOrderRequestId+'&supplierid='+SupplierId;
	window.document.forms['QuotationDetailsForm'].submit();
	return false;
}

function ChooseQuotationNew(SpecialOrderId, SpecialOrderDetailId, SpecialOrderRequestId, SupplierId) 
{
	window.document.forms["QuotationDetailsForm"].action='SelectQuotation.aspx?orderid='+SpecialOrderId+'&itemid=' + SpecialOrderDetailId + '&requestid='+SpecialOrderRequestId+'&supplierid='+SupplierId;
	window.document.forms["QuotationDetailsForm"].submit();
	return false;
}

function AffiliateCancelOrder()
{
	ShowConfirmation('../../Includes/Confirm.aspx?msg=120000&param=');
	ButtonClicked = false;
}

function AffiliateCancelOrder2()
{
	ShowConfirmation('../../../Includes/Confirm.aspx?msg=120001&param=');
	ButtonClicked = false;
}

function AffiliateCancelOrder_Run()
{
	window.opener.document.forms['OrderDetailsForm'].action='CancelOrder.aspx';
	window.opener.document.forms['OrderDetailsForm'].submit();
}

function AffiliateCancelOrder2_Run()
{
	window.opener.document.forms['OrderDetailsForm'].action='../CancelOrder.aspx';
	window.opener.document.forms['OrderDetailsForm'].submit();
}

function AffiliateApproveCharges()
{
	window.document.forms['OrderDetailsForm'].action='../WorkInProgress/AcceptExtraCharges.aspx';
	window.document.forms['OrderDetailsForm'].submit();
	return false;
}

function AffiliateCancelCharges()
{
	window.document.forms['OrderDetailsForm'].action='../WorkInProgress/RejectExtraCharges.aspx';
	window.document.forms['OrderDetailsForm'].submit();
	return false;
}

// ===============================================
//	Affiliate purchase order functions
// ===============================================
function AffiliateAcceptOrder()
{
	if (!(isValidMoney(window.document.forms["OrderDetailsForm"].Gst.value) && (window.document.forms["OrderDetailsForm"].Pst == null || isValidMoney(window.document.forms["OrderDetailsForm"].Pst.value)) && isValidMoney(window.document.forms["OrderDetailsForm"].ShippingCharge.value))) {
		ShowAlert("../../../Includes/Alert.aspx?Msg=Please enter a valid Shipping cost.");
		ButtonClicked=false;
		return false;
	} else if (!isValidDate(window.document.forms["OrderDetailsForm"].PromisedBy.value)) {
		ShowAlert("../../../Includes/Alert.aspx?Msg=Please enter a valid Promised by Date.");
		ButtonClicked=false;
		return false;
	}
	
	//ShowProgressBarSub3();
	
	window.document.forms['OrderDetailsForm'].action='../VendorOrders/AcceptOrder.aspx';
	window.document.forms['OrderDetailsForm'].submit();
	
	return false;
}

function AffiliateFulFillOrder()
{
	window.document.forms['OrderDetailsForm'].action='../FulFillOrder.aspx';
	window.document.forms['OrderDetailsForm'].target='_self';
	window.document.forms['OrderDetailsForm'].submit();
	window.open('OrderInvoice.aspx?orderid=' + getQueryVariable("orderid"), "_blank", "");
	return false;
}

// ===============================================
//	Vendor purchase order functions
// ===============================================

function AcceptOrder()
{
	if (!(isValidMoney(window.document.forms["OrderDetailsForm"].Gst.value) && (window.document.forms["OrderDetailsForm"].Pst == null || isValidMoney(window.document.forms["OrderDetailsForm"].Pst.value)) && isValidMoney(window.document.forms["OrderDetailsForm"].ShippingCharge.value))) {
		ShowAlert("../../Includes/Alert.aspx?Msg=Please enter valid Shipping.");
		ButtonClicked=false;
		return false;
	} else if (!isValidDate(window.document.forms["OrderDetailsForm"].PromisedBy.value)) {
		ShowAlert("../../Includes/Alert.aspx?Msg=Please enter valid Promised by Date.");
		ButtonClicked=false;
		return false;
	}
	
	//ShowProgressBarSub2();
	
	window.document.forms['OrderDetailsForm'].action='../WorkInProgress/AcceptOrder.aspx';
	window.document.forms['OrderDetailsForm'].submit();
	return false;
}

function ApproveOrder()
{
	window.document.forms['OrderDetailsForm'].action='../WorkInProgress/ApproveOrder.aspx';
	window.document.forms['OrderDetailsForm'].submit();
	return false;
}

//	client approves an order before it is sent to the vendor
function ClientApproveOrder()
{
	window.document.forms['OrderDetailsForm'].action='../WorkInProgress/ClientApproveOrder.aspx';
	window.document.forms['OrderDetailsForm'].submit();
	return false;
}

//	affiliate approves a clients order
function AffiliateApproveClientApprovalOrder()
{
	ShowConfirmation('../../Includes/Confirm.aspx?msg=270000&param=');
	ButtonClicked = false;
}

function AffiliateApproveClientApprovalOrder_Run()
{
	window.opener.document.forms['OrderDetailsForm'].action='ApproveClientOrder.aspx';
	window.opener.document.forms['OrderDetailsForm'].submit();
}

function FulFillOrder()
{
	window.document.forms['OrderDetailsForm'].action='../WorkInProgress/FulFillOrder.aspx';
	window.document.forms['OrderDetailsForm'].target='_self';
	window.document.forms['OrderDetailsForm'].submit();
	return false;
}

function VendorCancelOrder()
{
	if (window.confirm("Are you sure you want to cancel this order?")) 
	{
		window.document.forms['OrderDetailsForm'].action='../WorkInProgress/CancelOrder.aspx';
		window.document.forms['OrderDetailsForm'].submit();
		return false;
	} else {
		ButtonClicked = false;
	}
}

// ===============================================
//	Vendor estimate functions
// ===============================================
function VendorReturnRequest()
{
	window.document.forms['EstimateDetailsForm'].action='ReturnEstimate.aspx';
	window.document.forms['EstimateDetailsForm'].submit();
	OpenNotification("../../Includes/Notification.aspx?Msg=The prices have been returned to your affiliate");
	return false;
}

function VendorSaveRequestItem()
{
	window.document.forms['QuotationItemDetailsForm'].action='SaveEstimateItem.aspx';
	window.document.forms['QuotationItemDetailsForm'].submit();
	return false;
}

function VendorCancelRequest()
{
	if (window.confirm("Are you sure you want to cancel this request?")) {
		window.document.forms['EstimateDetailsForm'].action='CancelEstimate.aspx';
		window.document.forms['EstimateDetailsForm'].submit();
		return false;
	} else {
		ButtonClicked = false;
	}
}

// ===============================================
//	Client purchase order functions
// ===============================================
function ClientCancelOrder()
{
	if (window.confirm("Are you sure you want to cancel this order?")) {
		window.document.forms['OrderDetailsForm'].action='../WorkInProgress/CancelOrder.aspx';
		window.document.forms['OrderDetailsForm'].submit();
		return false;
	} else {
		ButtonClicked = false;
	}
}

function ClientPlaceEstimateOrder()
{
	if (window.document.forms["EstimateDetailsForm"].PoNumber+'' != 'undefined' && window.document.forms["EstimateDetailsForm"].PoNumber.value == '') {
		ShowAlert("../../Includes/Alert.aspx?Msg=Please enter a PO Number!");
		ButtonClicked=false;
		return false;
	} else if (!isValidDate(window.document.forms["EstimateDetailsForm"].NeededBy.value)) {
		ShowAlert("../../Includes/Alert.aspx?Msg=Please enter a valid Needed by Date.");
		ButtonClicked=false;
		return false;
	}

	window.document.forms['EstimateDetailsForm'].action='../PendingEstimates/PlaceOrder.aspx';
	window.document.forms['EstimateDetailsForm'].submit();
	
	OpenNotification("../../Includes/Notification.aspx?Msg=The Order has been placed, for order status check the Work In Progress for details");
	
	return false;
}

function ClientCopyToNewRequest()
{
	window.document.forms['EstimateDetailsForm'].action='../PendingEstimates/CopyToNewRequest.aspx';
	window.document.forms['EstimateDetailsForm'].submit();
	return false;
}

function ClientCopyToNewRequestOrder()
{
	window.document.forms['EstimateDetailsForm'].action='../PendingEstimates/CopyToNewOrder.aspx';
	window.document.forms['EstimateDetailsForm'].submit();
	OpenNotification("../../Includes/Notification.aspx?Msg=The request for quotation has been sent, you will receive an estimate shortly.");	
	return false;
}

// ===============================================
//	Common order functions
// ===============================================
function SubmitOrderSearch()
{
	window.document.forms['OrderDetailsForm'].action='SearchResults.aspx';
	window.document.forms['OrderDetailsForm'].submit();
}

// ================================================
//	Print functions
// ================================================
function PrintProductReport()
{
	window.document.forms['OrderDetailsForm'].action='ProductReportPrintable.aspx';
	window.document.forms['OrderDetailsForm'].target='_blank';
	window.document.forms['OrderDetailsForm'].submit();
	ButtonClicked=false;
	return false;
}
function PrintPurchaseOrderReport()
{
	window.document.forms['OrderDetailsForm'].action='PurchaseOrderReportPrintable.aspx';
	window.document.forms['OrderDetailsForm'].target='_blank';
	window.document.forms['OrderDetailsForm'].submit();
	window.document.forms['OrderDetailsForm'].action='PurchaseOrderReport.aspx';
	window.document.forms['OrderDetailsForm'].target='_self';
	ButtonClicked=false;
	return false;
}
function PrintSpecialItemReport()
{
	window.document.forms['OrderDetailsForm'].action='SpecialItemReportPrintable.aspx';
	window.document.forms['OrderDetailsForm'].target='_blank';
	window.document.forms['OrderDetailsForm'].submit();
	ButtonClicked=false;
	return false;
}
function PrintCompletedOrders()
{
	window.document.forms['CompletedOrdersListForm'].action='CompletedOrdersListPrintable.aspx';
	window.document.forms['CompletedOrdersListForm'].target='_blank';
	window.document.forms['CompletedOrdersListForm'].submit();
	ButtonClicked=false;
	return false;
}
function PrintOrderSearch()
{
	window.document.forms['OrderDetailsForm'].action='OrderSearchPrintable.aspx';
	window.document.forms['OrderDetailsForm'].target='_blank';
	window.document.forms['OrderDetailsForm'].submit();
	ButtonClicked=false;
	return false;
}
function PrintProductSearch()
{
	window.document.forms['OrderDetailsForm'].action='ProductSearchPrintable.aspx';
	window.document.forms['OrderDetailsForm'].target='_blank';
	window.document.forms['OrderDetailsForm'].submit();
	ButtonClicked=false;
	return false;
}
function PrintOrderDetails(orderid)
{
	window.open('OrderDetailsPrintable.aspx?orderid='+orderid);
	ButtonClicked=false;
	return false;
}

// Ants Luts, Feb 16, 05
function PrintAffiliateVendorOrderDetails(orderid)
{
	window.open('VendorOrders/OrderDetailsPrintable.aspx?orderid='+orderid);
	ButtonClicked=false;
	return false;
}

function PrintPackingSlip(Orderid)
{
	window.document.forms['OrderDetailsForm'].action='../Orders/PackingSlip.aspx?orderid='+Orderid;
	window.document.forms['OrderDetailsForm'].target='_blank';
	window.document.forms['OrderDetailsForm'].submit();
	window.document.forms['OrderDetailsForm'].target='_self';
	ButtonClicked=false;
	return false;
}
// ================================================
//	Copy functions
// ================================================
function CopyPurchaseOrder(sPurchaseOrderID) {
	alert(sPurchaseOrderID);
}

// ================================================
//	Shopping cart functions
// ================================================
function AddToCart(ProductLetter)
{
	window.document.forms['ProductDetailsForm'].action='../Shopping/AddCart.aspx?productletter='+ProductLetter;
	window.document.forms['ProductDetailsForm'].submit();
	return false;
}

function UpdateCart(ProductLetter)
{
	window.document.forms['ProductDetailsForm'].action='../Shopping/UpdateCart.aspx?productletter='+ProductLetter;
	window.document.forms['ProductDetailsForm'].submit();
	return false;
}
function UpdatePODetail(ProductLetter,OrderID)
{
	window.document.forms['ProductDetailsForm'].action='../Shopping/UpdatePODetail.aspx?productletter='+ProductLetter+'&orderid='+OrderID;
	window.document.forms['ProductDetailsForm'].submit();
	return false;
}

// Image proofing
function UpdateProof() 
{
	var oFields = window.document.forms["ProductDetailsForm"].getElementsByTagName("INPUT");
	var sProductId = window.document.forms["ProductDetailsForm"].ProductId.value;
	var sQueryString = "";
	var len = oFields.length;
	for (var i=0; i<len; i++) {
		if (oFields[i].tagName == "INPUT" && oFields[i].name.substr(0,6) == "field_") {
			sQueryString += oFields[i].name.substr(6) + "=" + encodeURIComponent(oFields[i].value) + "&";
		}
	}
	try {
		window.document.forms['ProductDetailsForm'].ProductImage.src = "../Search/Proof.aspx?" + sQueryString + "productid=" + sProductId;
	} catch (ex) {
	}
}

function UpdateProofLarge() 
{
	var oFields = window.document.forms["ProductDetailsForm"].getElementsByTagName("INPUT");
	var sProductId = window.document.forms["ProductDetailsForm"].ProductId.value;
	var sQueryString = "";
	var len = oFields.length;
	for (var i=0; i<len; i++) {
		if (oFields[i].tagName == "INPUT" && oFields[i].name.substr(0,6) == "field_") {
			sQueryString += oFields[i].name.substr(6) + "=" + encodeURIComponent(oFields[i].value) + "&";
		}
	}
	try {
		window.document.forms['ProductDetailsForm'].action = "../Search/ProofLarge.aspx?" + sQueryString + "productid=" + sProductId + "&size=2";
		window.document.forms['ProductDetailsForm'].target='_blank';
		window.document.forms['ProductDetailsForm'].submit();
		//	reset the target for future actions
		window.document.forms['ProductDetailsForm'].target='_self';
	} catch (ex) {
	}
}

function UpdateProofPDF() 
{
	var oFields = window.document.forms["ProductDetailsForm"].getElementsByTagName("INPUT");
	var sProductId = window.document.forms["ProductDetailsForm"].ProductId.value;
	var sQueryString = "";
	var len = oFields.length;
	for (var i=0; i<len; i++) {
		if (oFields[i].tagName == "INPUT" && oFields[i].name.substr(0,6) == "field_") {
			sQueryString += oFields[i].name.substr(6) + "=" + escape(oFields[i].value) + "&";
		}
	}
	try {
		window.document.forms['ProductDetailsForm'].action = "../Search/ProofPDF.aspx?" + sQueryString + "productid=" + sProductId;
		window.document.forms['ProductDetailsForm'].target='_blank';
		window.document.forms['ProductDetailsForm'].submit();
		//	reset the target for future actions
		window.document.forms['ProductDetailsForm'].target='_self';
	} catch (ex) {
	}
}


function AffiliateUpdateProof() 
{
	var pId = window.document.forms["ProductDetailsForm"].purchaserid.value;
	var oFields = window.document.forms["ProductDetailsForm"].getElementsByTagName("INPUT");
	var sProductId = window.document.forms["ProductDetailsForm"].ProductId.value;
	var sQueryString = "";
	var len = oFields.length;
	for (var i=0; i<len; i++) {
		if (oFields[i].tagName == "INPUT" && oFields[i].name.substr(0,6) == "field_") {
			sQueryString += oFields[i].name.substr(6) + "=" + encodeURIComponent(oFields[i].value) + "&";
		}
	}
	try {
		window.document.forms['ProductDetailsForm'].ProductImage.src = "../../Purchaser/Search/Proof.aspx?r=affiliate&p=" + pId + "&" + sQueryString + "productid=" + sProductId;
	} catch (ex) {
	}
}

function AffiliateUpdateProofLarge() 
{
	var pId = window.document.getElementById("purchaserid").value;
	var oFields = window.document.forms["ProductDetailsForm"].getElementsByTagName("INPUT");
	var sProductId = window.document.forms["ProductDetailsForm"].ProductId.value;
	var sQueryString = "";
	var len = oFields.length;
	for (var i=0; i<len; i++) {
		if (oFields[i].tagName == "INPUT" && oFields[i].name.substr(0,6) == "field_") {
			sQueryString += oFields[i].name.substr(6) + "=" + encodeURIComponent(oFields[i].value) + "&";
		}
	}
	try {
		window.document.forms['ProductDetailsForm'].action = "../../Purchaser/Search/ProofLarge.aspx?r=affiliate&p=" + pId + "&" + sQueryString + "productid=" + sProductId + "&size=2";
		window.document.forms['ProductDetailsForm'].target='_blank';
		window.document.forms['ProductDetailsForm'].submit();
		
		//	reset the target for future actions
		window.document.forms['ProductDetailsForm'].target='_self';
	} catch (ex) {
		window.alert("error");
	}
}
// ???

function SavePurchaserNote()
{
	var note = window.document.getElementById("PurchaserNote").value;
	note = escape(note);
	var url  = "OrderNotesEdit.aspx?orderid=" + window.document.getElementById("PurchaseOrderId").value + "&str=" + urlencode(note);
	ASyncHttpGetRequest(url, "vendor_save_status", "AffiliateSaveSupplierNote1()");
	window.document.getElementById("vendor_save_status").innerHTML = "SAVING...";
}

function AffiliateSaveSupplierNote()
{
	var note = window.document.getElementById("SupplierNote").value;
	note = escape(note);
	var url  = "SaveSupplierNote.aspx?orderid=" + window.document.getElementById("PurchaseOrderId").value + "&str=" + urlencode(note);
	ASyncHttpGetRequest(url, "vendor_save_status", "AffiliateSaveSupplierNote1()");
	window.document.getElementById("vendor_save_status").innerHTML = "SAVING...";
}

function AffiliateSaveSupplierNote1()
{
	//window.document.getElementById("vendor_save_status").innerHTML = "SAVED";
}

function urlencode(strText) {                             
	var isObj;
	var trimReg;
	if( typeof(strText) == "string" ) {
		if( strText != null ) {
			trimReg = /(^\s+)|(\s+$)/g;
			strText = strText.replace(trimReg, '');
			//for(var i=32;i<256;i++) {
				strText = strText.replace(String.fromCharCode(34),escape(String.fromCharCode(34)));
				strText = strText.replace(String.fromCharCode(35),escape(String.fromCharCode(35)));
				strText = strText.replace(String.fromCharCode(36),escape(String.fromCharCode(36)));
				strText = strText.replace(String.fromCharCode(37),escape(String.fromCharCode(37)));
				strText = strText.replace(String.fromCharCode(38),escape(String.fromCharCode(38)));
				strText = strText.replace(String.fromCharCode(39),escape(String.fromCharCode(39)));
			//}
		}
	}
	return strText;
}

// ================================================
//	mask functions
// ================================================


// ================================================
function TotalNumberMaskKeyPress(objEvent) {
	NumberMaskKeyPress(objEvent);
}

function TotalNumberMaskChange(objEvent) {
	NumberMaskChange(objEvent);
	var Quantity = parseFloat(document.getElementById("txtQuantityA").value);
	var Overs = parseFloat(document.getElementById("txtOversWaste").value);
	var Bindery = parseFloat(document.getElementById("txtBinderyWaste").value);
	var Printing = parseFloat(document.getElementById("txtPrintingWaste").value);
	var total_waste = Quantity + Overs + Bindery + Printing;
	
	document.getElementById("txtTotalQuantity").value = total_waste;
}

// ================================================

function NumberMaskKeyPress(objEvent) {
	var iKeyCode, strKey;

	var objInput = GetEventObject(objEvent);
	var iKeyCode = GetKeyCode(objEvent);
	
	strKey = String.fromCharCode(iKeyCode);

	if (isValidNumber(objInput.value)) {
		objInput.validValue = objInput.value;
		if (!reValidNumberChars.test(strKey) && !reKeyboardChars.test(strKey)) {
			return false;
		}
	} else {
		objInput.value = objInput.validValue;
		return false;
	}
	// didn't enter a number and the box is empty, default to '0'
	if (!reValidNumberChars.test(strKey) && objInput.value == "")
		objInput.value = "0";
}

function NumberMaskChange(objEvent) {
	var objInput = GetEventObject(objEvent);

	if (!isValidNumber(objInput.value)) {
		objInput.value = objInput.validValue || "";
		objInput.focus();
		objInput.select();
	} else {
		objInput.validValue = objInput.value;
	}
}

function isValidNumber(strValue) {
	return reValidNumberString.test(strValue) || strValue.length == 0;			
}

function GetKeyCode(objEvent)
{
	var iKeyCode;
	if (isIE) {
		iKeyCode = objEvent.keyCode;
	} else {
		iKeyCode = objEvent.which;
	}
	return(iKeyCode);
}

function GetEventObject(objEvent)
{
	var objInput;
	if (isIE) {
		objInput = objEvent.srcElement; 
	} else {
		objInput = objEvent.target;
	}
	return(objInput);
}

function FloatIntMaskKeyPress(objEvent)
{
	var objInput = GetEventObject(objEvent);
	if (objInput.value.indexOf(".") >= 0)
	{
		MoneyMaskKeyPress(objEvent);
	}
	else
	{
		NumberMaskKeyPress(objEvent);
	}
}

function FloatIntMaskChange(objEvent)
{
	var objInput = GetEventObject(objEvent);
	if (objInput.value.indexOf(".") >= 0)
	{
		MoneyMaskChange(objEvent);
	}
	else
	{
		NumberMaskChange(objEvent);
	}
}

function MoneyMaskKeyPress(objEvent) {

	return true;

	var iKeyCode, strKey;

	var objInput = GetEventObject(objEvent);
	var iKeyCode = GetKeyCode(objEvent);
	
	strKey = String.fromCharCode(iKeyCode);

	if (isValidMoney(objInput.value)) {
		objInput.validValue = objInput.value;
		if (!reValidMoneyChars.test(strKey) && !reKeyboardChars.test(strKey) || (rePeriod.test(strKey) && objInput.value.indexOf(".") > 0)) {
			return false;
		}
	} else {
		objInput.value = objInput.validValue || "0.00";
		return false;
	}
}

function MoneyMaskChange(objEvent) {
	var objInput = GetEventObject(objEvent);

	if (!isValidMoney(objInput.value)) {
		objInput.value = objInput.validValue || "0.00";
		objInput.focus();
		objInput.select();
	} else {
		if (objInput.value.indexOf(".") >= 0) {
			if (objInput.value.indexOf(".") == 0)
			{
				objInput.value = "0" + objInput.value;
			}
			if (objInput.value.indexOf(".") == objInput.value.length-1) {
				objInput.value += "00";
			} else if (objInput.value.indexOf(".") == objInput.value.length-2) {
				objInput.value += "0";
			} else if (objInput.value.indexOf(".") != objInput.value.length-3) {
				objInput.value = objInput.value.substr(0,objInput.value.indexOf(".")+3);
			}
		} else {
			if (objInput.value == "")
				objInput.value = "0.00";
			else
				objInput.value += ".00";
		}
		objInput.validValue = objInput.value;
	}
}

function DateMaskChange(objEvent) {
	var objInput = GetEventObject(objEvent);

	if (!isValidDate(objInput.value)) {
		objInput.value = objInput.validValue || GetCurrentDate();
		objInput.focus();
		objInput.select();
		ShowAlert("../../Includes/Alert.aspx?Msg=Please enter a valid 'Needed By' date - YYYY-MM-DD");
	} else {
		objInput.validValue = objInput.value;
	}
}

function DateMaskChangeAffiliate(objEvent) {
	var objInput = GetEventObject(objEvent);

	if (!isValidDate(objInput.value)) {
		objInput.value = objInput.validValue || GetCurrentDate();
		objInput.focus();
		objInput.select();
		ShowAlert("../../../Includes/Alert.aspx?Msg=The date entered is not valid!  The Date should be in the following format: YYYY-MM-DD");
	} else {
		objInput.validValue = objInput.value;
	}
}

function GetCurrentDate() {
	var dt = new Date();

	var month = dt.getMonth()+1;
	if (Number(month) < 10)
		month = "0" + month;

	var day = dt.getDate();
	if (Number(day) < 10)
		day = "0" + day;

	return dt.getFullYear() + "-" + month + "-" + day;
}

function isValidMoney(strValue) {
	return reValidMoneyString1.test(strValue) || reValidMoneyString2.test(strValue);
}

function isValidDate(strValue) {
	return reValidDateString.test(strValue);
}


//========================================================================================================
//	added functions
//========================================================================================================

function AffiliatePrintPackingSlip(Orderid)
{
	window.document.forms['OrderDetailsForm'].action='../VendorOrders/PackingSlip.aspx?orderid='+Orderid;
	window.document.forms['OrderDetailsForm'].target='_blank';
	window.document.forms['OrderDetailsForm'].submit();
	window.document.forms['OrderDetailsForm'].target='_self';
	ButtonClicked=false;
	return false;
}

function AffiliateApproveClientOrder()
{
	window.document.forms['OrderDetailsForm'].action='../WorkInProgress/ApproveMyOrder.aspx';
	window.document.forms['OrderDetailsForm'].submit();
	return false;
}

function AffiliateForwardOrder()
{
	window.document.forms['OrderDetailsForm'].action='ForwardToVendor.aspx';
	window.document.forms['OrderDetailsForm'].submit();
	return false;
}

function AffiliateSendToSubcontractor(orderid)
{
	window.open("ChooseSubContractor.aspx?orderid=" + orderid, "_self");
	return false;
}

function DefaultOpenAd(newPageURL)
{
    window.open(newPageURL, "_blank","height=815, width=625, " + "resizable=no, scrollbars=yes, menubar=no, location=no, status=no");
}

function OpenHelpPage(newPageURL)
{
	window.open(newPageURL, "_blank", "height=580, width=720, resizable=yes, scrollbars=yes, menubar=no, location=no, status=no, toolbar=yes");
}

function ShowProgressBarSub3()
{
	OpenNewWindowCenter('../../../Includes/ProgressBar.aspx?a=a', 400, 180);
}

function ShowProgressBarSub2()
{
	OpenNewWindowCenter('../../Includes/ProgressBar.aspx?a=a', 400, 180);
}

function ShowProgressBarSub1()
{
	OpenNewWindowCenter('../Includes/ProgressBar.aspx?a=a', 400, 180);
}

function ShowProgressBar()
{
	OpenNewWindowCenter('ProgressBar.aspx?a=a', 400, 180);
}

function getQueryVariable(variable) 
{
	var query = window.location.search.substring(1);
	var vars = query.split("&");
  
	for (var i=0; i < vars.length; i++) 
	{
		var pair = vars[i].split("=");

		if (pair[0] == variable) 
		{
			return pair[1];
		}
	} 
  
	return null;
}

function getOpenerQueryVariable(variable) 
{
	var query = window.opener.location.search.substring(1);
	var vars = query.split("&");
  
	for (var i=0; i < vars.length; i++) 
	{
		var pair = vars[i].split("=");

		if (pair[0] == variable) 
		{
			return pair[1];
		}
	} 
  
	return null;
}

function getOpenerQueryVariable(variable) 
{
	var query = window.opener.location.search.substring(1);
	var vars = query.split("&");
  
	for (var i=0; i < vars.length; i++) 
	{
		var pair = vars[i].split("=");

		if (pair[0] == variable) 
		{
			return pair[1];
		}
	} 
  
	return null;
}

function UploadFileButtonClick()
{
	var uploadid = getQueryVariable("uploadid");

	if (uploadid == null)
	{
		//OpenNewWindowCenter('../Includes/ProgressBar.aspx?a=a&noclose=true', 400, 180);
		OpenNewWindowCenter('../Includes/ProgressBar.aspx?a=a', 400, 180);
	}
	else
	{
		//OpenNewWindowCenter('../Includes/ProgressBar.aspx?a=a&noclose=true&uploadid='+uploadid, 400, 180);
		OpenNewWindowCenter('../Includes/ProgressBar.aspx?a=a&uploadid='+uploadid, 400, 180);
	}
	
	window.document.forms[0].submit();
	
	return false;
}

function UploadFileButtonClick2()
{
	//OpenNewWindowCenter('../../Includes/ProgressBar.aspx?a=a&noclose=true', 400, 180);
	OpenNewWindowCenter('../../Includes/ProgressBar.aspx?a=a', 400, 180);
	window.document.forms[0].submit();
	
	return false;
}

function FileUploadFormSubmit()
{
	element = document.getElementById('FileUpload')
	
	if (element == null || element.value == null || element.value == "")
	{
		ShowAlert("../../Includes/Alert.aspx?Msg=Please select a file to upload!");
		ButtonClicked=false;
		return false;
	}
	
	//OpenNewWindowCenter('../../Includes/ProgressBar.aspx?a=a&noclose=true', 400, 180);
	OpenNewWindowCenter('../../Includes/ProgressBar.aspx?a=a', 400, 180);
	
	window.document.forms[0].submit();
	
	return false;
}

function FileUploadFormSubmitProof()
{
	var w = 400;
	var h = 180;
	var l = (screen.width - w) / 2;
	var t = (screen.height - h) / 2;
	
	element = document.getElementById('FileUpload')
	
	if (element == null || element.value == null || element.value == "")
	{
		ShowAlert("../../Includes/Alert.aspx?Msg=Please select a file to upload!");
		ButtonClicked=false;
		return false;
	}
	
	var f = element.value;
	f = f.substr(f.length - 4, 4);
	
	f = f.toLowerCase();
	
	if (f != ".pdf")
	{
		ShowAlert("../../Includes/Alert.aspx?Msg=Only PDF files (*.pdf) accepted!");
		ButtonClicked=false;
		return false;
	}

	//window.open('../../Includes/ProgressBar.aspx?a=a&noclose=true', "_blank", 'resizable=0, height='+h+',width='+w+',top='+t+',left='+l+'w');
	window.open('../../Includes/ProgressBar.aspx?a=a', "_blank", 'resizable=0, height='+h+',width='+w+',top='+t+',left='+l+'w');
	
	window.document.forms[0].submit();
	
	return false;
}

function FileUploadRequestFormSubmit()
{
	element = document.getElementById('UploadFileRequestForm_txtEmail')
	
	if (element == null || element.value == null || element.value == "")
	{
		ShowAlert("../../Includes/Alert.aspx?Msg=Please enter an e-mail address!");
		ButtonClicked=false;
		return false;
	}

	window.document.forms[0].submit();
	
	OpenNotification("../../Includes/Notification.aspx?Msg=The request has been sent to the e-mail address you specified for status check PENDING FILES.");
	
	return false;
}

function SelectSearchText()
{
	if (document.forms["SearchForm"].elements['SearchProductKeywords'] != null)
	{
		if (document.forms["SearchForm"].elements['SearchProductKeywords'].value == "Search all products")
		{
			document.forms["SearchForm"].elements['SearchProductKeywords'].value = "";
		}
	}
	return false;
}

function BlurSearchText()
{
	if (document.forms["SearchForm"].elements['SearchProductKeywords'] != null)
	{
		if (document.forms["SearchForm"].elements['SearchProductKeywords'].value == "")
		{
			document.forms["SearchForm"].elements['SearchProductKeywords'].value = "Search all products";
		}
	}
	return false;
}

function progBarRefresh()
{
	window.location = window.location + '&r=r';
}

function GeneratePieGraph()
{
	window.document.forms[0].action='ProductStatisticsGraph.aspx';
	window.document.forms[0].target='_blank';
	window.document.forms[0].submit();
	window.document.forms[0].target='_self';
	ButtonClicked = false;
	return false;
}

function QuotationOperationAddText(paper)
{
	var text;
	var note;
	var func;
	
	text = window.document.forms[0].txtCurrent.value;
	note = window.document.forms[0].txtNotes.value;
	
	if (paper == "true")
	{
		func = window.document.forms[0].EstimateDataName_EstimateDataNameIdDropDown.value;
	}
	else
	{
		func = window.document.forms[0].EstimateDataType_EstimateDataTypeIdDropDown.value;
	}
	
	if (func != null && func != "")
	{
		// first line without text doesn't need the linebreak
		if (text != "")
		{
			text += "\r\n";
		}
			
		text += func;
		
		if (note != null && note != "")
		{	
			text += " (";
			text += note;
			text +=")";
		}
		
		window.document.forms[0].txtCurrent.value = text;
		window.document.forms[0].txtNotes.value = "";
	}
}

function ForwardOrderClick()
{
	// check to make sure we have a supplier selected
	if (window.document.forms[0].SuppliersList_SupplierIdDropDown.value == '0')
	{
		ShowAlert("../../../Includes/Alert.aspx?Msg=Please select a vendor!");
	}
	else if (window.document.forms[0].UsersList_UserIdDropDown.value == '0')
	{
		ShowAlert("../../../Includes/Alert.aspx?Msg=Please select a user!");
	}
	else
	{
		var supplier = window.document.forms[0].SuppliersList_SupplierIdDropDown.value;
		ShowConfirmation('../../../Includes/Confirm.aspx?msg=100000&param=' + supplier);
	}
}

function ForwardOrderSubmit()
{
	window.opener.document.forms[0].submit();
	OpenNotification("Notification.aspx?Msg=The order has been sent and is waiting for acceptance.  See the Work In Progress, Orders to vendors, for details.");
	window.close();
}

function OpenQuotationOperation2(orderid, itemid, index, template, type)
{
	url = "?orderid=" + orderid + "&itemid=" + itemid + "&index=" + index + "&template=" + template;
	switch (type)
	{
		case ("prepress"):
			EditPrepressWindow('');
			break;
		case ("ink"):
			EditInkWindow();
			break;
		case ("paper"):
			EditPaperWindow(false);
			break;
		case ("printing"):
			OpenPressWindow();
			break;
		case ("digital"):
			OpenDigitalWindow();
			break;
		case ("bindery"):
			EditBinderyWindow('');
			break;
		case ("delivery"):
			EditDeliveryWindow('');
			break;
	}
}

function OpenQuotationOperation(Path)
{
	OpenNewWindowCenter(Path, 400, 380);
}

function OpenQuotationAddMultiProduct(Path)
{
	OpenNewWindowCenter(Path, 400, 400);
}

function OpenQuotationAddMultiPart(Path)
{
	OpenNewWindowCenter(Path, 400, 385);
}

function OpenNewWindowCenter(Path, w, h)
{
	var l = (screen.width - w) / 2;
	var t = (screen.height - h) / 2;
	window.open(Path, "_blank", "resizable=0, height=" + h + ",width=" + w + ",top=" + t + ",left=" + l + "w");
}

function OpenNewWindowCenterResizeable(Path, w, h)
{
	var l = (screen.width - w) / 2;
	var t = (screen.height - h) / 2;
	window.open(Path, "_blank", 'resizable=1, height=' + h + ',width=' + w + ',top=' + t + ',left=' + l + 'w');
}

// SHIPPING - handled by MaskChange (below)
function ShippingMaskKeyPress(objEvent)
{
	//ShippingMaskChange(objEvent);
	return true;
}


function VariableQuantityMaskKeyPress(objEvent)
{
	return NumberMaskKeyPress(objEvent);
}

function VariableQuantityMaskChange(objEvent)
{
	if (NumberMaskChange(objEvent) != false)
	{
		var qa = window.document.getElementById("QuantityA");
		var qb = window.document.getElementById("QuantityB");
		var qc = window.document.getElementById("QuantityC");
		
		var fQa = parseFloat(qa.value);
		var fQb = parseFloat(qb.value);
		var fQc = parseFloat(qc.value);
		
		var fPa = parseFloat(window.document.getElementById("PriceA").value);
		var fPb = parseFloat(window.document.getElementById("PriceB").value);
		var fPc = parseFloat(window.document.getElementById("PriceC").value);
		
		var pu  = window.document.getElementById("ProductUOM").value;
		
		var q = parseFloat(window.document.getElementById("VariableQuantity").value);
		
		var result = 0;
		
		if (pu == "Thousand" || pu == "Each")
		{
			if (q >= fQc && fQc != 0)
				result = fPc;
			else if (q >= fQb && fQb != 0)
				result = fPb;
			else
				result = fPa;
				
			window.document.getElementById("TotalOtherPrice").innerHTML = "  Total: $ " + (result * q);
		}
		else
		{
			var q_lo = 0;
			var q_hi = 0;
			var p_lo = 0;
			var p_hi = 0;
			
			if (q >= fQc && fQc != 0)
			{
				q_lo = fQc;
				p_lo = fPc;
				if (q >= fQc)
					q_hi = 0;
				else
				{
					p_hi = p_lo;
					q_hi = q_lo;
				}
			}
			else if (q >= fQb && fQb != 0)
			{
				q_lo = fQb;
				p_lo = fPb;
				q_hi = fQc;
				p_hi = fPc;
			}
			else if (q >= fQa && fQa != 0)
			{
				q_lo = fQa;
				q_hi = fQb;
				p_lo = fPa;
				p_hi = fPb;
			}
			else
			{
				p_lo = 0;
				q_lo = 0;
				q_hi = fQa;
				p_hi = fPa;
			}
			
			if (q_hi != 0)
			{
				var s = p_hi - p_lo;
				var e = q_hi - q_lo;
				var c = q - q_lo;
				var p = c / e;
				//window.alert("price_max: " + s + "  qty_max: " + e + "  qty_rng: " + c + "  qty_div: " + p);
				result = (s * p) + p_lo;
			}
			else
			{
				result = (p_lo / q_lo) * q;
			}
		}
		
		window.document.getElementById("VariablePrice").value = result;
		
		UpdateMoneyBox(window.document.getElementById("VariablePrice"));
		
		return true;
	}
	return false;
}


function ShippingMaskChange(objEvent)
{
	var objInput = GetEventObject(objEvent);

	if (!isValidMoney(objInput.value))
	{
		objInput.value = objInput.validValue || "0.00";
		objInput.focus();
		objInput.select();
	}
	else
	{
		if (objInput.value.indexOf(".") > 0)
		{
			if (objInput.value.indexOf(".") == objInput.value.length - 1)
			{
				objInput.value += "00";
			}
			else if (objInput.value.indexOf(".") == objInput.value.length - 2)
			{
				objInput.value += "0";
			}
			else if (objInput.value.indexOf(".") != objInput.value.length - 3)
			{
				objInput.value = objInput.value.substr(0, objInput.value.indexOf(".") + 3);
			}
		}
		else
		{
			objInput.value += ".00";
		}
		
		objInput.validValue = objInput.value;
	}
	
	gstOnShip = document.getElementById('GSTOnShipping');
	pstOnShip = document.getElementById('PSTOnShipping');
	//pstOnShip = document.getElementById('PSTOnShipping');
	
	oSubTotal = document.getElementById('oSubTotal');
	oSubTotalGst = document.getElementById('oSubTotalGst');
	oSubTotalPst = document.getElementById('oSubTotalPst');
	oShipping = document.getElementById('oShipping');
	Shipping  = document.getElementById('ShippingCharge');
	
	PstTaxGst  = document.getElementById('PstOnGst');
	
	var update = false;
	
	// Update the GST / PST
	if (gstOnShip.value == "true")
	{
		gstBox = document.getElementById('Gst');
		oGst = document.getElementById('oGST');
		gstPercent = document.getElementById('GstPercent');
		
		var p = parseFloat(gstPercent.value);
		var o = parseFloat(gstBox.value);
		var s = parseFloat(Shipping.value);
		var t = parseFloat(oShipping.value);
		var g = parseFloat(oGst.value);
		
		gstBox.value = (g + ((p / 100) * (s - t)));
		
		UpdateMoneyBox(gstBox);
		
		update = true;
	}
	
	if (pstOnShip.value == "true")
	{
		pstBox = document.getElementById('Pst');
		oPst = document.getElementById('oPST');
		pstPercent = document.getElementById('PstPercent');
		
		var p = parseFloat(pstPercent.value);
		var o = parseFloat(pstBox.value);
		var s = parseFloat(Shipping.value);
		var t = parseFloat(oShipping.value);
		var g = parseFloat(oPst.value);
		
		// pst should be charged on GST here
		if (PstTaxGst.value == "true")
		{
			ooGst = document.getElementById('oGST');
			oGstBox = document.getElementById('Gst');
			
			var og = parseFloat(ooGst.value);			// original Gst
			var gg = parseFloat(oGstBox.value);			// Current Gst
			
			var lg = gg - og;
			
			if (lg < 0)
				lg = 0;
			
			pstBox.value = (g + ((p / 100) * ((s - t) + lg)));
		}
		else
		{
			pstBox.value = (g + ((p / 100) * (s - t)));
		}
		
		UpdateMoneyBox(pstBox);
		
		update = true;
	}
	
	// Update the total here
	//if (update == true)
	{
		Total = document.getElementById('Total');
		pstBox = document.getElementById('Pst');
		gstBox = document.getElementById('Gst');
		
		var p = parseFloat(pstBox.value);
		var g = parseFloat(gstBox.value);
		var s = parseFloat(Shipping.value);
		var u = parseFloat(oSubTotal.value);
		
		Total.value = p + g + s + u;
		
		UpdateMoneyBox(Total);
	}
}

function UpdateMoneyBox(objInput) {

	if (!isValidMoney(objInput.value)) {
		objInput.value = objInput.validValue || "0.00";
		//objInput.focus();
		//objInput.select();
	} else {
		if (objInput.value.indexOf(".") >= 0) {
			
			if (objInput.value.indexOf(".") == 0)
			{
				objInput.value = "0" + objInput.value;
			}
			
			if (objInput.value.indexOf(".") == objInput.value.length-1) {
				objInput.value += "00";
			} else if (objInput.value.indexOf(".") == objInput.value.length-2) {
				objInput.value += "0";
			} else if (objInput.value.indexOf(".") != objInput.value.length-3) {
				objInput.value = objInput.value.substr(0,objInput.value.indexOf(".")+3);
			}
		} else {
			objInput.value += ".00";
		}
		objInput.validValue = objInput.value;
	}
}

function OpenNotification(Path)
{
	/*var w = 305;
	var h = 180;
	var l = (screen.width - w) / 2;
	var t = (screen.height - h) / 2;
	window.open(Path, "_blank", 'resizable=0, height='+h+',width='+w+',top='+t+',left='+l+'w');*/
	OpenNewWindowCenter(Path, 305, 180);
}

function ShowAlert(Path)
{
	/*var w = 305;
	var h = 180;
	var l = (screen.width - w) / 2;
	var t = (screen.height - h) / 2;
	window.open(Path, "_blank", 'resizable=0, height='+h+',width='+w+',top='+t+',left='+l+'w');*/
	OpenNewWindowCenter(Path, 305, 180);
}

function ShowConfirmation(Path)
{
	/*var w = 305;
	var h = 180;
	var l = (screen.width - w) / 2;
	var t = (screen.height - h) / 2;
	window.open(Path, "_blank", 'resizable=0, height='+h+',width='+w+',top='+t+',left='+l+'w');*/
	OpenNewWindowCenter(Path, 305, 180);
}

function EmailQuotation(Path)
{
	window.location = Path;
	OpenNotification("../../Includes/Notification.aspx?Msg=The estimate has been e-mailed to the client");
}

function SendQuotationToClient(Path)
{
	window.location = Path;
	OpenNotification("../../Includes/Notification.aspx?Msg=The estimate has been sent see the Pending Estimates section");
}

// affiliate places an order from a client to himself
function AffiliatePlaceEstimateOrder()
{
	if (window.document.forms["QuotationDetailsForm"].PoNumber+'' != 'undefined' && window.document.forms["QuotationDetailsForm"].PoNumber.value == '') {
		ShowAlert("../../Includes/Alert.aspx?Msg=Please enter a PO Number!");
		ButtonClicked=false;
		return false;
	} else if (!isValidDate(window.document.forms["QuotationDetailsForm"].NeededBy.value)) {
		ShowAlert("../../Includes/Alert.aspx?Msg=Please enter a valid Needed by Date!");
		ButtonClicked=false;
		return false;
	}

	window.document.forms['QuotationDetailsForm'].action='../Quotations/PlaceOrder.aspx';
	window.document.forms['QuotationDetailsForm'].submit();
	
	OpenNotification("../../Includes/Notification.aspx?Msg=The Order has been placed, check the Work In Progress for details");
	
	return false;
}

// affiliate places an order as the client to the selected supplier
function AffiliatePlaceEstimateOrderSupplier()
{
	if (window.document.forms[0].SuppliersList_SupplierIdDropDown.value == '0')
	{
		ShowAlert("../../Includes/Alert.aspx?Msg=Please select a vendor!");
		ButtonClicked = false;
		return false;
	} else if (window.document.forms[0].UsersList_UserIdDropDown.value == '0') {
		ShowAlert("../../Includes/Alert.aspx?Msg=Please select a user!");
		ButtonClicked = false;
		return false;
	} else if (window.document.forms["QuotationDetailsForm"].PoNumber+'' != 'undefined' && window.document.forms["QuotationDetailsForm"].PoNumber.value == '') {
		ShowAlert("../../Includes/Alert.aspx?Msg=Please enter a PO Number.");
		ButtonClicked=false;
		return false;
	} else if (!isValidDate(window.document.forms["QuotationDetailsForm"].NeededBy.value)) {
		ShowAlert("../../Includes/Alert.aspx?Msg=Please enter a valid Needed by Date!");
		ButtonClicked=false;
		return false;
	}

	window.document.forms['QuotationDetailsForm'].action='../Quotations/PlaceOrder.aspx';
	window.document.forms['QuotationDetailsForm'].submit();
	
	OpenNotification("../../Includes/Notification.aspx?Msg=The Order has been placed, check the Work In Progress for details");
	
	return false;
}


function ForwardCheckVendor()
{
	if (window.document.forms[0].SuppliersList_SupplierIdDropDown.value == '0')
	{
		ShowAlert("../../Includes/Alert.aspx?Msg=Please select a vendor!");
		//window.alert("Please select a vendor!");
		ButtonClicked = false;
		return false;
	}

	window.document.forms[0].submit();
	OpenNotification("../../Includes/Notification.aspx?Msg=The file has been forwarded to the chosen vendor.  An e-mail notification was sent to the vendor.");
	
	return false;
}


function progInfoGetFunction()
{
	if (xmlhttp.readyState == 4)
	{
		document.getElementById('progInfo').innerHTML = xmlhttp.responseText;
		
		var upload_done = document.getElementById('uploadDone');
		
		if (upload_done != null)
		{
			window.close();
		}
		else
		{
			var upload_timer = document.getElementById('uploadTimer');
			var t;
			
			if (upload_timer != null)
			{
				t = parseInt(upload_timer.value);
			}
			else
			{
				t = 2000;
			}
			
			setTimeout("progInfoGet()", t);
		}
	}
}

function progInfoGet()
{
	var uploadid = getQueryVariable('uploadid');

	// no xml http request support so use the classical progress bar
	if (xmlhttp == null)
	{
		if (uploadid != null)
		{
			window.location = "ProgressBar2.aspx?started=true&uploadid=" + uploadid;
		}
		else
		{
			window.location = "ProgressBar2.aspx?started=true";
		}
		return;
	}

	if (uploadid != null)
	{
		xmlhttp.open("GET", "ProgressRequestInfo.aspx?uploadid=" + uploadid, true);
	}
	else
	{
		xmlhttp.open("GET", "ProgressRequestInfo.aspx", true);
	}
	
	xmlhttp.onreadystatechange = progInfoGetFunction;
	xmlhttp.send(null);
}


function JobParentUpdate()
{
	/*if (xmlhttp == null)
	{*/
		window.opener.location = window.opener.location;		// normal refresh
	/*
	}
	else
	{
		var orderid = getQueryVariable('orderid');
		var itemid  = getQueryVariable('itemid');
		var index   = getQueryVariable('index');
		var template= window.opener.document.getElementById("template_hidden").value;

		// not asynchronous, block until the update happens
		xmlhttp.open("GET", "quotationItemRequest.aspx?orderid=" + orderid + "&itemid=" + itemid + "&index=" + index + "&template=" + template, false);
		xmlhttp.send(null);
		
		// this must happen, otherwise there is a problem, manually refresh the parent window
		if (xmlhttp.readyState == 4)
		{
			window.opener.document.getElementById("contents").innerHTML = xmlhttp.responseText;		
		}
		else
		{
			window.opener.location = window.opener.location;
		}
	}*/
}

//==============================================================================
//	Virtual Affiliate functions
//==============================================================================

function AffiliateReturnRequest()
{
	window.document.forms['EstimateDetailsForm'].action='ReturnQuotationPrices.aspx';
	window.document.forms['EstimateDetailsForm'].submit();
	OpenNotification("../../Includes/Notification.aspx?Msg=The prices have been returned.");
	return false;
}

function AffiliateCancelRequest()
{
	ShowConfirmation('../../Includes/Confirm.aspx?msg=130000&param=');
	ButtonClicked = false;
}

function AffiliateCancelRequest_Run()
{
	window.opener.document.forms['EstimateDetailsForm'].action='CancelQuotationRequest.aspx';
	window.opener.document.forms['EstimateDetailsForm'].submit();
}

function EstimateDataSubmit()
{
	var Name = window.document.getElementById("txtName");
	
	if (Name == null || Name.value == "")
	{
		ShowAlert("../../../Includes/Alert.aspx?Msg=Please enter a valid name!");
	}
	else
	{
		window.document.forms[0].submit();
	}
}

function AddEditEstimateDataGroup(cat, method)
{
	var Path = "OperationAddEdit.aspx?category=" + cat;
	
	if (method == "edit")
	{
		var Pid;
		
		if (cat == "group")
		{
			Pid = window.document.getElementById("lstGroup");
			
			if (Pid == null || Pid.value == null || Pid.value == "")
			{
				ShowAlert("../../../Includes/Alert.aspx?Msg=Please choose a Group from the list to edit!");
				return;
			}
		}
		else if (cat == "type")
		{
			Pid = window.document.getElementById("lstFunction");
			
			if (Pid == null || Pid.value == null || Pid.value == "")
			{
				ShowAlert("../../../Includes/Alert.aspx?Msg=Please choose a Function from the list to edit!");
				return;
			}
		}
		else if (cat == "name")
		{
			Pid = window.document.getElementById("lstName");
			
			if (Pid == null || Pid.value == null || Pid.value == "")
			{
				ShowAlert("../../../Includes/Alert.aspx?Msg=Please choose a Name from the list to edit!");
				return;
			}
		}
		
		Path += "&pid=" + Pid.value;
	}
	else
	{
		var Type;
		
		if (cat == "group")
		{
			Type = getQueryVariable('type');
		}
		else if (cat == "type")
		{
			var group = window.document.getElementById("lstGroup");
			Type = group.value;
		}
		else if (cat == "name")
		{
			var group = window.document.getElementById("lstFunction");
			Type = group.value;
		}
		
		Path += "&type=" + Type;
	}
	
	OpenNewWindowCenter(Path, 320, 160);
}

function OpenSmartRequest(type, oid, id)
{
	var w = 430;
	var h = 150;
	var url = "";
	
	if (type == "ink")
	{
		url = "SmartRequestInk.aspx?type=" + type + "&orderid=" + oid + "&id=" + id;
		h += 240;
	}
	else if (type != "paper")
	{
		url = "SmartRequestOperation.aspx?type=" + type + "&orderid=" + oid + "&id=" + id;
		h += 20;
	}
	else
	{
		url = "SmartRequestPaper.aspx?orderid=" + oid + "&id=" + id;
		h += 50;
	}
	
	var l = (screen.width - w) / 2;
	var t = (screen.height - h) / 2;

	window.open(url, "_blank", 'resizable=0, height='+h+',width='+w+',top='+t+',left='+l+'w');
}

function RestoreSmartRequest()
{
	RestoreSmartItem('prepress');
	RestoreSmartItem('color');
	RestoreSmartItem('paper');
	RestoreSmartItem('printing');
	RestoreSmartItem('bindery');
	RestoreSmartItem('delivery');
}

function SubmitSmartRequest()
{
	window.document.forms[0].submit();
	ShowProgressBarSub2();
}

function RestoreSmartItem(item)
{
	var divN = document.getElementById('DIV' + item + 'Note');
	var hidN = document.getElementById(item + 'NoteHidden');
	divN.innerHTML = hidN.value.replace(/\n/g, "<BR>");
}

function SaveSmartRequest()
{
	var type = getQueryVariable('type');
	
	var div2 = window.opener.document.getElementById('DIV' + type + 'Note');
	var hid2 = window.opener.document.getElementById(type + 'NoteHidden');

	var val2 = document.getElementById('txtNote');
	div2.innerHTML = val2.value.replace(/\n/g, "<BR>");
	
	var re = new RegExp("<BR>", "g");
	hid2.value = val2.value.replace(re, "\n");
}

function SmartRequestAddItem()
{
	var element = document.getElementById('EstimateType_EstimateDataTypeIdDropDown');
	var note = document.getElementById('txtNote');
	var nbox = document.getElementById('txtNoteBox');
	
	if (note.value != "")
	{
		note.value += "\n";
	}
	
	note.value += element.value;
	
	if (nbox.value != "")
	{
		note.value += " (";
		note.value += nbox.value;
		note.value += ")";
		nbox.value = "";
	}
}

function SmartRequestAddItem3()
{
	var element = document.getElementById('EstimateName_EstimateDataNameIdDropDown');
	var note = document.getElementById('txtNote');
	var nbox = document.getElementById('txtNoteBox');
	
	if (note.value != "")
	{
		note.value += "\n";
	}
	
	note.value += element.value;
	
	if (nbox.value != "")
	{
		note.value += " (";
		note.value += nbox.value;
		note.value += ")";
		nbox.value = "";
	}
}

function LoadSmartRequest()
{
	var type = getQueryVariable('type');
	var hid2 = window.opener.document.getElementById(type + 'NoteHidden');
	var val2 = document.getElementById('txtNote');
	
	if (val2.value == "" && hid2.value != "")
	{
		var re = new RegExp("<BR>", "g");
		val2.value = hid2.value.replace(re, "\n");
	}
}

function ShowItemChange(objEvent)
{
	if (chkShowItem.checked == true)
	{
		chkShowPrice.disabled   = false;
		chkShowDetails.disabled = false;
	}
	else
	{
		chkShowPrice.disabled   = true;
		chkShowDetails.disabled = true;
		chkShowPrice.checked    = false;
		chkShowDetails.checked  = false;
	}
}

function ValidateShowcase()
{
	var fName = window.document.getElementById("txtFirstName").value;
	var lName = window.document.getElementById("txtLastName").value;
	var Email = window.document.getElementById("txtEmail").value;
	var Phone = window.document.getElementById("txtPhoneNumber1").value;
	
	var Addr1  = window.document.getElementById("txtAddressLine1").value;
	var City   = window.document.getElementById("txtCity").value;
	var Postal = window.document.getElementById("txtPostalCode").value;
	
	if (fName == "")
		window.alert("Please enter your first name!");
	else if (lName == "")
		window.alert("Please enter your last name!");
	else if (Email == "")
		window.alert("Please enter your e-mail address!");
	else if (Phone == "")
		window.alert("Please enter your phone number!");
	else if (Addr1 == "")
		window.alert("Please enter a shipping address!");
	else if (City == "")
		window.alert("Please enter a shipping city!");
	else if (Postal == "")
		window.alert("Please enter a shipping postal code!");
	else
	{
		ShowProgressBarSub2();
		window.document.forms[0].submit();
	}
}


function ValidateGeneralRequest()
{
	var fName = window.document.getElementById("txtFirstName").value;
	var lName = window.document.getElementById("txtLastName").value;
	var Email = window.document.getElementById("txtEmail").value;
	var Phone = window.document.getElementById("txtPhoneNumber1").value;
	
	var Addr1  = window.document.getElementById("txtAddressLine1").value;
	var City   = window.document.getElementById("txtCity").value;
	var Postal = window.document.getElementById("txtPostalCode").value;
	
	if (fName == "")
		window.alert("Please enter your first name!");
	else if (lName == "")
		window.alert("Please enter your last name!");
	else if (Email == "")
		window.alert("Please enter your e-mail address!");
	else if (Phone == "")
		window.alert("Please enter your phone number!");
	/*else if (Addr1 == "")
		window.alert("Please enter a shipping address!");
	else if (City == "")
		window.alert("Please enter a shipping city!");
	else if (Postal == "")
		window.alert("Please enter a shipping postal code!");*/
	else
	{
		var uploadid=getQueryVariable("uploadid");
		OpenNewWindowCenter('../Includes/ProgressBar.aspx?a=a&uploadid=' + uploadid, 400, 180);
		window.document.forms[0].submit();
	}
}

function ValidateSmartRequest()
{
	var fName = window.document.getElementById("txtFirstName").value;
	var lName = window.document.getElementById("txtLastName").value;
	var Email = window.document.getElementById("txtEmail").value;
	var Phone = window.document.getElementById("txtPhoneNumber1").value;
	
	var Addr1  = window.document.getElementById("txtAddressLine1").value;
	var City   = window.document.getElementById("txtCity").value;
	var Postal = window.document.getElementById("txtPostalCode").value;
	
	if (fName == "")
		window.alert("Please enter your first name!");
	else if (lName == "")
		window.alert("Please enter your last name!");
	else if (Email == "")
		window.alert("Please enter your e-mail address!");
	else if (Phone == "")
		window.alert("Please enter your phone number!");
	/*else if (Addr1 == "")
		window.alert("Please enter a shipping address!");
	else if (City == "")
		window.alert("Please enter a shipping city!");
	else if (Postal == "")
		window.alert("Please enter a shipping postal code!");*/
	else
	{
		var uploadid=getQueryVariable("uploadid");
		OpenNewWindowCenter('../../Includes/ProgressBar.aspx?a=a&uploadid=' + uploadid, 400, 180);
		window.document.forms[0].submit();
	}
}

function AffiliateMultiProductPost()
{
	var pc = window.document.getElementById("Categories_ProductCategoryIdDropDown");
	var pt = window.document.getElementById("Products_ProductTypeIdDropDown");
	
	if (pc == null || pc.value=="" || pc.value==0)
	{
		window.alert("Please select a product category");
		return false;
	}
	else if (pt == null || pt.value=="" || pt.value==0)
	{
		window.alert("Please select a product type");
		return false;
	}
	
	return true;
}

function AffiliateEstimatePaperPost()
{
	var pn = window.document.getElementById("PaperNames");
	
	if (pn == null || pn.value=="" || pn.value <= 0)
	{
		window.alert("Please select a paper!");
		return false;
	}
	
	return true;
}

function AffiliateEstimateDefinitionPost(name)
{
	var pc = window.document.getElementById(name + "Group_EstimateDataGroupIdDropDown");
	var pt = window.document.getElementById(name + "Type_EstimateDataTypeIdDropDown");
	
	if (pc == null || pc.value=="" || pc.value<=0)
	{
		window.alert("Please select a group");
		return false;
	}
	else if (pt == null || pt.value=="" || pt.value<=0)
	{
		window.alert("Please select a " + name);
		return false;
	}
	
	return true;
} 

//=============================================================================================================
//	FileTransfer2
//=============================================================================================================

function AddAdditionalFile()
{
	document.getElementById("AdditionalFileCount").value = afCount;
	
	var tbl = document.getElementById("AdditionalFiles");
	var tbody = tbl.getElementsByTagName("TBODY")[0];
	var row = document.createElement("TR");
	var col = document.createElement("TD");
	var col2= document.createElement("TD");
	var inf = document.createElement("INPUT");
	
	inf.type= "file";
	inf.id  = "afile_" + afCount;
	inf.name= inf.id;
	inf.size= 30;
	
	col.appendChild(inf);
	row.appendChild(col);
	tbody.appendChild(row);
	
	afCount++;
}

function RemoveAdditionalFile()
{
	var tbl = document.getElementById("AdditionalFiles");
	
	if (tbl.rows.length > 1)
	{
		tbl.deleteRow(tbl.rows.length - 1);
	}
}


function PostQuickProcess()
{
	var state = getQueryVariable("state");
	window.document.forms[0].action='PostQuickProcess.aspx?state=' + state;
	window.document.forms[0].submit();
}

function filterQueryVariable(variable)
{
	if (getQueryVariable(variable) != null)
	{
		// filter out query variable
		var query = window.location.search.substring(1);
		var vars = query.split("&");
		var new_location = window.location.toString().split("?")[0];
	  
		for (var i=0; i < vars.length; i++) 
		{
			var pair = vars[i].split("=");

			if (pair[0] != variable) 
			{
				if (i == 0)
					new_location += "?";
				else
					new_location += "&";
					
				new_location += pair[0] + "=" + pair[1];
			}
		} 
		
		return new_location;
	}
	return window.location;
}

function ScheduleShowHidePrepress()
{
	if (getQueryVariable("hide_prepress") != null)
	{
		var loc = filterQueryVariable("hide_prepress");
		window.location = loc;
	}
	else
	{
		window.location = window.location + "&hide_prepress=true";
	}
}

function ScheduleShowHidePress()
{
	if (getQueryVariable("hide_press") != null)
	{
		var loc = filterQueryVariable("hide_press");
		window.location = loc;
	}
	else
	{
		window.location = window.location + "&hide_press=true";
	}
}

function ScheduleShowHideFinishing()
{
	if (getQueryVariable("hide_finishing") != null)
	{
		var loc = filterQueryVariable("hide_finishing");
		window.location = loc;
	}
	else
	{
		window.location = window.location + "&hide_finishing=true";
	}
}

function ScheduleShowHideDelivery()
{
	if (getQueryVariable("hide_delivery") != null)
	{
		var loc = filterQueryVariable("hide_delivery");
		window.location = loc;
	}
	else
	{
		window.location = window.location + "&hide_delivery=true";
	}
}


function ScheduleGoDirect(loc)
{
	var type = getQueryVariable("type");
	var hili = getQueryVariable("highlight");
	window.location = "Schedule.aspx?type=" + type + "&date=" + loc + "&highlight=" + hili;
}

function ScheduleGoDirect2(loc)
{
	window.location = "Schedule2.aspx?date=" + loc;
}

function ScheduleGoDirect3(loc)
{
	window.location = "Schedule3.aspx?date=" + loc;
}

//=============================================================================================================
//	XMLHttpRequest
//=============================================================================================================
/*
// Synchronous
function SyncHttpGetRequest(request_url, result_element_id, opener)
{
	window.alert("Sync Request");
	window.alert("asdf=" + result_element_id);
	
	if (xmlhttp == null)
	{
		window.alert("This application does not support your browser version.");
	}
	else
	{
		window.alert("Sync Request Get");
		
		xmlhttp.open("GET", request_url, false);	// not asynchronous, block until the update happens
		xmlhttp.send(null);
		
		window.alert("Sync Request Done");
		
		// this must happen, otherwise there is a problem
		if (xmlhttp.readyState == 4)// && xmlhttp.status == 200)
		{
			window.alert(xmlhttp.responseText);

			var element;

			if (opener == false)
			{
				element = document.getElementById(result_element_id);
			}
			else
			{
				element = window.opener.document.getElementById(result_element_id);
			}
			
			window.alert(element.id);
			
			element.innerHTML = xmlhttp.responseText;
			
			window.alert("test");
		}
		else
		{
			window.alert("SyncHttpRequest - Failed!");	
		}
	}
}
*/

function NewXMLHttpRequest()
{
	xmlhttp = null;
	if (xmlhttp == null)
	{
		try 
		{
			xmlhttp = new XMLHttpRequest();
			xmlhttp_reset = true;
		}
		catch (e)
		{
			try 
			{
				xmlhttp = new ActiveXObject("Msxml2.XMLHTTP.3.0");
			}
			catch (ee)
			{
				try 
				{
					xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
				}
				catch (eee)
				{
					try
					{
						xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
					}
					catch(eeee)
					{
						xmlhttp = null;
					}
				}
			}
		}
	}
}

// Asynchronous - do not block (set loading messages manually)
function ASyncHttpGetRequest(request_url, result_element_id, func_callback)
{
	NewXMLHttpRequest();
	if (xmlhttp == null)
	{
		window.alert("This application does not support your browser version.");
	}
	else
	{
		xmlhttp.open("GET", request_url, true);
		xmlhttp.onreadystatechange = function()
		{
			if (xmlhttp.readyState == 4)
			{
				if (result_element_id != null && result_element_id != "")
				{
					//if (xmlhttp.status == 200)
					{
						window.document.getElementById(result_element_id).innerHTML = xmlhttp.responseText;
					}
					//else
					{
					//	window.document.getElementById(result_element_id).innerHTML = "ERROR OCCURRED: (" + xmlhttp.status + ") " + xmlhttp.statusText;
					}
				}
				
				if (func_callback != null && func_callback != "")
				{
					setTimeout(func_callback, 1);
				}
			}
			
		}
		// Not supported by Opera 8.0
		//xmlhttp.setRequestHeader('Accept','message/x-formresult');
		xmlhttp.send(null);
	}
}



function ASyncHttpGetRequestOpener(request_url, result_element_id, func_callback)
{
	NewXMLHttpRequest();
	if (xmlhttp == null)
	{
		window.alert("This application does not support your browser version.");
	}
	else
	{
		xmlhttp.open("GET", request_url, true);
		xmlhttp.onreadystatechange = function()
		{
			if (result_element_id != null && result_element_id != "")
			{
				if (xmlhttp.readyState == 4)
				{
					if (xmlhttp.status == 200)
					{
						if (func_callback != null && func_callback != "")
						{
							setTimeout(func_callback, 1);
						}
						
						if (result_element_id != null && result_element_id != "")
						{
							window.opener.document.getElementById(result_element_id).innerHTML = xmlhttp.responseText;
						}
					}
					else
					{
						window.document.getElementById(result_element_id).innerHTML = "ERROR OCCURRED: (" + xmlhttp.status + ") " + xmlhttp.statusText;
					}
					
					setTimeout("window.close();", 1000);
				}
			}
		}
		// Not supported by Opera 8.0
		//xmlhttp.setRequestHeader('Accept','message/x-formresult');
		xmlhttp.send(null);
	}
}


