/***********************************************************************/
/* JS/BULLOCKCART.JS : THE BULLOCKCART ENGINE                          */
/* SUBWAY-CUSTOMIZED VERSION 1.0                                       */
/* COPYRIGHT(C) 2009-2011 SPINNAKER360 PTE LTD                         */
/* THIS SCRIPT MAY NOT BE REPRODUCED OR DISTRIBUTED WITHOUT PERMISSION */
/***********************************************************************/
var lastItem = null;	// Holder for "order last item again"

function showCart(status){
// showCart() : show the shopping cart
// PARAM status : response status code to show (if any)

	// (A) CHECK FOR ANY PROMPTS FIRST (OVER LIMIT, FULFILL EXPIRE)
	// IF ANOTHER POPUP IS ALREADY OPEN ... SET TO FIRE ONHIDE TO PREVENT CLASH OF TITANS
	var checkCart = function(){
		var data = { "action" : "checkPrompts" };
		var req = new Request({
			method: 'post',
			url: 'ajax_cart.php',
			async: false,
			onSuccess: function(responseText){
				var response = JSON.decode(responseText);
				if(response.status==0){
					popup.setMode("text", response.text);
					popup.show();
				}
			}
		}).post(data);
	};
	if(popup.open){ popup.onHide = checkCart; }
	else{ checkCart(); }

	// (B) UPDATE CART
	var data = { "action" : "showCart" };
	if(isFinite(status)){
		$extend(data, { "notify" : status });
	}
	var req = new Request({
		method: 'post', url: 'ajax_cart.php', async: false,
		onRequest: function(){
			$('menuContentsR').set("html", "<img src='images/spinnerSmall.gif' /> Retrieving...");
		},
		onSuccess: function(responseText){
			$('menuContentsR').set("html", responseText);
			/*
			var productDetailsToggle = $('menuContentsR').getElements('span[class=cartShowItemDetails]');
			if(productDetailsToggle!==undefined && productDetailsToggle!==null && productDetailsToggle!=""){
				var productDetails = $('menuContentsR').getElements('div[class=cartItemDetails]');
				if(productDetails!==undefined && productDetails!==null && productDetails!=""){
					productDetails.each(function(el, index){
						// Stupid IE8 engine cannot hide properly
						// var slide = new Fx.Slide(el).hide();
						var slide = new Fx.Slide(el).toggle();
						productDetailsToggle[index].addEvent('click', function(){
							if(slide.open){ this.set("html", "[Show Details]"); }
							else{ this.set("html", "[Hide Details]"); }
							slide.toggle();
						});
					});
				}
			}
			*/
			if(lastItem===null){
				$('lastitem').setStyle("display", "none");
			}
			initToolTip();
		}
	}).post(data);
}

function updateSneak(){
// updateSneak() : update the cart sneak peak

	var data = { "action" : "updateSneak" };
	var req = new Request({
		method: 'post', url: 'ajax_cart.php', async: false,
		onRequest: function(){ $('cartSneak').set("html", "UPDATING..."); },
		onSuccess: function(responseText){
			$('cartSneak').set("html", responseText);
		}
	}).post(data);
}

function resetCart(){
// resetCart() : reset the entire cart

	var ans = confirm("Are you sure?");
	if(ans){
		var data = { "action" : "resetCart" };
		var req = new Request({
			method: 'post', url: 'ajax_cart.php', async: false,
			onRequest: function(){
				popup.contents.set("html", "");
				//popup.contents.addClass("LM_loading");
				popup.contents.set("html", "<img src='images/ajax-loader.gif' /> Loading...");
			},
			onSuccess: function(responseText){
				showCart(responseText); updateSneak();
				lastItem = null;
				$('lastitem').disabled = true;
			}
		}).post(data);
	}
}

function setSMSFav(type, set){
// setSMSFav() : set SMS notification or Fav Order via AJAX
// PARAM type: [1] SMS or [2] FAV
//       set : set on / off

	var data = null;
	if(type=="SMS"){
		data = {
			"action" : "setSMS",
			"sms" : set
		};
	} else {
		data = {
			"action" : "setFAV",
			"fav" : set
		};
	}
	var req = new Request({
		method: 'post', url: 'ajax_cart.php', async: false,
		onRequest: function(){
			popup.contents.set("html", "");
			//popup.contents.addClass("LM_loading");
			popup.contents.set("html", "<img src='images/ajax-loader.gif' /> Loading...");
		},
		onSuccess: function(responseText){
			showCart(); updateSneak();
		}
	}).post(data);
}

function updateQty(productID, remove, silent){
// updateQty() : update quantity
// PARAM productID : product ID
//       remove : remove this item from the cart
//       silent : silent mode, do not update cart

	var qty = remove ? 0 : $('cartPopupQty_'+productID).value;
	if(isNaN(qty) || (qty==0 && !remove)) { alert("Please enter a valid quantity!"); }
	else {
		var data = {
			"action" : "updateQty",
			"productID" : productID,
			"qty" : qty
		};
		var req = new Request({
			method: 'post', url: 'ajax_cart.php', async: false,
			/*
			onRequest: function(){
				popup.contents.set("html", "");
				popup.contents.set("html", "<img src='images/ajax-loader.gif' /> Loading...");
			},
			*/
			onSuccess: function(responseText){
				if(!silent){
					showCart(responseText); updateSneak(); closeTip();
				}
			}
		}).post(data);
	}
}

function checkDiscount(code){
// checkDiscount() : check discount code

	var data = {
		"action" : "checkDiscount",
		"code" : code
	};
	var req = new Request({
		method: 'post', url: 'ajax_cart.php', async: false,
		onRequest: function() {
			$('cartDiscountCode').disabled = true;
			$('discountCodeStatus').set("html", "<img src='images/spinnerSmall.gif' /> Checking...");
		},
		onSuccess: function(responseText) {
			$('cartDiscountCode').disabled = false;
			if(responseText=="OK"){
				showCart(); updateSneak();
			}
			else if(responseText=="EXP"){ $('discountCodeStatus').set("html", "<span class='sysWarn'><img src='images/error.gif' /> Coupon expired.</span>"); }
			else{ $('discountCodeStatus').set("html", "<span class='sysWarn'><img src='images/error.gif' /> Invalid coupon.</span>"); }
		}
	}).post(data);
}

function setCompanyName(name){
// setCompanyName() : set the company name

	var data = {
		"action" : "setCoName",
		"name" : name
	};
	var req = new Request({
		method: 'post', url: 'ajax_cart.php', async: false,
		onRequest: function() {
			$('cartCompany').disabled = true;
		},
		onSuccess: function(responseText) {
			$('cartCompany').disabled = false;
		}
	}).post(data);
}

function processCheckout(process){
// processCheckout() : process checkout
// PARAM process : process to carry out

	// (1) PROCESSES
	var proceed = false; var data = null; var req = null;
	switch(process){
		// (PROCESS 1) SHOW CONFIRM LOCATION & PAYMENT MODE
		case 1:
			data = { "action" : "showCheckoutFulfill" };
			proceed = true;
			break;

		// (PROCESS 2) SHOW NEW / EXISTING CUSTOMER?
		case 2:
			data = { "action" : "showCheckoutSignin" };
			proceed = true;
			break;

		// (PROCESS 3) SHOW CC INFO
		case 3:
			location.href = "https://www.substogo.sg/checkout.php";
			break;

		// (PROCESS 4 - FOLLOW-UP OF PROCESS 2) NEW/LOGIN FORM
		case 4:
			var errmsg = "";
			// New account check
			if($('checkoutNew').checked){
				if($('checkoutFirstname').value.length<$('checkoutFirstnameMin').value){
					errmsg += "Please enter your given name.\n";
					$('checkoutFirstname').addClass("inputErr");
				} else { $('checkoutFirstname').removeClass("inputErr"); }
				if($('checkoutLastname').value.length<$('checkoutLastnameMin').value){
					errmsg += "Please enter your surname.\n";
					$('checkoutLastname').addClass("inputErr");
				} else { $('checkoutLastname').removeClass("inputErr"); }
				if($('checkoutEmail').value.length<$('checkoutEmailMin').value){
					errmsg += "Please enter your email.\n";
					$('checkoutEmail').addClass("inputErr");
				} else { $('checkoutEmail').removeClass("inputErr"); }
				if($('checkoutTel').value.length<$('checkoutTelMin').value || isNaN($('checkoutTel').value)){
					errmsg += "Please enter your contact no.\n";
					$('checkoutTel').addClass("inputErr");
				} else { $('checkoutTel').removeClass("inputErr"); }
			}
			// Anon sign in check
			if($('checkoutSignin').checked){
				var user = $('anon_login_email').value;
				var password = $('anon_login_password').value;
				if(user==""){
					errmsg += "Please enter your email.\n";
					$('anon_login_email').addClass("inputErr");
				} else { $('anon_login_email').removeClass("inputErr"); }
				if(password==""){
					errmsg += "Please enter your password.\n";
					$('anon_login_password').addClass("inputErr");
				} else { $('anon_login_password').removeClass("inputErr"); }
			}
			if($('checkoutAgree').checked===false){
				errmsg += "You must agree to the Terms of Use.";
			}

			if(errmsg){ alert(errmsg); }
			// Anon Sign-in
			else if($('checkoutSignin').checked){
				data = {
					"action" : "anonLoginCheck",
					"user" : $('anon_login_email').value,
					"pass" : $('anon_login_password').value
				};
				req = new Request({
					url: 'ajax_user.php', async: false,
					onRequest: function(){
						$('anonLoginStatus').set("html", "<img src='images/spinnerSmall.gif' /> Processing...");
					},
					onSuccess: function(response){
						// OK TO PROCEED WITH ANON LOGIN
						if(response=="OK"){
							data = {
								"action" : "anonLogin",
								"user" : $('anon_login_email').value
							};
							var loginReq = new Request({
								url: 'ajax_user.php', async: false,
								onSuccess: function(responseText){
									data = { "action" : "updateLogin" };
									var updateReq = new Request({
										method: 'post',
										url: 'ajax_user.php',
										async: false,
										onRequest: function(){
											$('loginBox').set('html', '');
										},
										onSuccess: function(responseText){
											$('loginBox').set('html', responseText);
										}
									}).post(data);
									processCheckout(1);
								}
							}).post(data);
						}
						// USER HAS DIFFERENT PRICEBOOK
						else if(response=="PRICEBOOK"){
							data = {
								"action" : "anonPricebook",
								"user" : $('anon_login_email').value,
								"pass" : $('anon_login_password').value
							};
							popup.setMode("ajax", "ajax_user.php", data);
							popup.show();
						}
						// WRONG USER/PASSWORD COMBO
						else{
							alert("Invalid user/password.");
							$('anonLoginStatus').set("html", "");
						}
					}
				}).post(data);
			}
			// New Registration
			else {
				data = {
					"action" : "checkEmail",
					"email" : $('checkoutEmail').value
				};
				req = new Request({
					url: 'ajax_user.php', async: false,
					onRequest: function(){
						$('checkoutAnonNext').disabled = true;
					},
					onSuccess: function(response){
						if(response=="1"){
							alert("Your email address has already been registered.");
							proceed = false;
							$('checkoutAnonNext').disabled = false;
						} else {
							data = {
								"action" : "showCheckoutFulfill",
								"register" : 1,
								"firstName" : $('checkoutFirstname').value,
								"lastName" : $('checkoutLastname').value,
								"email" : $('checkoutEmail').value,
								"tel" : $('checkoutTel').value
							};
							proceed = true;
						}
					}
				}).post(data);
			}
			break;

		// (PROCESS 5 - FOLLOW UP OF PROCESS 4) PROCEED WITH "REGULAR LOGIN" (ALL CART ITEMS LOST, FOR CUSTOMERS WITH DIFFERENT PRICEBOOKS)
		case 5:
			data = {
				"action" : "login",
				"user" : $('anonuser').value,
				"pass" : $('anonpass').value
			};
			req = new Request({
				method: 'post',
				url: 'ajax_user.php',
				async: false,
				onRequest: function() {
					$('anonLoginStatus').set("html", "<img src='images/spinnerSmall.gif' /> Processing...");
				},
				onSuccess: function(responseText) {
					if (responseText=="OK") {
						location.href = "index.php";
					} else {
						alert(responseText);
						$('anonLoginStatus').set("html", "");
					}
				}
			}).post(data);
			break;

		// (PROCESS 6) END - PROCEED ORDER CONFIRM
		case 6:
			data = { "action" : "processOrder" };

			req = new Request({
				url: 'ajax_cart.php', async: false,
				onRequest: function() {
					// CASH CHECKOUTS
					if($('cartPopupClose')){
						$('cartPopupClose').disabled = true;
						$('checkoutConfirmButton').disabled = true;
						$('checkoutBackButton').disabled = true;
						$('checkoutStatus').set("html", "<img src='images/spinnerSmall.gif' /> Processing order...");
					}
					// CC CHECKOUTS
					else{
						$('confirmButton').disabled = true;
						$('confirmStatus').set("html", "<img src='images/spinnerSmall.gif' /> Processing transaction, please do not navigate away from this page!");
					}
				},
				onSuccess: function(response){
					var result = JSON.decode(response);
					if(result.code=="0"){
						// CASH CHECKOUT - CONTINUE TO THANK YOU
						if(result.type=="cash" || result.type=="wt"){
							location.href="http://www.substogo.sg/thankYou.php";
						}
						// CC CHECKOUT - CONTINUE TO PROCESS ORDER UPDATE
						else {
							$('ccOrderID').value = result.orderID;
							$('ccOrderRef').value = result.orderRef;
							$('ccForm').submit();
						}
					}
					// CODE X - NOT OK
					else {
						location.href="http://www.substogo.sg/error.php?error="+result.code;
					}
				}
			}).post(data);
			break;
	}

	// (2) UPDATE POPUP ONLY IF CHECKS IN (1) PASS
	if (proceed){
		popup.setMode("ajax", "ajax_cart.php", data);
		popup.show();
	}
}

function checkoutAccount(show){
// checkoutAccount() : show register/sign in box during checkout
// PARAM show : [0] Register [1] Sign in

	if(show==0){
		$('checkoutRegisterForm').setStyle('display','block');
		$('checkoutSignInBox').setStyle('display','none');
	} else {
		$('checkoutRegisterForm').setStyle('display','none');
		$('checkoutSignInBox').setStyle('display','block');
	}
}

function showold(){
// showold() : "replay attack" last cart action

	if($type(lastItem)=="function"){ lastItem(); }
}

function editCartItem(productID){
// editCartItem() : edit an item in cart

	// REVERSE ENGINEERING
	var data = {
		"action" : "reverseEngineer",
		"productID" : productID
	};
	var req = new Request.JSON({
		url: 'ajax_cart.php', async: false,
		onSuccess: function(response){
			switch(response.baseCatName){
				case "Sandwich":
					chooseSub(response.productID, response.attributes[1], response);
					break;

				case "Lunchbox":
					chooseLunchbox(response.productID, response.attributes[1], response);
					break;

				case "Platters":
					if(response.catName=="Sub Platter" || response.catName=="Wrap Platter"){
						var gotBread = response.catName=="Sub Platter" ? true : false ;
						var gotBuild = ((response.name == "Build-Your-Own Platter (Subs)") || (response.name == "Build-Your-Own Platter (Wrap)")) ? true : false ;
						choosePlatter(response.productID, response.attributes[31], gotBread, gotBuild, response);
					} else {
						chooseCookiePlatter(response.productID, response);
					}
					break;

				case "Drinks":
					changeDrink(response);
					break;

				case "Snacks / Desserts":
					if(response.name=="Party Snacks"){
						selectParty(response.productID, response);
					} else if(response.name=="Cookies"){
						selectCookie(response.productID, response);
					} else {
						changeSnack(response);
					}
					break;
			}
		}
	}).post(data);
}

// [WS][12 MAY 2011] GIFT CARD FUNCTIONS
function gcQtyAction(gcID){
// gcQtyAction() : quantity change action
// PARAM gcID : gift card ID

	var newQty = $('gcQty'+gcID).value;
	newQty = newQty=="" ? 0 : newQty;
	if(isNaN(newQty) || newQty<0){
		alert("Please enter a valid quantity");
		$('gcQty'+gcID).value = $('gcOldQty'+gcID).value;
	} else {
		$('gcOldQty'+gcID).value = $('gcQty'+gcID).value;
		gcCalculateTotal();
	}
}

function gcCalculateTotal(){
// gcCalculateTotal() : calculate and show new gift card prices

	var allQty = $('gcTable').getElements('input[type=text]');
	var total = 0;
	allQty.each(function(e){
		var current = e.id.substring(5,e.length);
		var thisPrice = parseFloat($('gcPrice'+current).value);
		var thisQty = e.value;
		thisQty = thisQty=="" ? 0 : parseInt(thisQty) ;
		total += thisQty * thisPrice;
	});
	$('gcTotal').set("html", total.toFixed(2));
}

function gcCheckout(next){
// gcCheckout() : additional step in checkout process - record selected gift cards
// PARAM next : next process

	var qty = 0;
	var pid = [];
	var pqty = [];
	var allQty = $('gcTable').getElements('input[type=text]');
	allQty.each(function(e){ if(isNumeric(e.value)){
		pid[pid.length] = e.id.substring(5,e.length);
		pqty[pqty.length] = e.value;
		qty += parseInt(e.value);
	}});

	if(qty>0){
		if($('giftcardtnc').checked){
			var data = {
				"action" : "checkout1",
				"rco" : 1,
				"pid" : pid,
				"pqty" : pqty
			};
			var req = new Request({
				method: 'post',
				url: 'ajax_giftCard.php',
				async: false,
				onRequest: function(){
					$('checkoutStatus').set("html", "<img src='images/spinnerSmall.gif'/> Processing transaction, please do not navigate away from this page!");
				}
				//,onSuccess: function(response){ alert(response); }
			}).post(data);
			processCheckout(next);
		} else {
			alert("You must agree to the gift cards terms & conditions.");
		}
	} else {
		var req = new Request({
			method: 'post',
			url: 'ajax_giftCard.php',
			async: false,
			onRequest: function(){
				$('checkoutStatus').set("html", "<img src='images/spinnerSmall.gif'/> Processing transaction, please do not navigate away from this page!");
			}
			//,onSuccess: function(response){}
		}).post({ action : "clearGC" });
		processCheckout(next);
	}
}
