/***********************************************/
/* FULFILLMENT.JS : FULFULLMENT MODULE         */
/* COPYRIGHT(C) 2009-2010 SPINNAKER360 PTE LTD */
/***********************************************/

/**** FULFILLMENT PROCESSES ****/
function processFulfill(process, productID, attributes, postAction, change) {
// processFulfill() : process fulfillment
// PARAM process : process to do
//	     productID : product ID (if any)
//	     attributes : related attributes (if any, products, fulfillment mode, payment mode, etc...)
//	     postAction : action to perform after fulfillment mode
//       change : [flag] change location OR payment mode

	// (A) PROCESS DATA
	var proceed = false, data, paymentMode, fulfill, mode, req;

	switch (process) {
		// [PROCESS 0] : CHECK IF FULFILLMENT MODE IS CHOSEN
		case 0:
			data = { "action" : "process0" };
			req = new Request({
				url: 'ajax_fulfill.php', async: false,
				onSuccess: function(responseText) {
					// (0.1) FULFILLMENT NOT CHOSEN
					if (responseText == "0"){ processFulfill(1, productID, attributes, postAction); }
					// (0.2) FULFILLMENT CHOSEN
					else { processPostAction(productID, attributes, postAction); }
				}
			}).post(data);
			break;

		// [PROCESS 1] : SHOW CHOOSE FULFILLMENT / PAYMENT
		case 1:
			data = {
				"action" : "process1",
				"productID" : productID,
				"postAction" : postAction
			};
			if($defined(attributes)){
				$extend(data, { "attributes" : attributes });
			}
			proceed = true;
			break;

		// [PROCESS 2] : SET FULFILLMENT / PAYMENT
		case 2:
			data = {
				"action" : "process2",
				"productID" : productID,
				"postAction" : postAction
			};
			if($defined(attributes)){
				$extend(data, { "attributes" : attributes });
			}

			// CHANGE PAYMENT MODE
			if(change){
				$extend(data, { "change" : 1 });
			}
			// OR SELECT PAYMENT MODE
			else {
				fulfill = $('fulfillPickup').checked ? "pickup" : "deliver";
				paymentMode = $('fulfillPayCC').checked ? 'cc' : $('fulfillPayCash').checked ? 'cash' : null;
				$extend(data, { "paymentMode" : paymentMode });
			}

			req = new Request({
				url: 'ajax_fulfill.php', async: false,
				onSuccess: function(responseText) {
					if (change) {
						// CHANGE PAYMENT MODE
						popup.hide(); showCart(6);
					} else {
						if (fulfill == "pickup") {
							processFulfill(3, productID, attributes, postAction);
						} else {
							processFulfill(4, productID, attributes, postAction);
						}
					}
				}
			}).post(data);
			break;

		// [PROCESS 3] : SHOW SELECT PICKUP LOCATION & TIME
		case 3:
			data = {
				"action" : "process3",
				"productID" : productID,
				"postAction" : postAction
			};
			if($defined(attributes)){
				$extend(data, { "attributes" : attributes });
			}

			// CHANGE PICKUP LOCATION
			if(change){
				$extend(data, { "change" : 1 });
			}
			proceed = true;
			break;

		// [PROCESS 4] : SHOW SELECT DELIVERY LOCATION & TIME
		case 4:
			data = {
				"action" : "process4",
				"productID" : productID,
				"postAction" : postAction
			};
			if($defined(attributes)){
				$extend(data, { "attributes" : attributes });
			}
			if(change){
				$extend(data, { "change" : 1 });
			}
			proceed = true;
			break;

		// [PROCESS 5] : SET FULFILLMENT LOCATION & TIME
		case 5:
			// (5A) CHECK FOR VALID TIME FIRST (SELECTED TIME SLOT HAS NOT EXPIRED)
			var pass = true;
			if($defined($('validUnix'))){
				data = {
					"action" : "checkFulfillValid",
					"validTill" : $('validUnix').value
				};
				req = new Request({
					url: 'ajax_fulfill.php', async: false,
					onRequest: function(){
						if($defined($('fulfillBack'))){ $('fulfillBack').disabled = true; }
						$('fulfillDone').disabled = true;
						$('fulfillDone').disabled = true;
					},
					onSuccess: function(responseText) {
						if(responseText=="0"){
							alert("Your selected time has expired!\nPlease select another time slot.");
							$('fulfillBack').disabled = false;
							$('fulfillDone').disabled = false;
							pass = false;
						}
					}
				}).post(data);
			}

			// (5B) INTELLIGENCE GATHERING
			if(pass){
				mode = $('fulfillMode').value;
				data = {
					"action" : "process5",
					"date" : $('selectedDate').value,
					"time" : $('selectedHr').value + ":" + $('selectedMin').value,
					"orderLimit" : $('fulfillOrderLimit').value,
					"mode" : mode
				};
				if($('validUnix')){
					data = $extend({ "valid" : $('validUnix').value }, data);
				}
				if(mode == "pickup"){
					data = $extend({ "location" : $('fulfillLocation').value }, data);
				} else {
					data = $extend({
						"fulfillDeliverType" : $('fulfillDeliverType').value,
						"location" : $('fulfillLocation').value,
						"fulfillUnit" : $('fulfillUnit').value,
						"fulfillDeliverStore" : $('deliverStore').value,
						"minOrder" : $('fulfillMinOrder').value,
						"deliveryCharge" : $('fulfillDeliverCharge').value,
						"freeDeliverZone" : $('fulfillFreeDeliver').value
					}, data);
				}

				// (5C) SEND TO INTELLIGENCE AGENCY
				req = new Request({
					url: 'ajax_fulfill.php', async: false,
					onRequest: function(){
						if($defined($('fulfillBack'))){ $('fulfillBack').disabled = true; }
						$('fulfillDone').disabled = true;
					},
					onSuccess: function(responseText) {
						// (5C-1) PRIME TIME BOMB
						if($defined($('validTimeStamp'))){
							timeBomb = Date.parse($('validTimeStamp').value);
							timeSync();
						} else {
							timeBomb = null;
							$('fulfillExpireWrapper').setStyle("display", "none");
							$('fulfillExpire').setStyle("display", "none");
						}
						
						// (5C-2) CONTINUE WITH POST ACTION
						processPostAction(productID, attributes, postAction);
					}
				}).post(data);
			}
			break;
	}

	// (B) DISPLAY POPUP
	if(proceed) {
		popup.onShow = function() { initToolTip(); };
		popup.setMode("ajax", "ajax_fulfill.php", data);
		popup.show();
	}
}

function processPostAction(productID, attributes, postAction) {
// processPostAction() : process post action (from fulfillment mode or hot item check)
// PARAM productID : product ID
//       attributes : product related attributes (if any)
//       postAction : action to perform after fulfillment mode

	var split, bread, build, selection;

	switch (postAction) {
		// Forward to "Show Cart"
		case "showCart":
			if(popup.open){ popup.hide(); }
			updateSneak();
			showCart(attributes);
			break;

		// Forward to "Redirect and show cart"
		case "redirectShowCart":
			location.href='menu.php?show=1';
			break;

		// Forward to "Use Previous Order"
		case "reorder":
			if($defined($('fulfillCat'))){
				updateProductCatalog($('fulfillCat').value);
			}
			checkPreviousOrder(attributes);
			break;

		// Forward to "Customize Sub"
		case "sub":
			if($defined($('fulfillCat'))){
				updateProductCatalog($('fulfillCat').value);
			}
			chooseSub(productID, attributes);
			break;

		/*
		// Forward to "Customize Breakfast Sub"
		case "breakfast":
			if($defined($('fulfillCat'))){
				updateProductCatalog($('fulfillCat').value);
			}
			chooseBreakfast(productID);
			break;
		*/

		// Forward to "Customize Lunchbox"
		case "lunchbox":
			if($defined($('fulfillCat'))){
				updateProductCatalog($('fulfillCat').value);
			}
			chooseLunchbox(productID, attributes);
			break;

		// Forward to "Customize Platter"
		case "platter":
			if($defined($('fulfillCat'))){
				updateProductCatalog($('fulfillCat').value);
			}
			// Split [0] size [1] bread [2] build
			split = attributes.split('#');
			bread = split[1] != "0";
			build = split[2] != "0";
			choosePlatter(productID, parseInt(split[0], 10), bread, build);
			break;

		// Forward to "Customize Cookie Platter"
		case "cookiePlatter":
			if($defined($('fulfillCat'))){
				updateProductCatalog($('fulfillCat').value);
			}
			chooseCookie(productID);
			break;

		// Forward to "Add Drink To Cart"
		case "drinks":
			if($defined($('fulfillCat'))){
				updateProductCatalog($('fulfillCat').value);
			}
			selection = attributes != "0";
			addDrinkToCart(productID, selection);
			popup.hide();
			break;

		// Forward to "Add Snack To Cart"
		case "snack":
			if($defined($('fulfillCat'))){
				updateProductCatalog($('fulfillCat').value);
			}
			selection = attributes != "0";
			addSnackToCart(productID, selection);
			popup.hide();
			break;

		// Forward to "Select Cookie"
		case "cookie":
			if($defined($('fulfillCat'))){
				updateProductCatalog($('fulfillCat').value);
			}
			selectCookie(productID);
			break;

		// Forward to "Select Party Snacks"
		case "party":
			if($defined($('fulfillCat'))){
				updateProductCatalog($('fulfillCat').value);
			}
			selectParty(productID);
			break;
	}
}

/**** PICKUP BRANCH PROCESSES ****/
function getStoreSelection(storeID){
// [Pickup fulfillment sub-function]
// getStoreSelection() : discovers available time selections for store
// PARAM storeID : store ID

	$('fulfillDone').disabled = true;
	if (!$defined(storeID)) {
		$('fulfillStoreStatus').set("html", "");
	} else {
		var data = {
			"action" : "storeSelection",
			"storeID" : storeID
		};

		var req = new Request({
			url: 'ajax_fulfill.php', async: false,
			onRequest: function() {
				$('fulfillStoreStatus').set("html", "<img src='images/spinnerSmall.gif' /> Retrieving store...");
			},
			onSuccess: function(responseText) {
				$('fulfillStoreStatus').set("html", responseText);
				if ($defined($('selectedDate'))) {
					var cal = new CalendarEightysix('selectedDate', {
						'format': '%Y-%m-%d',
						'minDate': (new Date()).format('%Y-%m-%d'), // today's date
						'maxDate': $('advanceOrderDateMax').value,
						'disallowUserInput': true,
						'pickFunction': changeDate
					});
					checkDate(storeID, $('selectedDate').value);
				}
			}
		}).post(data);
	}
}

function checkDate(storeID, date){
// checkDate() : check if selected date is open for pickups
// PARAM storeID : selected store ID
//       date : selected date

	// (0) SET THE "NAME" OF THE DATE FIRST
	var minDate = (new Date()).format('%Y-%m-%d'); // today's date
	var dateString = "";
	if(minDate==$('selectedDate').value){
		dateString = "(today)";
	} else {
		var mooDate = new Date();
		mooDate.parse($('selectedDate').value);
		dateString = "("+mooDate.format("%A")+")";
	}
	$('dateString').set("html", dateString);
	var data = {
		"action" : "checkPickupDate",
		"storeID" : storeID,
		"date" : date
	};

	var req = new Request({
		url: 'ajax_fulfill.php', async: false,
		onRequest: function() {
			$('conflictstatusPre').set("html", "<img src='images/spinnerSmall.gif' /> Checking store status...");
			$('conflictstatusPost').set("html", "");
		},
		onSuccess: function(responseText) {
			$('conflictstatusPre').set("html", responseText);
			if($('combatFit').value==1){
				getHourBounds(storeID, date);
			} else {
				$('fulfillDone').disabled = true;
				$('selectedHr').set("html", "<option>--</option>");
				$('selectedMin').set("html", "<option>--</option>");
			}
		}
	}).post(data);
}

function getHourBounds(storeID, date) {
// [Pickup fulfillment sub-function]
// getHourBounds() : get selectable hours range for selected pickup store
// PARAM storeID : selected store ID
//       date : selected date

	var data = {
		action	: 'getHourBounds',
		storeID	: storeID,
		date	: date
	};

	var req = new Request({
		url: 'ajax_fulfill.php', async: false,
		onRequest: function(){
			$('conflictstatusPost').set("html", "<img src='images/spinnerSmall.gif' /> Checking store status...");
		},
		onSuccess: function(responseText) {
			if(responseText=="NA"){
				$('fulfillDone').disabled = true;
				$('selectedHr').set("html", "<option>--</option>");
				$('selectedMin').set("html", "<option>--</option>");
				$('conflictstatusPost').set("html", "<div class='errorsign'>Store is unable to handle orders for selected date.</div>");
			} else {
				$('selectedHr').set("html", responseText);
				getMinBounds(storeID, date, $('selectedHr').value);
			}
		}
	}).post(data);
}

function getMinBounds(storeID, date, hr) {
// [Pickup fulfillment sub-function]
// getMinBounds() : get selectable min range for selected pickup store
// PARAM storeID : selected store ID
//       date : selected date
//       hr : selected hr

	var data = {
		action	: 'getMinBounds',
		storeID	: storeID,
		date	: date,
		hr		: hr
	};

	var req = new Request({
		url: 'ajax_fulfill.php', async: false,
		onSuccess: function(responseText) {
			$('selectedMin').set("html", responseText);
			checkPickupTime();
		}
	}).post(data);
}

function changeDate(){
// [Pickup fulfillment sub-function]
// changeDate() : handles date change in pickup fulfillment

	checkDate($('fulfillLocation').value, $('selectedDate').value);
}

function checkPickupTime(){
// [Pickup fulfillment sub-function]
// checkPickupTime() : check if the selected date/time is available for pickup

	var data = {
		action	: 'checkPickupConflict',
		storeID	: $('fulfillLocation').value,
		date	: $('selectedDate').value,
		time	: $('selectedHr').value + ":" + $('selectedMin').value + ":00"
	};

	var req = new Request.JSON({
		url: 'ajax_fulfill.php', async: false,
		onRequest: function(){
			$('fulfillDone').disabled = true;
			$('conflictstatusPost').set("html", "<img src='images/spinnerSmall.gif' /> Checking store schedule");
		},
		onSuccess: function(result){
			$('conflictstatusPost').set("html", result.message);
			var toDisable = true;
			if(result.status == 'OK') {
				toDisable = $defined($('fulfillCheck')) ? true : false ;
			}
			$('fulfillDone').disabled = toDisable;
		}
	}).post(data);
}

/**** DELIVERY BRANCH PROCESSES ****/
function fulfillGetAddress(postcode){
// [Delivery fulfillment sub-function]
// fulfillgetAddress() : get address for postal code; fulfillment mode specialized
// PARAM postcode : postal code

	if (postcode.length < 6 || isNaN(postcode)) {
		$('fulfill_address_status').set("html", "<img src='images/error.gif' /> Invalid postal code");
		$('fulfill_address').value = "";
	} else {
		var data = {
			action	: 'getAddr',
			pc		: postcode
		};

		var req = new Request({
			url: 'ajax_postcode.php', async: false,
			onRequest: function() {
				$('fulfill_address_status').set("html", "<img src='images/spinnerSmall.gif' /> Retrieving...");
			},
			onSuccess: function(responseText) {
				if (responseText == "") {
					$('fulfill_address_status').set("html", "<img src='images/error.gif' /> Invalid postal code");
					$('fulfill_address').value = "";
				} else {
					$('fulfill_address_status').set("html", "<img src='images/ok.gif' />");
					$('fulfill_address').value = responseText;
				}
			}
		}).post(data);
	}
}

function setDeliveryAddress(mode){
// [Delivery fulfillment sub-function]
// setDeliveryAddress() : set/check delivery address
// PARAM mode : [manual] entry or address [book]

	var proceed = false,
		fullAddress;

	if (mode == 'book'){
		$('fulfillDone').disabled = true;
		$('fulfillDeliverType').value = mode;
		$('fulfillAddressBook').getElements('option').each(function(item) {
			if (item.selected){
				// use title param for postcode, value for address book id and innerHTML for full address
				$('fulfillSelectedDeliver').set("html", item.innerHTML);
				$('fulfillLocation').value = item.value;
				$('fulfillUnit').value = "";
				$('bookPC').value = item.title;
				proceed = true;
			}
		});
	} else {
		if (!$chk($('fulfill_address').value) || $('fulfill_PC').value.length < 6) {
			$('fulfill_PC').addClass('inputErr');
			alert("Please enter a valid postal code.");
		} else {
			$('fulfill_PC').removeClass('inputErr');
			$('fulfillDone').disabled = true;
			fullAddress = $('fulfill_address').value + ($chk($('fulfill_unit').value) ? " " + $('fulfill_unit').value : "") + " Singapore " + $('fulfill_PC').value;
			$('fulfillSelectedDeliver').set("html", fullAddress);
			$('fulfillDeliverType').value = mode;
			$('fulfillLocation').value = $('fulfill_PC').value;
			$('fulfillUnit').value = $chk($('fulfill_unit').value) ? $('fulfill_unit').value : "";
			$('bookPC').value = "";
			proceed = true;
		}
	}

	if (proceed) { preDeliverCheck(); }
}

function preDeliverCheck() {
// [Delivery fulfillment sub-function]
// preDeliverCheck() : pre-get hour & mins check

	var data = {
		action	: 'preDeliverCheck',
		pc		: $('fulfillDeliverType').value == "book" ? $('bookPC').value : $('fulfillLocation').value
	};

	var req = new Request({
		url: 'ajax_fulfill.php', async: false,
		onRequest: function(){
			$('deliveryNotes').set("html", "<img src='images/spinnerSmall.gif' /> Checking stores..");
		},
		onSuccess: function(responseText){
			$('deliveryNotes').set("html", responseText);
			if($('selectedDate')) {
				var minDate = $defined($('sameDayDeliver'))
							? (new Date()).format('%Y-%m-%d') // today's date
							: (new Date()).increment().format('%Y-%m-%d'); // tomorrow's date
				var cal = new CalendarEightysix('selectedDate', {
					'format': '%Y-%m-%d',
					'defaultDate': minDate,
					'minDate': minDate,
					'maxDate': $('advanceOrderDateMax').value,
					'disallowUserInput': true,
					'pickFunction': getDHourBounds
				});

				getDHourBounds();
			}
		}
	}).post(data);
}

function getDHourBounds() {
// getDHourBounds() : get selectable hours for delivery
// [Delivery fulfillment sub-function]

	// (0) SET SELECTED DATE AS STRING
	var todayDate = (new Date()).format('%Y-%m-%d'); // today's date
	var dateString = "";
	if(todayDate==$('selectedDate').value){
		dateString = "(Today)";
	} else {
		var mooDate = new Date();
		mooDate.parse($('selectedDate').value);
		dateString = "("+mooDate.format("%A")+")";
	}
	$('dateString').set("html", dateString);

	// (1) CHECK FOR DELIVERY AVAILABILITY FOR THE SELECTED DAY
	var proceed = false, req,
		commonData = {
			date: $('selectedDate').value,
			pc	: $('fulfillDeliverType').value == "book" ? $('bookPC').value : $('fulfillLocation').value
		},
		data = $extend({
			action: 'checkDeliveryAvail'
		}, commonData);

	req = new Request.JSON({
		url: 'ajax_fulfill.php', async: false,
		onRequest: function() {
			$('conflictStatus').set("html", "<img src='images/spinnerSmall.gif' /> Checking stores...");
		},
		onSuccess: function(responseText) {
			if (responseText.checkpass == false) {
				$('selectedHr').set("html", "<option>--</option>");
				$('selectedMin').set("html", "<option>--</option>");
				$('conflictStatus').set("html", responseText.msg);
				$('fulfillDone').disabled = true;
			} else {
				proceed = true;
			}
		}
	}).post(data);

	// (2) DELIVERY POSSIBLE - CARRY ON
	if (proceed) {
		data = $extend({ action : 'getDHourBounds' }, commonData);
		req = new Request({
			url: 'ajax_fulfill.php', async: false,
			onSuccess: function(responseText){
				if (responseText == "NA") {
					$('selectedHr').set("html", "<option>--</option>");
					$('selectedMin').set("html", "<option>--</option>");
					$('conflictStatus').set("html", "<div class='errorsign'>Sorry, we are unable to service deliveries on " + $('selectedDate').value + ". Please call " + $('hqTel').value + " for alternative arrangements.</div>");
					$('fulfillDone').disabled = true;
				} else {
					$('selectedHr').set("html", responseText);
					getDMinBounds();
				}
			}
		}).post(data);
	}
}

function getDMinBounds() {
// [Delivery fulfillment sub-function]
// getDMinBounds() : get selectable mins for delivery

	var data = {
		action	: 'getDMinBounds',
		date	: $('selectedDate').value,
		hr		: $('selectedHr').value,
		pc		: $('fulfillDeliverType').value == "book" ? $('bookPC').value : $('fulfillLocation').value
	};

	var req = new Request({
		url: 'ajax_fulfill.php', async: false,
		onSuccess: function(responseText) {
			$('selectedMin').set("html", responseText);
			checkDeliverTime();
		}
	}).post(data);
}

function checkDeliverTime() {
// [Delivery fulfillment sub-function]
// checkDeliverTime() : check selected delivery time for conflicts

	var data = {
		action	: 'checkDeliverConflict',
		date	: $('selectedDate').value,
		time	: $('selectedHr').value + ":" + $('selectedMin').value + ":00",
		pc		: $('fulfillDeliverType').value == "book" ? $('bookPC').value : $('fulfillLocation').value
	};

	var req = new Request.JSON({
		url: 'ajax_fulfill.php', async: false,
		onRequest: function() {
			$('fulfillDone').disabled = true;
			$('conflictStatus').set("html", "<img src='images/spinnerSmall.gif' /> Checking store schedule");
		},
		onSuccess: function(result) {
			$('conflictStatus').set("html", result.message);

			if (result.status == 'OK'){ $('fulfillDone').disabled = false; }
			else { $('fulfillDone').disabled = true; }
		}
	}).post(data);
}

/**** SHARED ****/
function fulfillAgree(agree){
// fulfillAgree() : enable "Done" button only if user agrees to fulfillment "terms"

	if(agree){ $('fulfillDone').disabled = false; }
	else{ $('fulfillDone').disabled = true; }
}