/*
user.js - Written by Todd Moyer - Copyright 2010, 2011.

Unauthorized use is not permitted.
*/

function addCart(formName, gotoPage, dialogBox) {

	if (dialogBox != null) {
		var dialogHTML = '';
		var titleBarHTML = 'Adding to cart';
		dialogHTML += '<div style="text-align:center; margin: 20px;"><img src="/images/ajax-loader.gif"/> Adding to shopping cart</div>';
		$('#' + dialogBox).html(dialogHTML);
		$('#' + dialogBox).dialog('option', 'title', titleBarHTML);
		$('#' + dialogBox).dialog('option', 'closeText', '');
		$('#' + dialogBox).dialog('open');
		centerDialogs();
	}

	//var xmlDoc = newXML();
	var userData = getDataSource('user');
	var cartNode = $(userData).find('ShoppingCart');
	var cartChildren = $(cartNode).children();
	var itemsTotal = 0;
	var cartTotal = 0;
	var formIndex;

	if (document.forms) {
		for (var i=0; i<pageForms.length; i++) {
			var thisFormName = pageForms[i].formName;
			if (formName == thisFormName) {
				formIndex = i;
				break;
			}
		}
	}
	var formObject = pageForms[formIndex];
	
	var formElements = formObject.inputElements;
	var productAttributes = new Array();
	var testCount = 0;
	for (var j=0; j<formElements.length; j++) {
		var inputName = formElements[j].inputName;
		var inputElement = $('#' + inputName);
		var inputValue = inputElement.val();
		productAttributes[inputName] = inputValue;
		if ((inputName != 'CartItemId') && (inputName != 'qty') && (inputName != 'ext') && (inputName != 'weight')) {
			//alert(inputName);
			testCount += 1;
		}
		debugOut('     ' + inputName + ' = ' + inputValue);
	}

	if ((productAttributes['price'] == '') || (productAttributes['price'] == null)) {
		productAttributes['price'] = 0;
	}
	
	

	// loop through the ShoppingCart in user data, see what's already there...
	for (var i=0; i<cartChildren.length; i++) {
		if (cartChildren[i].nodeName == 'CartItem') {
			var item = $(cartChildren[i]);
			var itemChildren = item.children();
			var cartItemMatch = true;
			var checkCount = 0;
			
			for (var j=0; j<itemChildren.length; j++) {
				// check to see if everything except [CartItemId, qty, ext, weight] are the same
				// if so, just add quantities
				var cartItemAttribute = itemChildren[j];
				var cartItemAttributeName = cartItemAttribute.nodeName;
				var cartItemAttributeValue = $(cartItemAttribute).text();
				if ((cartItemAttributeName != 'CartItemId') &&
				    (cartItemAttributeName != 'qty') &&
				    (cartItemAttributeName != 'weight') &&
				    (cartItemAttributeName != 'ext')) {
					checkCount += 1;
					if (productAttributes[cartItemAttributeName] != cartItemAttributeValue) cartItemMatch = false;
				}
			}
			if (testCount > checkCount) cartItemMatch = false;
		}
		if (cartItemMatch) break;
	}

	if (cartItemMatch) {
		debugOut('Found item match, adding quantities');
		var qtyNode = item.children('qty');
		var newQtyVal = parseInt(qtyNode.text()) + parseInt(productAttributes['qty']);
		qtyNode.text(newQtyVal);

		var extNode = item.children('ext');
		var newExtVal = newQtyVal * parseFloat(productAttributes['price']);
		newExtVal = moneyFormat(newExtVal);
		extNode.text(newExtVal);
	}
	else {
		// add new CartItemNode
		debugOut('Adding new item to cart. cartNode=' + $(cartNode).text());
		var doc = newXML();
		var newItemElement = doc.createElement('CartItem');

		var cartItemId = (Math.round(Math.random() * 899999) + 100000) + '';
		cartItemId += (Math.round(Math.random() * 899999) + 100000) + '';
		cartItemId += (Math.round(Math.random() * 899999) + 100000) + '';

		var doc = newXML();
		var prodAttrElement = doc.createElement('CartItemId');
		$(prodAttrElement).text(cartItemId);
		$(newItemElement).append(prodAttrElement);

		var newExtVal = parseInt(productAttributes['qty']) * parseFloat(productAttributes['price']);
		var doc = newXML();
		var prodAttrElement = doc.createElement('ext');
		$(prodAttrElement).text(moneyFormat(newExtVal));
		$(newItemElement).append(prodAttrElement);

		for  (var attrName in productAttributes) {
			var doc = newXML();
			var prodAttrElement = doc.createElement(attrName);
			$(prodAttrElement).text(productAttributes[attrName]);
			$(newItemElement).append(prodAttrElement);
		}
		$(cartNode).append(newItemElement);
	}

	// update cart totals
	updateCartTotals(cartNode);

	if (gotoPage != null) {
		saveUserData(userData, false);
		window.location = gotoPage;
	}
	else {
		saveUserData(userData, true, 'afterAdd("' + dialogBox + '")');
	}
		
}
function afterAdd(dialogBox) {
	var closeAction = "$('#" + dialogBox + "').dialog('close');";
	if (dialogBox != 'null') {
		var dialogHTML = '';
		var titleBarHTML = 'Item added to cart';
		dialogHTML += '<div style="text-align:center; margin: 20px;">Item added to shopping cart<br/><br/>';
		dialogHTML += '<a class="grayButton" style="margin:10px" href="/cart" Margin="20px">VIEW CART</a>';
		dialogHTML += '<a class="grayButton" style="margin:10px" href="#" Margin="20px" onclick="' + closeAction + '">CLOSE</a>';
		dialogHTML += '</div>';
		$('#' + dialogBox).html(dialogHTML);
		$('#' + dialogBox).dialog('option', 'title', titleBarHTML);
	}
}
function removeCartItem(cartItemId) {
	$('#lineitem-' + cartItemId).hide(200);

	var userData = getDataSource('user');
	var cartNode = $(userData).find('ShoppingCart');
	var cartChildren = $(cartNode).children();

	for (var i=0; i<cartChildren.length; i++) {
		if (cartChildren[i].nodeName == 'CartItem') {
			var thisItemId = $(cartChildren[i]).children('CartItemId');
			if ($(thisItemId).text() == cartItemId) {
				$(cartChildren[i]).remove();
				break;
			}
		}
	}
	updateCartTotals(cartNode);
	saveUserData(userData, true);
}
function updateCartPromo(inputElement) {
	var userData = getDataSource('user');
	var cartNode = $(userData).find('ShoppingCart');
	var cartPromoCodeNode = $(cartNode).children('CartPromoCode');
	var cartPromoCode = $(inputElement).val();
	
	cartPromoCode = String(cartPromoCode).toUpperCase();

	$(inputElement).val(cartPromoCode);
	$(cartPromoCodeNode).text(cartPromoCode);

	updateCartTotals(cartNode);

	saveUserData(userData, true);
}
function updateCartQty(inputElement, cartItemId) {
	var userData = getDataSource('user');
	var cartNode = $(userData).find('ShoppingCart');
	var cartChildren = $(cartNode).children();

	var qtyVal = String($(inputElement).val());
	if (qtyVal == '') {
		qtyVal = 0;
	}
	else {
		var qtyValNumberString = '';
		for (var i=0; i<qtyVal.length; i++) {
			var thisChar = qtyVal.charAt(i);
			thisChar = parseInt(thisChar);
			if (!isNaN(thisChar)) qtyValNumberString += thisChar;
		}
		qtyVal = parseInt(qtyValNumberString);
		if (isNaN(qtyVal)) qtyVal = 1;
		$(inputElement).val(qtyVal);
	}

	for (var i=0; i<cartChildren.length; i++) {
		if (cartChildren[i].nodeName == 'CartItem') {
			var thisItemId = $(cartChildren[i]).children('CartItemId');
			if ($(thisItemId).text() == cartItemId) {
				var itemPrice = $(cartChildren[i]).children('price');
				var itemQty = $(cartChildren[i]).children('qty');
				var itemExt = $(cartChildren[i]).children('ext');
				
				var newExtVal = qtyVal * parseFloat($(itemPrice).text());
				newExtVal = moneyFormat(newExtVal);
				itemExt.text(newExtVal);
				itemQty.text(qtyVal);

				$('#ext-' + cartItemId).html('$' + newExtVal);

				break;
			}
		}
	}
	updateCartTotals(cartNode);
	saveUserData(userData, true);
}
function updateCartTotals(cartNode) {
	var cartChildren = $(cartNode).children();
	var parsonalNode = $(cartNode).parent().children('Personal');
	var itemsTotalNode = $(cartNode).children('CartItemsTotal');
	var cartPromoCodeNode = $(cartNode).children('CartPromoCode');
	var cartPromoCode = $(cartPromoCodeNode).text();
	var discountNode = $(cartNode).children('CartDiscount');
	var taxNode = $(cartNode).children('CartTax');
	var shippingNode = $(cartNode).children('CartShipping');
	var totalNode = $(cartNode).children('CartTotal');

	var itemsTotal = 0;
	var weightTotal = 0;
	for (var i=0; i<cartChildren.length; i++) {
		if (cartChildren[i].nodeName == 'CartItem') {
			var itemExt = $(cartChildren[i]).children('ext');
			var itemWt = $(cartChildren[i]).children('weight');
			var itemQty = $(cartChildren[i]).children('qty');
			itemsTotal += parseFloat($(itemExt).text());
			weightTotal += parseFloat($(itemWt).text()) * parseInt($(itemQty).text());
		}
	}
	var itemsTotalMF = moneyFormat(itemsTotal);
	debugOut('weightTotal=' + weightTotal);

	// calculate discount
	if (cartPromoCode != '') {
		var discountValue = 0;
		var promoData = getDataSource('promocodes');
		var promos = $(promoData).find('PromoCode');

		for (var i=0; i<promos.length; i++) {
			var thisCode = $(promos[i]).children('Code').text();
			var thisCodeActive = $(promos[i]).children('CodeActive').text() == 'true';
			thisCode = String(thisCode).toUpperCase();
			if ((thisCode == cartPromoCode) && (thisCodeActive)) {
				var flatDiscount = $(promos[i]).children('FlatDiscount').text();
				var percentDiscount = $(promos[i]).children('PercentDiscount').text();
			
				if ((flatDiscount != null) && (flatDiscount != '')) {
					flatDiscount = parseFloat(flatDiscount);
					if (!isNaN(flatDiscount)) discountValue += flatDiscount;
				}
				if ((percentDiscount != null) && (percentDiscount != '')) {
					percentDiscount = parseFloat(percentDiscount);
					if (!isNaN(percentDiscount)) discountValue += (percentDiscount / 100) * itemsTotal;
				}
			}
		}
	}

	var shipToState;
	if ($(parsonalNode).children('UseBillingForShipping').text() == 'true') shipToState = $(parsonalNode).find('BillingState').text();
	else shipToState = $(parsonalNode).find('ShippingState').text();

	// calculate tax
	if (shipToState == siteTaxableState) var taxValue = (siteTaxRate / 100) * itemsTotal;
	else var taxValue = 0;
		

	// calculate shipping
	var shippingValue = 0;
	var shippingMethod = $(cartNode).find('CartShippingMethod').text();
	if (shippingMethod != '') {
		var shippingData = getDataSource('shipping');
		var shipTypeNode = $(shippingData).find('ShipType:contains("' + shippingMethod + '")');
		var weightBrackets = $(shipTypeNode).find('WeightBracket');
		var highestWeight = -1;
		var highestWeightBracketNode;
		var foundWeightBracketNode = null;

		for (var i=0; i<weightBrackets.length; i++) {
			var minWt = parseFloat($(weightBrackets[i]).children('MinWeight').text());
			var maxWt = parseFloat($(weightBrackets[i]).children('MaxWeight').text());
			if (minWt > highestWeight) highestWeightBracketNode = weightBrackets[i];
			if ((weightTotal >= minWt) && (weightTotal <= maxWt)) {
				foundWeightBracketNode = weightBrackets[i];
				break;
			}
		}
		if (foundWeightBracketNode == null) foundWeightBracketNode = highestWeightBracketNode;

		var costRegions = $(foundWeightBracketNode).find('CostRegion');
		var foundCostRegion = null;
		for (var i=0; i<costRegions.length; i++) {
			
			var regionStates = $(costRegions[i]).find('States').text();

			if (shipToState == regionStates) {
				foundCostRegion = costRegions[i];
				break;
			}
			else if ((shipToState != '') && (regionStates.indexOf(shipToState) > -1)) {
				foundCostRegion = costRegions[i];
				break;
			}
		}
		if (foundCostRegion != null) {
			shippingValue = parseFloat($(foundCostRegion).find('Cost').text());
			var regionNum = $(foundCostRegion).find('RegionNumber').text();
		}

		debugOut('RegionNumber=' + regionNum);
	}

	if (isNaN(itemsTotal)) itemsTotal = 0;
	if (isNaN(discountValue)) discountValue = 0;
	if (isNaN(taxValue)) taxValue = 0;
	if (isNaN(shippingValue)) shippingValue = 0;

	var discountValueMF = moneyFormat(discountValue);
	var shippingValueMF = moneyFormat(shippingValue);
	var taxMF = moneyFormat(taxValue);
	var totalValue = itemsTotal - discountValue + taxValue + shippingValue;
	var totalValueMF = moneyFormat(totalValue);

	$('#itemsTotal').html('$' + itemsTotalMF);
	$('#cartDiscount').html('- $' + discountValueMF);
	$('#cartTax').html('$' + taxMF);
	$('#cartShipping').html('$' + shippingValueMF);
	$('#cartTotal').html('$' + totalValueMF);

	if (discountValue != 0) $('#discountBlock').css('display', 'block');
	else $('#discountBlock').css('display', 'none');

	$('#Subtotal').val(itemsTotalMF);
	$('#Discount').val(discountValueMF);
	$('#Tax').val(taxMF);
	$('#Shipping').val(shippingValueMF);
	$('#Total').val(totalValueMF);

	$(itemsTotalNode).text(itemsTotalMF);
	$(discountNode).text(discountValueMF);
	$(taxNode).text(taxMF);
	$(shippingNode).text(shippingValueMF);
	$(totalNode).text(totalValueMF);
}

function initUserData() {
	var userData;
	//var userId = getCookie('user-id');
	if ((userId != null) && (userId != '')) {
		// fetch user data from server
		$.ajax({
			// load the data XML
			type: 'POST',
			processData: false,
			url: '/getuser.php',
			dataType: 'xml',
			data: 'userId=' + userId + '&sessionId=' + sessionId,
			async: false,
			success: function(data) {
				userData = data;
				deleteCookieCrumbs('user-data');
			},
			error: function(req, textStatus, errorThrown) {
				alert("error loading user data xml: textStatus=" + textStatus);
			}
		});
	}
	else {
		// this could be replaced with HTML5 sessionStorage or client database in the future
		
		var userDataCookie = getCookieCrumbs('user-data');
		
		if ((userDataCookie != null) && (userDataCookie != '')) {
			userData = getDataSource('emptyData');
			userData = cookieDecodeXML(userDataCookie, $(userData).find('Data'));
		}
		else {
			userData = getDataSource('userDataBlank');
		}
	
		
	}
	return userData;
}
var updateUserDataTimer;
function updateUserFieldDelayed(fieldName, newValue) {
	clearTimeout(updateUserDataTimer);
	updateUserField(fieldName, newValue, 2000);
}
function updateUserField(fieldName, newValue, delayAmount) {
	var userData = getDataSource('user');
	var updateNode = $(userData).find(fieldName);
	$('#saved').css('display', 'none');

	if (updateNode != null) {
		if (updateNode.length == 1) {
			$(updateNode).text(newValue);
			debugOut('Setting ' + fieldName + ' = ' + newValue);

			if ((fieldName.indexOf('State') != -1) || (fieldName == 'UseBillingForShipping') || (fieldName == 'CartShippingMethod')) {
				// tax and shipping may need to be recalculated
				updateCartTotals($(userData).find('ShoppingCart'));
			}
			if (delayAmount == null) saveUserData(userData, true);
			else updateUserDataTimer = setTimeout('saveUserData(null, true)', delayAmount);
		}
		else debugOut(fieldName + ' found ' + updateNode.length + ' time(s) in user data.');
	}
}

function saveUserData(userData, asynch, callback) {
	
	var userId = getCookie('user-id');

	if (userData == null) userData = getDataSource('user');

	$('#saving').css('display', 'inline');
	$('#saved').css('display', 'none');
	$('#validation').css('display', 'none');

	if (userId != null) {
		// post to server
		

		var formSendData = getDataSource('user');
		formSendData = $(formSendData).find('User');

		var userDataSerialized = serialize(formSendData, 0, true, true);
		userDataSerialized = String(userDataSerialized).replace('&', '%26');
		
		$.ajax({
			type: 'POST',
			processData: false,
			url: '/updateuser.php',
			dataType: 'xml',
			data: 'userId=' + userId + '&sessionId=' + sessionId + '&xmldoc=' + userDataSerialized,
			async: asynch,
			success: function(updateResponse) {
				var responseData = $(updateResponse).find('UserUpdateResponse');
				if ($(responseData).attr('Success') == 'true') {
					var successMessage = $(responseData).attr('SuccessMessage');
					$('#saving').css('display', 'none');
					$('#saved').css('display', 'inline');
					$('#validation').css('display', 'none');
					if ((successMessage != null) && (successMessage != '')) alert(successMessage);
				}
				else {
					var validationMessage = $(responseData).attr('ValidationMessage');
					if ((validationMessage == null) || (validationMessage == '')) validationMessage = 'Error saving account.';
					$('#validation').html(validationMessage);
					$('#saving').css('display', 'none');
					$('#saved').css('display', 'none');
					$('#validation').css('display', 'inline');
				}
				eval(callback);
			},
			error: function(req, textStatus, errorThrown) {
				alert("error updating user data: textStatus=" + textStatus);
				eval(callback);
			}
		});
	}
	else {
		// store updates in cookies
		var cookieReadyData = cookieEncodeXML($(userData).find('Data'));
		setCookieCrumbs('user-data', cookieReadyData);
		setTimeout("$('#saving').css('display', 'none');$('#saved').css('display', 'inline');", 500);
	}
}
function clearUserCookies() {
	deleteCookieCrumbs('user-data');
}
function checkClearUserIdCookie() {
	var clearUserCookie = getCookie('delete-user-id');	
	if (clearUserCookie == 'true') {
		debugOut('Deleteing user ID cookie');
		deleteCookie('user-id');
		deleteCookie('delete-user-id');
		userId = null;
	}
}
function clearCart() {
	var userData = getDataSource('user');
	var cartNode = $(userData).find('ShoppingCart');
	var itemsTotalNode = $(cartNode).children('CartItemsTotal');
	var discountNode = $(cartNode).children('CartDiscount');
	var promoCodeNode = $(cartNode).children('CartPromoCode');
	var taxNode = $(cartNode).children('CartTax');
	var shippingNode = $(cartNode).children('CartShipping');
	var totalNode = $(cartNode).children('CartTotal');
	
	$(cartNode).find('CartItem').remove();

	$(itemsTotalNode).text('0.00');
	$(taxNode).text('0.00');
	$(shippingNode).text('0.00');
	$(totalNode).text('0.00');
	$(discountNode).text('0.00');
	$(promoCodeNode).text('');

	saveUserData(userData, true);

	debugOut('Cart cleared.');
	
}
function logOut() {
	deleteCookieCrumbs('user-data');
	deleteCookie('session-id');
	deleteCookie('user-id');
	window.location = '/';
}


