

function HHcartDisplaySmall() {
	var randomnumber=Math.floor(Math.random()*9999);

	urlstr = "rn="+ randomnumber;
	$.ajax({
		type: "GET",
		url: "/includes/inc.ajax_call.php",
		data: "modFunction=cartDisplaySmall&"+ urlstr,
		success: function(msg){
			$("#hhStoreCartContents").html(msg);
		}
	});
}

function HHcartChangeCountry(selCountry,stateField) {
	var dropdown = $('select[name='+stateField+']');

	dropdown.html('<option>Loading regions</option>');

	$.ajax({
		type: 'get',
		url: '/includes/inc.ajax_call.php',
		data: { modFunction: 'getCountryStates', country: selCountry },
		dataType: 'json',
		success: function(result){
			dropdown.empty();
			for(var val in result.states)
			{
				var opt = $('<option/>');
				opt.text(result.states[val]);
				opt.val(val);
				dropdown.append(opt);
			}
		}
	});
}

function hhCartSearchProducts(pageNum, target) {
	var randomnumber=Math.floor(Math.random()*9999);
	
	if (typeof(target) == 'undefined')
		target = '#main-content';
	
	if ( pageNum > 1 ) {
		var searchQuery = $("#hhSearchProductsQpages").val();
	}else {
		var searchQuery = $("#hhSearchProductsQ").val();
	}
	urlstr = "viewPage="+ pageNum +"&q="+ php_urlencode(searchQuery) +"&rn="+ randomnumber;

	$.ajax({
		type: "GET",
		url: "/includes/inc.ajax_call.php",
		data: "modFunction=cartSearchProducts&"+ urlstr,
		success: function(msg){
			$(target).html(msg);
		}
	});
	
}

function HHcartFilterByCategory(pageNum, target) {
	var randomnumber=Math.floor(Math.random()*9999);
	var filterStr = "";

	if (typeof(target) == 'undefined')
		target = '#main-content';

	$(".HHCategoryFilters").each( function() {
		if ( $(this).attr("checked") == true ) {
			if ( filterStr != "" ) {
				filterStr += ",";
			}
			filterStr += $(this).val();
		}
	});

	urlstr = "viewPage="+ pageNum +"&rn="+ randomnumber;
	$.ajax({
		type: "GET",
		url: "/includes/inc.ajax_call.php",
		data: "modFunction=cartShowFilteredProducts&filterStr="+ filterStr +"&"+ urlstr,
		success: function(msg){
			$(target).html(msg);
		}
	});

}

function HHcartDisplayLarge() {
	var randomnumber=Math.floor(Math.random()*9999);

	urlstr = "&rn="+ randomnumber;
	$.ajax({
		type: "GET",
		url: "/includes/inc.ajax_call.php",
		data: "modFunction=cartDisplayFull&"+ urlstr,
		success: function(msg){
			$("#hhStoreCartContentsLarge").html(msg);
		}
	});
}

function HHupdateProductQty() {
	urlstr = "";
	prodCnt = 0;
	$(".HHcartQty").each(
		function() {
			
			urlstr += "&newQty["+ $(this).attr("id") +"]="+ $(this).attr("value");
			prodCnt += 1;
		}
	);
	
	$.ajax({
		type: "GET",
		url: "/includes/inc.ajax_call.php",
		data: "modFunction=cartUpdateQty"+ urlstr,
		success: function(msg){
			$("#cartLargeDebug").html(msg);
			HHcartDisplayLarge();
			HHcartDisplaySmall();
		}
	});
}

function HHtoggleShippingAddress(chkStatus) {
	if ( chkStatus.checked == true ) {
		$("#separateBillingAddress").hide();
	}else {
		$("#separateBillingAddress").show();
	}
}

function HHselectShipping() {
	var errMsg = "";
	var urlstr = "";
	
	var fieldNames = {
		Firstname: 'First Name',
		Lastname: 'Last Name',
		Address: 'Street Address',
		State: 'State/Province',
		Phone1: 'Phone Number',
		Phone2: 'Alt. Phone NUmber',
		Country: 'Country',
		City: 'City',
		Postal: 'Postal Code'
	};
	
	shippingSelected = "";
	$(".hhShippingOptions").each(
		function() {
			if ( $(this).attr("checked") == true ) {
				shippingSelected = $(this).attr("value");
				urlstr += "&shippingType="+ $(this).attr("value");
			}
		}
	);

	if ( shippingSelected == "" ) {
		alert("Please select a shipping address.");
		errMsg = "Please select a shipping address.";
	}
	
	if ( errMsg == "" ) {	
		$('.hhShippingFields[name^='+shippingSelected+']').each(function(){
		 	var fieldArr = $(this).attr("name").split("_");
			
			if ($(this).val() == '')
			{
				
				if ( fieldArr[1] == 'Phone2' ) {
					urlstr += "&shipTo_"+ fieldArr[1] +"=";
				}else {
					var field = fieldNames[fieldArr[1]];
					alert('Please enter your ' + field + ' (shipping address)');
					errMsg += 'Missing field: ' + field;
					return false;
				}
			}
			else
			{
				urlstr += "&shipTo_"+ fieldArr[1] +"="+ php_urlencode($(this).attr("value"));
			}
		});
		
		/*$(".hhShippingFields").each(
			function() {
				if ( $(this).attr("name").indexOf(shippingSelected) == 0 ) {
					fieldArr = $(this).attr("name").split("_");
					if ( $(this).attr("value") == "" ) {
						alert("Please enter your "+ fieldArr[1]);
						errMsg += "Missing field: "+ fieldArr[1] +".";
						$(this).focus();
						return false;
					}else {
						urlstr += "&shipTo_"+ fieldArr[1] +"="+ php_urlencode($(this).attr("value"));
						//urlstr += "&"+ $(this).attr("name") +"="+ php_urlencode($(this).attr("value"));
					}
				}
			}
		);*/
	}
	

	
	if ( $("#hhBillingAddressSame").attr("checked") == false ) {
		urlstr += "&billingAddressSame=0";
		
		$(".hhBillingOptions").each(
			function() {
				if ( $(this).attr("checked") == true ) {
					billingSelected = $(this).attr("value");
					urlstr += "&BillingType="+ $(this).attr("value");
				}
			}
		);
		
		if ( billingSelected == "" ) {
			alert("Please select a billing address.");
			errMsg = "Please select a billing address.";
		}
		
		if ( errMsg == "" ) {	
			$('.hhBillingFields[name^='+billingSelected+']').each(function(){
				var fieldArr = $(this).attr("name").split("_");
				if ($(this).val() == '')
				{
					if ( fieldArr[1] == 'Phone2' ) {
						urlstr += "&billTo_"+ fieldArr[1] +"=";
					}else {
						var field = fieldNames[fieldArr[1]];
						alert('Please enter your ' + field + ' (billing address)');
						errMsg += 'Missing field: ' + field;
						return false;
					}
				}
				else
				{
					urlstr += "&billTo_"+ fieldArr[1] +"="+ php_urlencode($(this).attr("value"));
				}
			});
			/*
			$(".hhBillingFields").each(
				function() {
					if ( $(this).attr("name").indexOf(billingSelected) == 0 ) {
						fieldArr = $(this).attr("name").split("_");
						if ( $(this).attr("value") == "" ) {
							alert("Please enter your "+ fieldArr[1]);
							errMsg += "Missing field: "+ fieldArr[1] +".";
							$(this).focus();
							return false;
						}else {
							urlstr += "&billTo_"+ fieldArr[1] +"="+ php_urlencode($(this).attr("value"));
						}
					}else {
						
					}
				}
			);
			*/
		}
		
	}else {
		urlstr += "&billingAddressSame=1";
	}
	
	if ( errMsg == "" ) {
		$.ajax({
			type: "GET",
			url: "/includes/inc.ajax_call.php",
			data: "modFunction=cartSelectShipping&"+ urlstr,
			success: function(msg){
				//$("#shippingdebug").html(msg);
				//document.location = '/store/checkout/';
				document.location = '/store/shippingMethod';
				
			}
		});
	}
}

// optionsElement - jquery expression to prepend before .hhCartOptions below. 
function HHaddProductToCart(productId, optionsQuery) {
	if (typeof(optionsQuery) == 'undefined') optionsQuery = '';
	
	// Get Qty Field
	productQty = $("#hhCartQty_"+productId).attr('value');

	urlstr = "productId="+ productId;
	
	if ( productQty.length > 0 ) {
		//if ( productQty - 0 == productQty ) {
		if (!isNaN(productQty) && productQty != 0) {
			// Valid Qty. Check to make sure the Options are all selected.
			err = false;
			urlstr += "&productQty="+ productQty;
			
			$(optionsQuery + " .hhCartOptions").each(
				function() {
					optionArray = $(this).attr('value').split('[-!-]');
					optionRequired = optionArray[0]; // 'required' or 'optional'
					optionId = optionArray[1];
					optionName = optionArray[2];
					
					optionSelected = 0;
					$(".hhCartOptions_"+ optionId).each(
						function() {
							if ( $(this).attr('checked') == true ) {
								optionSelected = $(this).attr('value');
							}
						}
					);
					urlstr += "&productOptions["+ optionId +"]="+ optionSelected;					
					if ( optionRequired == 'required' && optionSelected == 0 ) {
						alert('Please select an option under "'+ optionName +'".');
						err = true;
					}
				});
			
			if ( err == false ) {

				$.ajax({
					type: "GET",
					url: "/includes/inc.ajax_call.php",
					data: "modFunction=cartAddProduct&"+ urlstr,
					dataType: 'json',
					hh: 'addToCart',
					success: function(response){
						if (response.ok)
							HHcartDisplaySmall();
						else
							alert(response.msg);
							
						//$("#cartDebug").html(msg);
					}
				});
			}else {
				// alert('Error missing required options.');
			}

		}else {
			alert('Please enter a valid quantity for this product.');
			$("#hhCartQty_"+productId).focus();
		}
	}else {
		alert('Please enter a quantity for this product.');
		$("#hhCartQty_"+productId).focus();
	}
}

function HHcartForgotPass() {
	urlstr = "";
	errMsg = "";
	
	if ( $("#hhCartUserLogin").attr("value") != "" ) {
		urlstr += "&hhUsername="+ $("#hhCartUserLogin").attr("value");
	}else {
		errMsg = "Please enter your username or email address.";	
		$("#hhCartUserLogin").focus();
		$("#hhCartLoginFormMsg").html(errMsg);
		$("#hhCartLoginFormMsg").show();
		return false;
	}
	
	if ( errMsg == "" ) {
		$.ajax({
			type: "GET",
			url: "/includes/inc.ajax_call.php",
			data: "modFunction=cartForgotPass&"+ urlstr,
			success: function(msg){
				$("#hhCartLoginFormMsg").html(msg);
				$("#hhCartLoginFormMsg").show();
			}
		});
	}
}

function HHcartLogin(redirectUrl) {
	urlstr = "";
	errMsg = "";
	
	if ( $("#hhCartUserLogin").attr("value") != "" ) {
		urlstr += "&hhUsername="+ $("#hhCartUserLogin").attr("value");
	}else {
		errMsg = "Please enter your username or email address.";	
		$("#hhCartUserLogin").focus();
		$("#hhCartLoginFormMsg").html(errMsg);
		$("#hhCartLoginFormMsg").show();
		return false;
	}
	
	if ( $("#hhCartUserPassword").attr("value") != "" ) {
		urlstr += "&hhPassword="+ $("#hhCartUserPassword").attr("value");
	}else {
		errMsg = "Please enter your password.";	
		$("#hhCartUserPassword").focus();
		$("#hhCartLoginFormMsg").html(errMsg);
		$("#hhCartLoginFormMsg").show();
		return false;
	}
	
	if ($('#hhRememberMe').is(':checked'))
		urlstr += '&hhRememberMe=1';
	
	if ( errMsg == "" ) {
		$.ajax({
			type: "GET",
			url: "/includes/inc.ajax_call.php",
			data: "modFunction=cartAccountAuth&"+ urlstr,
			success: function(msg){
				msg = msg.replace(/^\s*/, '');
				msg = msg.replace(/\s*$/, '');
				if ( msg == "MEMBER_AUTH_FAILURE" ) {
					errMsg = "You have entered an invalid username & password combination.";	
					$("#hhCartUserPassword").attr('value','');
					$("#hhCartUserPassword").focus();
					$("#hhCartLoginFormMsg").html(errMsg);
					$("#hhCartLoginFormMsg").show();
					return false;
				}else if ( msg == "MEMBER_AUTH_SUCCESS" ) {
					if (redirectUrl)
						document.location = redirectUrl;
					else
						document.location = '/store/shipping';
				}else {
					errMsg = "Unable to verify your username & password combination. Please try again later.";	
					$("#hhCartUserPassword").attr('value','');					
					$("#hhCartUserPassword").focus();
					$("#hhCartLoginFormMsg").html(errMsg);
					$("#hhCartLoginFormMsg").show();
					return false;
				}
			}
		});
	}
}

function HHcartRegisterAccount() {
	urlstr = "";
	errMsg = "";
	
	if ( $("#hhNewAccEmail").attr("value") != "" ) {
		if ( $("#hhNewAccEmail").attr("value") != $("#hhNewAccEmailVerify").attr("value") ) {
			errMsg = "Your email address and verification do not match.";
			alert("Your email address and verification do not match.");
			$("#hhNewAccEmailVerify").focus();
			return false;
		}else {
			urlstr += "&NewAccEmail="+ $("#hhNewAccEmail").attr("value");
		}
	}else {
		errMsg = "Please enter your email address.";
		alert("Please enter your email address.");
		$("#hhNewAccEmail").focus();
		return false;
	}
	
	if ( $("#hhNewAccPassword").attr("value").length >= 8 ) {
		if ( $("#hhNewAccPassword").attr("value") != $("#hhNewAccPasswordVerify").attr("value") ) {
			errMsg = "Your password and password verification do not match.";
			alert("Your password and password verification do not match.");
			$("#hhNewAccPasswordVerify").focus();
			return false;
		}else {
			urlstr += "&NewAccPassword="+ $("#hhNewAccPassword").attr("value");
		}
	}else {
		errMsg = "Please select a password. (8 Character Minimum)";
		alert("Please select a password. (8 Character Minimum)");
		$("#hhNewAccPassword").focus();
		return false;
	}
	
	if ( $("#hhNewAccFirstname").attr("value") != "" ) {
		urlstr += "&NewAccFirstname="+ $("#hhNewAccFirstname").attr("value");
	}else {
		errMsg = "Please enter your first name.";
		alert("Please enter your first name.");
		$("#hhNewAccFirstname").focus();
		return false;
	}
	
	if ( $("#hhNewAccLastname").attr("value") != "" ) {
		urlstr += "&NewAccLastname="+ $("#hhNewAccLastname").attr("value");
	}else {
		errMsg = "Please enter your last name.";
		alert("Please enter your last name.");
		$("#hhNewAccLastname").focus();
		return false;
	}
	
	if ( $("#hhNewAccAddress").attr("value") != "" ) {
		urlstr += "&NewAccAddress="+ $("#hhNewAccAddress").attr("value");
	}else {
		errMsg = "Please enter your street address.";
		alert(errMsg);
		$("#hhNewAccAddress").focus();
		return false;
	}
	
	if ( $("#hhNewAccCity").attr("value") != "" ) {
		urlstr += "&NewAccCity="+ $("#hhNewAccCity").attr("value");
	}else {
		errMsg = "Please enter your city.";
		alert(errMsg);
		$("#hhNewAccCity").focus();
		return false;
	}
	
	if ( $("#hhNewAccState").attr("value") != "" ) {
		urlstr += "&NewAccState="+ $("#hhNewAccState").attr("value");
	}else {
		errMsg = "Please enter your state/province.";
		alert(errMsg);
		$("#hhNewAccState").focus();
		return false;
	}
	
	if ( $("#hhNewAccCountry").val() != "" ) {
		urlstr += "&NewAccCountry="+ $("#hhNewAccCountry").val();
	}else {
		errMsg = "Please enter your country.";
		alert(errMsg);
		$("#hhNewAccCountry").focus();
		return false;
	}
	
	if ( $("#hhNewAccPostal").attr("value") != "" ) {
		urlstr += "&NewAccPostal="+ $("#hhNewAccPostal").attr("value");
	}else {
		errMsg = "Please enter your zip/postal code.";
		alert(errMsg);
		$("#hhNewAccPostal").focus();
		return false;
	}
	
	if ( errMsg == "" ) {
		urlstr = "";
		
		$(".hhNewAccFields").each(
			function() {
				urlstr += "&"+ $(this).attr("name") +"="+ php_urlencode($(this).attr("value"));
			});
		$.ajax({
			type: "GET",
			url: "/includes/inc.ajax_call.php",
			data: "modFunction=cartAccountRegister&"+ urlstr,
			success: function(msg){
				if ( msg.indexOf('<!--ACCOUNT_CREATION_ERROR-->') != -1 ) {
					alert("Unable to create your account. Please try again shortly.");
					return false;
				}else {
					//hhAccountCreated
					$("#hhAccountInterface").hide();
					$("#hhAccountCreated").show();
					//alert("Your account has been successfull
					//alert('not found msg ret: '+  msg.indexOf('<!--ACCOUNT_CREATION_ERROR-->'));
				}
				//$("#HHcartRegisterDebug").html(msg);
			}
		});
	}
}

function HHverifyPaymentForm(f)
{
	if (f.ccNum.value == '') 
	{
		alert('Please enter your credit card number');
		return false;
	}
	
	if (f.ccSecurity.value == '')
	{
		alert('Please enter your credit card\'s security code');
		return false;
	}
	
	f.submit();
}

function addCoupon()
{
	var couponCode = $('input[name=coupon]').val();
	$.ajax({
		type: 'GET',
		url: '/includes/inc.ajax_call.php',
		data: { modFunction: 'cartAddCoupon', coupon: couponCode },
		success: function(msg){
			HHcartDisplayLarge();
			alert(msg);
		}
	});
}

function HHsetShippingOption(descr, amount)
{
	document.shippingOptionForm.descr.value = descr;
	document.shippingOptionForm.amount.value = amount;
}

function HHselectShippingOption()
{
	var f = document.shippingOptionForm;
	if ($(f).find('input:checked[name=option]').length == 0)
	{
		alert('Please select a shipping option');
		return false;
	}
	
	var query = 'modFunction=cartSelectShippingOption&'+$(document.shippingOptionForm).serialize();
	
	$.ajax({
		type: 'GET',
		url: '/includes/inc.ajax_call.php',
		data: query,
		success: function(msg){
			document.location = '/store/checkout';
		}
	});
}


function HHaddProductToFavorites(id)
{
	var query = 'modFunction=cartAddFavoriteProduct&productId='+id;
	
	$.ajax({
		type: 'GET',
		url: '/includes/inc.ajax_call.php',
		data: query,
		success: function(msg){
			alert(msg);
	
			$('#remFav'+id).show();
			$('#addFav'+id).hide();
		}
	});
}

function HHremoveFavorite(id)
{
	if (!confirm('Are you sure you want to remove this product from your favorites?')) return;
	
	var query = 'modFunction=cartRemoveFavoriteProduct&productId='+id;
	
	$('#fav'+id).fadeOut('fast', function() { $(this).remove(); });
	
	$.ajax({
		type: 'GET',
		url: '/includes/inc.ajax_call.php',
		data: query,
		success: function(result){
			$('#remFav'+id).hide();
			$('#addFav'+id).show();
		}
	});
}

function HHcopyOrder(id)
{
	if (!confirm('Are you sure? Your current cart contents will be cleared')) return;
	
	$.ajax({
		type: 'GET',
		url: '/includes/inc.ajax_call.php',
		data: 'modFunction=cartCopyOrder&orderId='+id,
		success: function(smallCart){
			//$('#hhStoreCartContents').html(smallCart);
			document.location = '/store/viewcart/';
		}
	});
}

function HHviewOrderedProducts(id)
{
	$('#ordered'+id).slideToggle();
}

function HHverifyProfileField(field, form, displayErr)
{
	if (form[field].value == '')
	{
		alert(displayErr);
		return false;
	}
	return true;
}

function HHcartUpdateAccount()
{
	var f = document.HHprofileForm;
	var query = $.param({
		modFunction: 'cartUpdateAccount'
	});
	
	query += '&' + $(f).serialize();
	
	if (!HHverifyProfileField('email', f, 'Please enter your email address')) return;
	if (!HHverifyProfileField('firstname', f, 'Please enter your first name')) return;
	if (!HHverifyProfileField('lastname', f, 'Please enter your last name')) return;
	
	if (f.password.value != '' && (f.password.value != f.password_conf.value))
	{
		alert('Passwords do not match!');
		return;
	}
	
	$.ajax({
		type: 'GET',
		url: '/includes/inc.ajax_call.php',
		data: query,
		success: function(msg){
			alert(msg);
		}
	});
}














