﻿// JScript File
Ajax.Commands.OrderSummary=function(elementId, ajaxCommand, cmdCounter){
	this.priority=net.CommandQueue.PRIORITY_IMMEDIATE;
	this.type=net.CommandQueue.TYPE_SINGLEPROCESS;
	this.id=cmdCounter;
	this.ajaxCommand = ajaxCommand;
	this.elementId = elementId;
	var cmdParams = elementId.toString().split('|');
	this.orderId = cmdParams[0];
	this.consumerStep = cmdParams[1];
	this.action = cmdParams[2];
    	this.tipAmount = cmdParams[3];	
	this.fromVendorWebsite = cmdParams[4];	
}

Ajax.Commands.OrderSummary.prototype.QueryStringVariables=function(){
    var commandVariables = new Hashtable();
    commandVariables.put("orderId", this.orderId);
    commandVariables.put("tipAmount", this.tipAmount);
    commandVariables.put("consumerStep", this.consumerStep);  
    commandVariables.put("fromVendorWebsite", this.fromVendorWebsite);  
    commandVariables.put("action", this.action);
    return commandVariables;
}

Ajax.Commands.OrderSummary.prototype.ParseResponse=function(docEl){
    var attrs = docEl.attributes;
    var status = attrs.getNamedItem('status').value;
    var message = attrs.getNamedItem('message').value;       

    if(status == 'success') {
	net.Base.ReleaseQueue(); 
	var action = attrs.getNamedItem('action').value;
	var consumerStep =  attrs.getNamedItem('ConsumerStep').value;
	var orderId  =  attrs.getNamedItem('OrderId').value;
	var vendorLocationId  =  attrs.getNamedItem('VendorLocationId').value;
	var orderLinesCount = parseFloat(attrs.getNamedItem('OrderLinesCount').value);
	var orderTotalsAttrs=docEl.childNodes[0].attributes;
	document.getElementById('orderId').value = orderId;
	var tipDropDownHtml = attrs.getNamedItem('tipDropDownHtml').value;
	var grandTotal = orderTotalsAttrs.getNamedItem('GrandTotal').value;
	
	document.getElementById("OrderTotals").innerHTML = GetTotalsHTML(orderTotalsAttrs,orderLinesCount,orderId,consumerStep,tipDropDownHtml);
	
	document.getElementById("FormAction").innerHTML = GetFormActionHTML(orderTotalsAttrs,orderLinesCount,orderId, consumerStep,docEl);        
     
	var HTMLNode = docEl.getElementsByTagName('OrderLinesDetails');       
	document.getElementById("OrderDetailTable").innerHTML = GetDetailsHTML(HTMLNode,orderLinesCount,orderId,consumerStep, vendorLocationId);
	
	document.getElementById("Favs").innerHTML = GetOptionsHTML(orderLinesCount,consumerStep);
	if (orderLinesCount > 0 && consumerStep == "3") {
	    document.getElementById("fixednextstep").innerHTML = "<p class='subtotal'>Order Subtotal: " + grandTotal + " <span>(<a href='#Orderinfobox'>view details</a>)</span></p><h4 class=\"button\"><a href=\"javascript:MakeSureTheyDidntClickSubmitAlreadyThenPost(document.pageForm,'UpdateConsumerStep3.m');\" name=\"updateStep3Link\" id=\"A1\" title=\"Proceed to the next step\">Next Step</a></h4>"      
	}
	
	//Delete only if any address validation message was displayed...
	var alertMessage = document.getElementById("AlertMessage");	
	if(alertMessage != null) {	
	    if(alertMessage.style.display == 'block') {
		document.getElementById("AlertMessage").style.visibility="hidden";
		document.getElementById("AlertMessage").style.display="none";	
	    }
	}	
    }
}

function FormatTipAmounts(tipAmount)
{
    var  formatedTipAmt = tipAmount.toString();
    try
    {
	var timAmtLen = tipAmount.toString().split('.');
	switch(timAmtLen.length)
	{
	    case 1:{
		    formatedTipAmt = tipAmount.toString() + '.00';
		    break;
		}
	    case 2: {
		    if(timAmtLen[1].length == 1) {
			formatedTipAmt = tipAmount.toString() + '0';
			}		    
		    break;   
		}
	}
    }
    catch(err)
    {
	alert(err);
    }    
    return formatedTipAmt;
}


function GetFormActionHTML(attrs,orderLinesCount,orderId,consumerStep,docEl) {
    var html = "";
    var pathAdjust = document.getElementById('pathAdjust').value;
    if (consumerStep == "3") {
	if(orderLinesCount > 0) {
	    html += "<a href=\"javascript:MakeSureTheyDidntClickSubmitAlreadyThenPost(document.pageForm,'" + pathAdjust + "UpdateConsumerStep3.m');\" name='updateStep3Link' id='updateStep3Link' title='Proceed to the next step'>";
	    html += "<img src='" + pathAdjust +"../images/Consumer/button_nextstepbig.gif' width='190' height='83' alt='Next Step' class='arrow' /></a>";
	} else {
	    html += "<p class='emptyorder'>Click a menu item to add it to your order.</p>";
	} 
    } else if (consumerStep == "4") {
    var showTerms = attrs.getNamedItem('ShowTermsOfUse').value;
    if (showTerms == 'True') {
        var checkd = (attrs.getNamedItem('AgreeToTerms').value == 'True') ? 'checked ' : '';
        html += "<div id='termscheckbox'>"
        html += "<input id='AgreeToTerms' name='AgreeToTerms' type='hidden' class='hidden' value='Y' class='billingcheckbox' />";
        html += "<p>By submitting your order, you agree to the <a href='conditions.html?height=360&width=660' class='smoothbox' title='Read our Terms of Use'>Terms of Use</a>.</p>";
        html += "</div>";

    }

    var cultureSensitiveFavText = document.forms.pageForm.cultureSensitiveFavoriteText.value;
	html += "<div id='checkboxarea'>";
	html += "  <label for='SaveFavoriteOption'><input type='checkbox' onClick=\"javascript:toggleSaveFavorite()\" name='SaveFavoriteOption' id='SaveFavoriteOption' />Save Order as a " + cultureSensitiveFavText + "</label>";
	html += "</div><!--checkboxarea-->";

	var favName = attrs.getNamedItem('FavName').value;
	if (favName.length == 0) {
	    favName = "Name Your " + cultureSensitiveFavText;
	}
	html += "<div id='SaveFavoriteInput' name='SaveFavoriteInput' style='display: none;'>"
	html += "  <input type='text' name='favoriteName' id='favoriteName' onfocus=\"javascript:ClearFav()\" size='18'";
	html += "  value='" + favName + "' />";
	html += "</div>";
	
		if (consumerStep == "4" && docEl.childNodes[2] != null) {  
           var ecoToGo=docEl.childNodes[2];
           var ecoToGoAttrib = ecoToGo.attributes;  
           var VendorSupportsEcoToGo = ecoToGoAttrib.getNamedItem('VendorSupportsEcoToGo').value;
           var Text = ecoToGoAttrib.getNamedItem('Text').value;
            html +=  "<div id=\"EcoFriendly\"><p class=\"learnmore\">Make your order eco-friendly <span><a href=\"Help.m#EcoFriendly\" onClick=\"window.open(this.href, 'popupwindow', 'width=1000,height=760,scrollbars,resizable'); return false;\" title=\"Learn more about making your SeamlessWeb order eco-friendly\">Learn more &raquo;</a></span></p>";
            if(VendorSupportsEcoToGo == "true") {
                var ecoToGoLine1 = ecoToGo.childNodes[0].attributes; 
	            VendorSupportsEcoToGo = ecoToGoLine1.getNamedItem('VendorSupportsEcoToGo').value;
	            var EcoToGoOrder = ecoToGoLine1.getNamedItem('EcoToGoOrder').value;
	            var AjaxCommand = ecoToGoLine1.getNamedItem('AjaxCommand').value;
	            var Text = ecoToGoLine1.getNamedItem('Text').value;
     
                html +=  "<label><input " + VendorSupportsEcoToGo + " type=\"radio\"" + EcoToGoOrder + " id=\"ecoToGoTrue\" name=\"EcoToGoOrder\" value=\"Y\" class=\"checkbox\" onclick=\"javascript:CreateCommand('" + AjaxCommand + "','');\" />" + Text + "</label>";
             
                var ecoToGoLine2 = ecoToGo.childNodes[1].attributes; 
	            VendorSupportsEcoToGo = ecoToGoLine2.getNamedItem('VendorSupportsEcoToGo').value;
	            EcoToGoOrder = ecoToGoLine2.getNamedItem('EcoToGoOrder').value;
	            AjaxCommand = ecoToGoLine2.getNamedItem('AjaxCommand').value;
	            Text = ecoToGoLine2.getNamedItem('Text').value;
            	
                html +=  "<label><input " + VendorSupportsEcoToGo + " type=\"radio\"" + EcoToGoOrder + " id=\"ecoToGoTrue\" name=\"EcoToGoOrder\" value=\"N\" class=\"checkbox\" onclick=\"javascript:CreateCommand('" + AjaxCommand + "','');\" />" + Text + "</label>";
            } else {
               html += "<p class=\"nogo\">" + Text + "</p>";
            }
            html += "</div>";
        }
	
	html += "<div id='submit_order_div' style='text-align:center;'>";
	html += "<a href=\"javascript:MakeSureTheyDidntClickSubmitAlreadyThenPost(document.pageForm, 'UpdateCheckout.m');\" name='updateCheckoutLink' id='updateCheckoutLink'>";
	html += "<img src='../images/Consumer/button_submitorderbig.gif' width='190' height='83' alt='Submit Order' class='arrow' /></a>";
	html += "</div>";
	


    }    
    
    return html;    
}

function GetTotalsHTML(orderTotalsAttrs,orderLinesCount,orderId,consumerStep,tipDropDownHtml) {
   var html = "";     
   html += "<table border='0' cellspacing='0' cellpadding='0' class='DataTable'>";
   html += "<colgroup>";
   html += "<col class='maincol' />";
   html += "<col class='sidecol' />";
   html += "</colgroup>";
   html += "<tbody>";

   html += " <tr class='noline'><td class='main'>Food/Beverage Total:</td>";
   var productTotalAmt = orderTotalsAttrs.getNamedItem('ProductTotalAmt').value;
   html += "<td>" + productTotalAmt + "</td></tr>";       
   
   var IsTaxIncludedInAmounts = orderTotalsAttrs.getNamedItem('IsTaxIncludedInAmounts').value;
   var taxAmt = orderTotalsAttrs.getNamedItem('TaxAmt').value;
   if(IsTaxIncludedInAmounts == 'False')
   {
	html += "<tr class='noline'><td class='main'>Sales Tax:</td><td>" + taxAmt + "</td></tr>";	    	    
   }
   if (orderTotalsAttrs.getNamedItem('AdditionalTax') != null) {
    var AdditionalTaxes = orderTotalsAttrs.getNamedItem('AdditionalTax').value;
    html += "<tr class='noline'><td class='main'>Additional Taxes:</td><td>" + AdditionalTaxes + "</td></tr>";

    var AdditionalTaxesList = orderTotalsAttrs.getNamedItem('AdditionalTaxList').value;
    AdditionalTaxesList = AdditionalTaxesList.split('|');
    for (var i = 0; i < AdditionalTaxesList.length;  i++) {
        html += "<tr class='noline'><td class='main'>&nbsp;&nbsp;&nbsp;&nbsp;- " + AdditionalTaxesList[i] + "</td><td></td></tr>";
    }
   }
          
   var deliveryType = orderTotalsAttrs.getNamedItem('DeliveryType').value;
   var deliveryFeeAmount = orderTotalsAttrs.getNamedItem('DeliveryFeeAmount').value;
   var deliveryFeeAmountValue = parseFloat(deliveryFeeAmount.slice(1));
   if(deliveryType == 'Delivery' && deliveryFeeAmountValue > 0)
   {
	var groupOrder = orderTotalsAttrs.getNamedItem('IsGroupOrder').value;
	var deliveryFeeIsPercent = orderTotalsAttrs.getNamedItem('DeliveryFeeIsPercent').value;
	if(groupOrder == 'True' && deliveryFeeIsPercent == 'N')
	{
	    html += "<tr><td class='GroupOrderDeliveryFeeDisplay'>Delivery Fee:</td><td class='GroupOrderDeliveryFeeDisplay'>";
	    html += deliveryFeeAmount;
	    html += "</td></tr><tr><td colspan='2' class='GroupOrderDeliveryFeeNote'>(Between all orders on the group order)</td></tr>";   
	}
	else
	{
	    html += "<tr class='noline'><td class='main'>Delivery Fee:</td><td>" + deliveryFeeAmount + "</td></tr>"; 
	}       
   }
   
   var IsShowTransactionFee = orderTotalsAttrs.getNamedItem('IsShowTransactionFee').value; 
   if(IsShowTransactionFee == 'True')
   {
	var TransactionFee = orderTotalsAttrs.getNamedItem('TransactionFee').value;	    
	html += "<tr class='noline'><td class='main'>Transaction fee:</td><td>" + TransactionFee + "</td></tr>";
    }

    var IsShowPresentationChargeTotal = orderTotalsAttrs.getNamedItem('IsShowPresentationChargeTotal').value;
    if(IsShowPresentationChargeTotal == 'True')
    {
	var PresentationCharge = orderTotalsAttrs.getNamedItem('PresentationCharge').value;
	html += "<tr class='noline'><td class='main'>Upgraded Presentation Charge:</td><td>" + PresentationCharge + "</td></tr>";
    }

    var showPercentDiscount = orderTotalsAttrs.getNamedItem('IsShowPercentDiscount').value;
    var showFixedDiscount = orderTotalsAttrs.getNamedItem('IsShowFixedDiscount').value;
    var showVolumeDiscount = orderTotalsAttrs.getNamedItem('IsShowVolumeDiscount').value;
    var DiscountPercent = orderTotalsAttrs.getNamedItem('DiscountPercent').value;
    var DiscountAmt = orderTotalsAttrs.getNamedItem('DiscountAmt').value;	
    var EffectiveDiscount = orderTotalsAttrs.getNamedItem('EffectiveDiscount').value;
    	
    if(showPercentDiscount == 'True')
	html += "<tr class='noline'><td class='main'>Discount Amount:</td><td>" + DiscountPercent + "</td></tr>";

    if(showFixedDiscount == 'True' || showVolumeDiscount == 'True')
	html += "<tr class='noline'><td class='main'>Discount Amount:</td><td>" + DiscountAmt + "</td></tr>";
        
    if(showPercentDiscount == 'True' || showFixedDiscount == 'True' || showVolumeDiscount == 'True')
	html += "<tr class='noline'><td class='main'>Effective Discount:</td><td>" + EffectiveDiscount + "</td></tr>";
    
    html += tipDropDownHtml;
    
    var grandTotal = orderTotalsAttrs.getNamedItem('GrandTotal').value;
    if(showPercentDiscount == 'True' || showFixedDiscount == 'True' || showVolumeDiscount == 'True'){
	html += "<tr><td class='main'><div id='OrderSubtotal'>Discounted total:</div></td><td><div id='OrderSubtotalPrice'>" + grandTotal + "</div></td></tr>";
    }else {
	html += "<tr class='subtotal'><td class='main'><div id='Div1'>Subtotal:</div></td><td><div id='Div2'>" + grandTotal + "</div></td></tr>";
    }        
    
    // Promo code
    if(consumerStep == "4") {
	var promoCode = orderTotalsAttrs.getNamedItem('PromoCode').value;
	html += "<tr><td class='promotion' colspan='2'>";
	html += "<label for='promotionCode'>Promo code:</label>";
	html += "<input class='TextSmall' type='text' name='promotionCode' id='promotionCode' value='" + promoCode + "' />";
	html += "  <a href=\"javascript:ApplyCouponOnly();doPost(document.pageForm,'UpdateCheckOut.m');\">Apply</a>";
	html += "</td></tr>";
    }
    
    html += "</tbody>";
    html += "</table>";

    return html;
}

function GetDetailsHTML(detailNode,orderLinesCount,orderId,consumerStep,vendorLocationId) {
    var html = "";
    if(orderLinesCount > 0 && 
	(consumerStep == "3" || consumerStep == "4"))
    {
	html += "<div id='OrderDetails'><h5>Order Details</h5>";
	
	//DetailNode Attributes....
	var detailNodeAttrs = detailNode[0].attributes;	
	var vendorType = detailNodeAttrs.getNamedItem('VendorType').value;
		
	//OrderLines
	html += "<ul>";
	var orderLineNode = detailNode[0].childNodes[0];
	for(var i=0;i<orderLineNode.childNodes.length;i++) {
	    var orderLineNodeAttrs = orderLineNode.childNodes[i].attributes;
	    var quantity = orderLineNodeAttrs.getNamedItem('Quantity').value;
	    var productName = orderLineNodeAttrs.getNamedItem('ProductName').value;
	    var productId = orderLineNodeAttrs.getNamedItem('ProductId').value;
	    var categoryId = orderLineNodeAttrs.getNamedItem('CategoryId').value;
	    var price = orderLineNodeAttrs.getNamedItem('Price').value.slice(1);
	    var lineId = orderLineNodeAttrs.getNamedItem('LineId').value;	    
	    var cartItemCount = orderLineNodeAttrs.getNamedItem('CartItemCount').value;
	    var aggregatePrice = orderLineNodeAttrs.getNamedItem('AggregatePrice').value;
	    var formattedPrice = orderLineNodeAttrs.getNamedItem('FormattedPrice').value;
	    
	    // lime item
	    html += "<li class='itemprice'>" + formattedPrice + "</li>";
	    html += "<li>" + quantity +" "+ productName;
	    
		//  product options
		html += "<ul>";
		var menuOptionsNode = orderLineNode.childNodes[i].childNodes[0];
		for(var j=0;j<menuOptionsNode.childNodes.length;j++) {
		    var itemOption = menuOptionsNode.childNodes[j];
		    var optionName = itemOption.firstChild.nodeValue;
		    var optionPrice = itemOption.attributes.getNamedItem('price').value;
		    html += "<li>" + optionName +" "+ optionPrice + "</li>";		
		}  	    
		// line item actions
		html += "<li class='editdelete'>";
		var editHtml = "javascript:TB_special(";
		if (consumerStep == "3"){	    
		    editHtml += "'MenuItem.m?ProductId=" + productId + "&CategoryId=" + categoryId + "&Price=" + price + "&LineId=" + lineId + "&ConsumerStep=" + consumerStep + "&VendorLocationId=" + vendorLocationId + "&height=360&width=660');";
		}else{
		    editHtml += "'MenuItemSSL.m?ProductId=" + productId + "&CategoryId=" + categoryId + "&Price=" + price + "&LineId=" + lineId + "&ConsumerStep=" + consumerStep + "&VendorLocationId=" + vendorLocationId + "&height=360&width=660');";
		}
		    html += "<a href=\"" + editHtml + "\"" + " class='thickbox' name='itemEdit' id='itemEdit' runat='server' title='Edit this item'>Edit</a> / ";
		var deleteHtml = "javascript:CreateCommand('28','";
		    deleteHtml += "Delete|" + orderId + "|" + lineId + "|" + consumerStep + "' );" ;
		    html += " <a href=\"" + deleteHtml + "\"" + " name='deleteItem' id='deleteItem'>Delete</a>";
		html += "</li>";
		html += "</ul>";
	    
	    html += "</li>";
	}	

	html += "</ul>";
	html += "</div>";	
    } 
    else
    {
	html += "<div id='OrderDetails' />";
    }    
    return html;
}

function GetOptionsHTML(orderLinesCount,consumerStep) {
    var html = "";  
    var cultureSensitiveFavText = document.forms.pageForm.cultureSensitiveFavoriteText.value;
        if(document.forms.pageForm.AnonymousUser != null && document.forms.pageForm.IsRecognized != null) {
	    if (orderLinesCount > 0 && consumerStep == "3") {
	        html += "<h3 class='addfave'>";
	        html += "  <a href=\"javascript:ShowElement('saveFavorite2');\">Save Order as a " + cultureSensitiveFavText + "</a>";
	        html += "</h3>";

	        html += "<div id='saveFavorite2' style='display:none;'>";
	        html += "<input type='hidden' name='InfoPopup_saveType' id='InfoPopup_saveType' value='' />";
	        html += "<input type='hidden' name='InfoPopup_orderId' id='InfoPopup_orderId' value='' />";
	        html += "<input type='text' name='InfoPopup_name' id='InfoPopup_name' value='Name this " + cultureSensitiveFavText + "' onfocus=\"this.value='';\" />";
	        html += "<a href='\#' onclick=\"saveFavorite();HideElement('saveFavorite2');\">";
	        html += "<img src='../images/consumer/button_savefave.gif' alt='Save " + cultureSensitiveFavText + "' width='90' height='23' class='button' /></a>";
	        html += "<p><a href=\"javascript:HideElement('saveFavorite2');\">Cancel</a></p>";
	        html += "</div>";
	    }
	
	}
    return html;
}
