/*
	--------------------------------
	retailer order system javascript
	----------------
*/

//eraseCookie('ROS_Current_Order_Id'); eraseCookie('ROS_Current_Order_Name');

var RetailerOrderSystem = {
	
	/* 
	-------------------------------------------
		properties */
	_ajax : false, _ajax_result : null, _ajax_query : null, _ajax_query_data : null,
	_user : null, _order : null, _order_name : null, _item : null, _box : null, 
	_order_to_duplicate : 0, _order_to_delete : 0, 
	_order_for_item_deletion : 0, _item_for_deletion : 0, _multiple_items_for_deletion : 0,
	_order_for_submission : null, _continue_url : null,
	
	/* 
	-------------------------------------------
		initiate order system for current user */
	initiate : function (userId, mode) {
		
		/* init output */
		this.output.initiate(mode);
		
		/* setup state */
		this._user 			= userId;
		this._order 		= readCookie('ROS_Current_Order_Id');
		this._order_name 	= readCookie('ROS_Current_Order_Name');

		/* ajax object create */
		try { this._ajax = new XMLHttpRequest(); }
		catch (e) {
			try { this._ajax = new ActiveXObject("Msxml2.XMLHTTP"); }
			catch (e) {
				try { this._ajax = new ActiveXObject("Microsoft.XMLHTTP"); }	
				catch (e) { this._ajax = false; }
			}
		}
		
	},
	
	/* 
	-------------------------------------------
		clear order system; no current user */
	clear : function () {
		this._user 	= null; this._order = null; 
		eraseCookie('ROS_Current_Order_Id'); eraseCookie('ROS_Current_Order_Name');
	},

	/* 
	-------------------------------------------
		verfiy the ajax object */
	_ajaxVerify : function () {
		if( !this._ajax ) {
			alert('You browser does not support AJAX which is required to use the Reatiler Ordering System');	
		}
		return this._ajax;
	},
	
	/* 
	-------------------------------------------
		ajax object run */
	_ajaxOpen : function () {
		
		/* open the ajax */
		var url = "/wholesale-orders/ajax.php?query="+this._ajax_query+'&'+this._ajax_query_data; 
		url = url + "&sid=" + Math.random();
		this._ajax_result = new Object;
		this._ajax.onreadystatechange = RetailerOrderSystem_AjaxCallback;
		this._ajax.open("GET", url, true);
		this._ajax.send(null);
		
	},
	
	/* 
	-------------------------------------------
		ajax object callback */
	_ajaxResponse : function (data) {
		
		/* get values */
		var jxvalues = data.split('|');
		for(var i=0; i<(jxvalues.length); i++) {
			var vr = jxvalues[i].split('='); this._ajax_result[vr[0]] = vr[1];
		}
		
		/* respond as needed */
		if(this._ajax_result.resultCode == 'SUCCESS') {
			switch(true) {
				case this._ajax_query == 'CREATE_ORDER':
					this.setCurrentOrder(this._ajax_result.resultId, this._ajax_result.resultName);
					if(this._item != null) {
						this.addItem(this._item);
					}
					this.output.appendItemData(this._ajax_result.newItemData);
					this.output.writeOut(this._order, this._ajax_result.resultId);
  					break;
				case this._ajax_query == 'DUPLICATE_ORDER':
					this.output.appendItemData(this._ajax_result.newItemData);
					this.output.writeOut(this._order, this._ajax_result.resultId);
  					break;
				case this._ajax_query == 'ADD_ORDER_ITEM':
 					this._box = orderItemAddedAlertBox(this._ajax_result.resultName, this._order_name, this._order);
					this.output.appendItemData(this._ajax_result.newItemData);
					this.output.writeOut(this._order, this._ajax_result.resultId);
  					break;
				case this._ajax_query == 'REMOVE_ORDER_ITEM':
					this.output.removeListItem('ID', this._ajax_result.resultId);
					this.output.writeOut(this._order, 0);
					break;
				case this._ajax_query == 'DELETE_ORDER':
					this.output.removeListItem('ID', this._ajax_result.resultId);
					this.output.writeOut(this._order, 0);
					break;
				case this._ajax_query == 'CHANGE_ORDER_ITEM_QUANTITY':
					this.output.updateListItem('ID', this._ajax_result.resultId, 'QUANTITY', this._ajax_result.newData);
					this.output.reWriteCartQuatities();
					break;
				case this._ajax_query == 'REMOVE_MULTIPLE_ORDER_ITEMS':
					var itR = this._ajax_result.itemsRemoved.split(',');
					for(var i=0; i<(itR.length); i++) {
						this.output.removeListItem('ID', itR[i]);
					}
					this.output.writeOut(this._order, 0);
					break;
				case this._ajax_query == 'SUBMIT_ORDER':
					$(document).attr("location","thank-you.php?cart="+this._ajax_result.resultId+"&u="+this._continue_url+"");
					this._box.hide();
					break;
			}
		} else {
			if(this._ajax_result == "") {
				alert('Unable to interface with the order system');
			} else {
				alert(this._ajax_result.resultMessage);
			}
		}

	},
	
	/* 
	-------------------------------------------
		create a new order */
	createOrder : function () {
		
		/* verify ajax */
		if( !this._ajaxVerify() ) {
			return false;
		}
		
		/* get form values */
		var jqC = this._box.getContent(); var elF = jqC.get(0);
		if(elF.orderName.value == '' || elF.orderName.value == null) {
			return false;
		} else {
			
			/* run ajax */
			if(this._order_to_duplicate != 0) {
				this._ajax_query = "DUPLICATE_ORDER"; 
				this._ajax_query_data = 'user-id='+this._user;
				this._ajax_query_data += '&order-id='+this._order_to_duplicate+'';
				this._ajax_query_data += '&order-name='+urlencode(elF.orderName.value);
				this._ajax_query_data += '&order-description='+urlencode(elF.orderDescription.value);
				this._ajaxOpen();
				this._order_to_duplicate = 0;
			} else {
				this._ajax_query = "CREATE_ORDER"; 
				this._ajax_query_data = 'user-id='+this._user;
				this._ajax_query_data += '&order-name='+urlencode(elF.orderName.value);
				this._ajax_query_data += '&order-description='+urlencode(elF.orderDescription.value);
				this._ajaxOpen();
			}
			
			/* hide box */
			this._box.hide();
			
		}
		
	},
	
	/* 
	-------------------------------------------
		set the current working order */
	setCurrentOrder : function (order, order_name) {
		
		this._order 		= order;
		this._order_name 	= order_name;
		
		/* cookies */
		createCookie('ROS_Current_Order_Id', this._order, 1);
		createCookie('ROS_Current_Order_Name', this._order_name, 1);
		
		/* kill any box */
		if(this._box != null) { this._box.hide(); this.box = null; }
		
		/* set top nav name display */
		setCurrentOrderTopDisplay(order, order_name);
		
		/* output list */
		this.output.writeOut(this._order, 0);
		
	},
	
	/* 
	-------------------------------------------
		nullifies the current order */
	dropCurrentOrder : function () {
		
		this._order 		= null;
		this._order_name 	= null;
		
		/* cookies */
		eraseCookie('ROS_Current_Order_Id'); eraseCookie('ROS_Current_Order_Name');
		
		/* set top nav name display */
		setCurrentOrderTopDisplay(null, '(none)');
		
	},
	
	/* 
	-------------------------------------------
		makes a new order */
	newOrder : function(order) {
		
		if(this._box != null) { this._box.hide(); this.box = null; }
		this._box = createNewOrderBox("New order...");
		
	},
	
	/* 
	-------------------------------------------
		duplicates an order */
	duplicateOrder : function(order) {
		
		this._order_to_duplicate = order;
		if(this._box != null) { this._box.hide(); this.box = null; }
		this._box = createNewOrderBox("Duplicate order...");
		
	},
	
	/* 
	-------------------------------------------
		confirms the removal of an order */
	removeOrder : function(order) {
		
		this._order_to_delete = order;
		if(this._box != null) { this._box.hide(); this.box = null; }
		this._box = confirmOrderRemovalBox();
		
	},
		
	/* 
	-------------------------------------------
		deletes an order */
	deleteOrder : function() {
		
		if(this._order_to_delete != 0) {
			this._ajax_query = "DELETE_ORDER"; 
			this._ajax_query_data = 'user-id='+this._user;
			this._ajax_query_data += '&order-id='+urlencode(this._order_to_delete);
			this._ajaxOpen();
			
		}
		
		/* unset if current */
		if(this._order_to_delete == this._order) {
			this.dropCurrentOrder();
		}
		
		/* must unset */
		this._order_to_delete = 0;
		
		/* hide box */
		if(this._box != null) { this._box.hide(); this.box = null; }
		
	},
	
	/* 
	-------------------------------------------
		increment quantities */
	clickQuantity : function (itemId, cartonAmount, increment) {
		
		/* get quantity */
		var $quantity = parseInt( $('#quantity_'+itemId+'').val() );
		
		/* increment quantity */
		switch(true) {
			case increment == -1:
				if($quantity > cartonAmount) {
					$quantity -= cartonAmount;
				} else {
					$quantity -= 1;
				}
				break;
			default:
				if($quantity >= cartonAmount) {
					$quantity += cartonAmount;
				} else {
					$quantity += 1;
				}
		}
		
		/* set quantity */
		$('#quantity_'+itemId+'').val($quantity);
		
	},
	
	/* 
	-------------------------------------------
		add item to order */
	addItem : function (itemId, popSelecter) {

		/* verify ajax */
		if( !this._ajaxVerify() ) {
			return false;
		}
		
		/* set current item */
		this._item = itemId;
		
		/* get quantity */
		var $quantity = $('#quantity_'+itemId+'').val();
		
		/* if no current order, pop the create order box, otherwise add */
		if( this._order == null ) {
			if(this._box != null) { this._box.hide(); this.box = null; }
			if(popSelecter == 1) { this._box = createOrderSelectBox();
			} else {
				this.newOrder();
			}
		} else {
			/* ajax add item */
			this._ajax_query = "ADD_ORDER_ITEM"; 
			this._ajax_query_data = 'user-id='+this._user;
			this._ajax_query_data += '&order-id='+urlencode(this._order);
			this._ajax_query_data += '&item-id='+urlencode(itemId);
			this._ajax_query_data += '&item-quantity='+$quantity;
			
			alert(this._ajax_query_data);
			
			//this._ajaxOpen();
			//this._item = null;
		}

	},

	/* 
	-------------------------------------------
		set item quantity */
	setItemQuantity : function (orderId, itemId, quantity ) {

		/* confirm for zero */
		if(isNaN(quantity)) {
			return false;
		} else {
			if(eval(quantity) < 1) {
				this.removeItem(orderId, itemId);
				return false;
			}
		}
		
		/* verify ajax */
		if( !this._ajaxVerify() ) {
			return false;
		}
		
		/* set current item */
		this._item = itemId;

		/* ajax update item */
		this._ajax_query = "CHANGE_ORDER_ITEM_QUANTITY"; 
		this._ajax_query_data = 'user-id='+this._user;
		this._ajax_query_data += '&order-id='+urlencode(orderId);
		this._ajax_query_data += '&item-id='+urlencode(itemId);
		this._ajax_query_data += '&quantity='+urlencode(quantity)+'';
		this._ajaxOpen();
		this._item = null;
		
	},

	/* 
	-------------------------------------------
		remove item */
	removeItem : function (orderId, itemId) {
		
		this._order_for_item_deletion = orderId;
		this._item_for_deletion = itemId;
		if(this._box != null) { this._box.hide(); this.box = null; }
		this._box = confirmItemRemovalBox(orderId);
		
	},
	
	/* 
	-------------------------------------------
		delete item */
	deleteItem : function () {
		
		/* verify ajax */
		if( !this._ajaxVerify() ) {
			return false;
		}
		
		/* ajax update item */
		if(this._order_for_item_deletion != 0 && this._item_for_deletion != 0) {
			this._ajax_query = "REMOVE_ORDER_ITEM"; 
			this._ajax_query_data = 'user-id='+this._user;
			this._ajax_query_data += '&order-id='+urlencode(this._order_for_item_deletion);
			this._ajax_query_data += '&item-id='+urlencode(this._item_for_deletion);
			this._ajaxOpen();
			this._item = null;
		}

		/* must unset */
		this._order_for_item_deletion = 0;
		this._item_for_deletion = 0;
		
		/* hide box */
		if(this._box != null) { this._box.hide(); this.box = null; }
		
		
	},
	
	/* 
	-------------------------------------------
		queue multiple items for removal */
	queueMultipleItemsForRemoval : function (orderId, itemIdArray) {
		
		if(itemIdArray.length == 0) {
			return false;
		}
		this._order_for_item_deletion = orderId;
		this._multiple_items_for_deletion = itemIdArray;
		if(this._box != null) { this._box.hide(); this.box = null; }
		this._box = confirmMultipleItemRemovalBox();
		
	},
	
	/* 
	-------------------------------------------
		delete multiple items */
	deleteMultipleQueuedItems : function () {
		
		/* verify ajax */
		if( !this._ajaxVerify() ) {
			return false;
		}
		
		/* ajax update item */
		if(this._order_for_item_deletion != 0 && this._multiple_items_for_deletion != 0) {
			this._ajax_query = "REMOVE_MULTIPLE_ORDER_ITEMS"; 
			this._ajax_query_data = 'user-id='+this._user;
			this._ajax_query_data += '&order-id='+urlencode(this._order_for_item_deletion);
			this._ajax_query_data += '&items='+urlencode(this._multiple_items_for_deletion.join());
			this._ajaxOpen();
		}

		/* must unset */
		this._order_for_item_deletion = 0;
		this._multiple_items_for_deletion = 0;
		
		/* hide box */
		if(this._box != null) { this._box.hide(); this.box = null; }
		
	},
	
	/* 
	-------------------------------------------
		submit click */
	sumbitCartClick : function(order, continueUrl) {
		
		this._order_for_submission = order;
		this._continue_url = continueUrl;
		this._box = createSubmitOrderBox();
		
	},
	
	/* 
	-------------------------------------------
		submit do */
	submitOrder : function(bxy) {
		
		if(this._order_for_submission != 0) {
			this._ajax_query = "SUBMIT_ORDER"; 
			this._ajax_query_data = 'user-id='+this._user;
			this._ajax_query_data += '&order-id='+urlencode(this._order_for_submission);
			this._ajaxOpen();
			bxy.getContent().find('p').text('Submitting your order, please wait..');
		}
		
	},
	
	/* 
	-------------------------------------------
		remove item */
	output : {
		
		_mode : null, 
		_listData : null, _listDataKeys : null, _listContainer : null,
		_listAbstract : null,
		
		initiate : function(mode) {
			this._mode = mode;
		},
		
		startList : function(abstract, container) {
			
			/* start a new list output */
			this._listData 		= new Array(); 
			this._listContainer = container; 
			this._listAbstract 	= abstract;
			
		},
		
		appendItemData : function(dataString) {
			
			var rge = new RegExp('__eq__', 'g');
			dataString = dataString.replace(rge, '=');

			/* always reset keys */
			this._listDataKeys 	= new Array();
			var itemObject = new Object();
			
			/* extract and add the item data */
			var itemvalues = dataString.split('^');
			for(var i=0; i<(itemvalues.length); i++) {
				var vr = itemvalues[i].split('__'); var key = vr[0]; value = vr[1];
				itemObject[key] = value; this._listDataKeys[this._listDataKeys.length] = key;
			}
			
			/* append data object */
			this._listData.unshift(itemObject);

		},
		
		updateListItem : function(prim_key, prim_value, key, value) {
			
			/* list setup? */
			if(this._listData == null) {
				return false;
			}
			
			/* update where prim_key = prim_value */
			for(var i=0; i<this._listData.length; i++) {
				if(this._listData[i][prim_key] == prim_value) {
					this._listData[i][key] = value;
				}
			}
			
		},
		
		tallyListItems : function(key) {
			
			/* list setup? */
			if(this._listData == null) {
				return false;
			}
			
			/* add together list items on key */
			var total = -256;
			for(var i=0; i<this._listData.length; i++) {
				var kv = this._listData[i][key];
				if(isNaN(kv)) {
					if(total == -256) { total = ''; }
					total += kv;
				} else {
					if(total == -256) { total = 0; }
					total += eval(kv);
				}
			}
			
			return total;
			
		},
		
		removeListItem : function(key, value) {

			/* list setup? */
			if(this._listData == null) {
				return false;
			}
			
			/* remove where key = value */
			for(var i=0; i<this._listData.length; i++) {
				if(this._listData[i][key] == value) {
					this._listData[i] = -127;
				}
			}
			
		},
		
		writeOut : function(currentOrder, newItemId) {
			
			/* write per mode */
			switch(true) {
				case this._mode == 'ORDER-LOG':
					this.writeOrderLog(currentOrder, newItemId);
					break;
				case this._mode == 'CART-EDIT':
					this.writeCartProducts();
					break;
			}
			
		},
		
		writeOrderLog : function(currentOrder, newItemId) {
			
			/* list setup? */
			if(this._listData == null) {
				return false;
			}
			
			/* clear contents */
			$(this._listContainer).html("<!-- -->");
			
			/* write list parts */
			for(var i = 0; i < this._listData.length; i++) {
				var rowData 	= this._listAbstract;
				var listItem 	= this._listData[i];
				if(listItem != -127) {
					var listItemId 	= listItem['ID'];
					if(listItemId == newItemId) {
						listItem['STATE'] = 'new';
					} else {
						listItem['STATE'] = 'normal';
					}
					if(listItemId == currentOrder) {
						listItem['STATE'] += '-current';
					}
					for(var k = 0; k < this._listDataKeys.length; k++) {
						var key =  this._listDataKeys[k]; var kys = "__" + this._listDataKeys[k] + "__";
						var rge = new RegExp(kys, 'g'); rowData = rowData.replace(rge, listItem[key]);
					}
					/* options */
					var optionS = '';
					var delOption = '';
					var listItemStatus = isNaN(listItem['STATUS']) ? 0 : eval(listItem['STATUS']);
					if(listItemStatus == 255) {
						if(listItemId == currentOrder) {
							optionS += '<a href="#" title="This is your current order"><img src="/assets/images/order-log-op-set-current-x.gif" /></a>';
						} else {
							optionS += '<a href="javascript:setCurrentOrder( '+listItemId+', '+"'"+listItem['NAME']+"'"+'  );" title="Make this your current order..."><img src="/assets/images/order-log-op-set-current.gif" /></a>';
						}
						delOption = '<a href="javascript:removeOrder( '+listItemId+' );" title="Remove this order..."><img src="/assets/images/order-log-op-delt.gif" /></a>';
					} else {
						delOption = '<img src="/assets/images/order-log-op-delt-x.gif" />';
					}
					optionS += '<a href="javascript:duplicateOrder( '+listItemId+' );" title="Duplicate this order..."><img src="/assets/images/order-log-op-dupe.gif" /></a>';
					optionS += delOption;
					rowData = rowData.replace(/__OPTIONS__/g, optionS);
					$(this._listContainer).append(rowData);
				}
			}
			
		},
		
		writeCartProducts : function() {
			
			/* list setup? */
			if(this._listData == null) {
				return false;
			}
			
			/* clear contents */
			$(this._listContainer).html("<!-- -->");

			/* write list parts */
			for(var i = 0; i < this._listData.length; i++) {
				var rowData 	= this._listAbstract;
				var listItem 	= this._listData[i];
				if(listItem != -127) {
					for(var k = 0; k < this._listDataKeys.length; k++) {
						var key =  this._listDataKeys[k]; var kys = "__" + this._listDataKeys[k] + "__";
						var rge = new RegExp(kys, 'g'); rowData = rowData.replace(rge, listItem[key]);
					}
					$(this._listContainer).append(rowData);
				}
			}
			
			/* regenerate summary */
			this.writeCartSummary();
			
		},
		
		writeCartSummary : function() {
			
			var cost = 0;
			for(var i=0; i<this._listData.length; i++) {
				var listItem 	= this._listData[i];
				if(listItem != -127) {
					cost += (eval(listItem['PRICE']) * eval(listItem['QUANTITY']));
				}
			}
			var gst = cost / 10;
			$('#cart-summary-cost').text("$"+currencyFormatted(cost));
			$('#cart-summary-cost-gst').text("$"+currencyFormatted(gst));
			$('#cart-summary-cost-total').text("$"+currencyFormatted((cost+gst)));
		},
		
		reWriteCartQuatities : function() {
			
			/* list setup? */
			if(this._listData == null) {
				return false;
			}
			
			/* write list parts */
			for(var i = 0; i < this._listData.length; i++) {
				var rowData 	= this._listAbstract;
				var listItem 	= this._listData[i];
				if(listItem != -127) {
					var quant = listItem['QUANTITY'];
					var quanf = 'inqnt-' + listItem['ID'];
					$('#'+quanf+'').attr("value",quant);
				}
			}
			
			/* regenerate summary */
			this.writeCartSummary();
			
		}
		
	}
	
};
var $ros = RetailerOrderSystem;
function RetailerOrderSystem_AjaxCallback() {
	if( $ros._ajax.readyState != 4 ) {
		return false;
	}
	$ros._ajaxResponse($ros._ajax.responseText);		
}