/***********************************************/
/* BULLOCKCART.JS : THE BULLOCKCART ENGINE     */
/* SUBWAY-CUSTOMIZED VERSION 1.0               */
/* COPYRIGHT(C) 2009-2010 SPINNAKER360 PTE LTD */
/***********************************************/

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");
			}
		}
	}).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){
// updateQty() : update quantity
// PARAM productID : product ID
//       remove : remove this item from the 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){
				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:
			// MOD HERE : USE HTTPS REDIRECTION
			location.href = "https://www.substogo.sg/checkoutCC.php";
			//location.href = "http://beta.spk/subway/checkoutCC.php";
		break;

		// (FOLLOW-UP 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({
					method: 'post', url: 'ajax_user.php', async: false,
					onRequest: function(){
						$('anonLoginStatus').set("html", "<img src='images/spinnerSmall.gif' /> Processing...");
					},
					onSuccess: function(responseText){
						// OK TO PROCEED WITH ANON LOGIN
						if(responseText=="OK"){
							data = {
								"action" : "anonLogin",
								"user" : $('anon_login_email').value
							};
							var loginReq = new Request({
								method: 'post',
								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(responseText=="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" : "showCheckoutFulfill",
					"register" : 1,
					"firstName" : $('checkoutFirstname').value,
					"lastName" : $('checkoutLastname').value,
					"email" : $('checkoutEmail').value,
					"tel" : $('checkoutTel').value
				};
				proceed = true;
			}
		break;

		// ANON-LOGIN - PROCEED WITH "REGULAR-ANON LOGIN" (ALL CART ITEMS LOST)
		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;

		// (END - PROCEED ORDER CONFIRM)
		case 6:
			data = { "action" : "processOrder" };
			req = new Request.JSON({
				method: 'post', 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){
					// MOD HERE : SWITCH BETWEEN HOSTS FOR TEST / PRODUCTION

					// CODE 0 - OK
					if(response.code==0){
						// CASH CHECKOUT - CONTINUE TO THANK YOU
						if(response.type=="cash"){
							location.href="http://www.substogo.sg/thankYou.php";
							//location.href="http://beta.spk/subway/thankYou.php";
						}
						// CC CHECKOUT - CONTINUE TO PROCESS ORDER UPDATE
						else {
							$('ccOrderID').value = response.orderID;
							$('ccForm').submit();
						}
					}
					// CODE X - NOT OK
					else {
						location.href="http://www.substogo.sg/error.php?error="+response.code;
						//location.href="http://beta.spk/subway/error.php?error="+response.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() : "reply attack" last cart action

	if($type(lastItem)=="function"){ lastItem(); }
}