/* JQUERY METHODS */
$(document).ready(function(){
	//test where the user came from to determine the correct protocol
	var uri = parseUri(location.href);	
	var site = uri.protocol + "://www.soapothecary.com";
	var sessionid = $("#sessionID").text();
	var userid = $("#userID").text();
	$("#start_date").datepicker();
	$("#end_date").datepicker();
	
	/* <<== PAGE LOAD DEFAULT ACTIONS ==>> */
	$('.hidden').hide();
	$('#formCreateAccount').hide();
	$('#errorTextjQuery').hide();
	$("#username").val("");
	$("#password").val("");
	
	// checkout page
	if (document.location == site + '/checkout.php') {
		//getUser();
	}
	
	/* <<== GET CART ITEM COUNT ==>> */
	refreshCartTotals();
	
	/* <<== CHECK LOGIN STATUS ==>> */
	checkLoginStatus();
	
	/* <<== ADD ITEM TO CART ==>> */		
	$("#buttonAddToCart").click(function() {
		var productid = $("#productID").text();
		var qty = $("#qty").val();
		var price = $('#prices option:selected').val();
		var scents = $('#scents option:selected').map(function(){ return this.value }).get().join(", ");

		var dataString = 'productid=' + productid + '&qty=' + qty + '&price=' + price + '&scents=' + scents;
		//alert(dataString);
		//return false;
		//alert(site + "/webservice/cart/add"); 
		$.ajax({
			type: "POST",
			url: "/webservice/cart/add",
			data: dataString,
			async: true,
			dataType: 'text',
			success: function(msg) {
				//alert(msg);
				if (msg == 1){
					window.location = "/basket"; 
				}
				else {
					alert("There was an issue trying to add this to your cart, please try again.");
				}	
			},
			error: function(jqXHR){
				//alert(jqXHR.statusText);
			}
		});
		return false;
	});
	
	/* <<== LOGIN ==>> */		
	$("#buttonLogin").click(function() {
		$('.hidden').hide();
		var action = $("#action").text();
		var sessionid = $("#sessionID").text();
		var username = $("#username").val();
		var password = $("#password").val();
		
		// error checking
		if (username == "") {
			$("#username_error").html("This field is required.");
			$("#username_error").show();
			$("#username").focus();
			return false;
		}
		
		if (password == "") {
			$("#password_error").html("This field is required.");
			$("#password_error").show();
			$("#password").focus();
			return false;
		}
		
		// POST DATA
		var dataString = 'action=' + action + '&sessionid=' + sessionid + '&username=' + username + '&password=' + password;

		// AJAX CALL
		$.ajax({
		type: "POST",
		url: "/ajax/auth.php",
		dataType: 'json',
		async: true,
		data: dataString,
		success: function(msg) {
			//alert(msg.Status + "::" + msg.Field + "::" + msg.Message);
			if (msg.Status == "0") {
				if (msg.Field == "Username") {
					$("#username_error").html(msg.Message);
					$("#username").val("");
					$("#username_error").show();
					$("#username").focus();
					return false;
				}
				else if (msg.Field == "Password") {
					$("#password_error").html(msg.Message);
					$("#password").val("");
					$("#password_error").show();
					$("#password").focus();
					return false;
				}
			}
			else {
				$("#username").val("");
				$("#password").val("");
				checkLoginStatus();
				refreshCartTotals();
				window.location = "/index.php";
			}
		}
		});
		
		return false;
	});
	
	/* <<== LOGOUT ==>> */		
	$("#linkLogout").click(function() {
		// POST DATA
		var dataString = 'action=logout';

		// AJAX CALL
		$.ajax({
		type: "POST",
		url: "/ajax/auth.php",
		data: dataString,
		async: true,
		success: function() {
			checkLoginStatus();
		}
		});
		return false;
	});
	
	/* <<== FORGOT PASSWORD ==>> */		
	$("#buttonForgot").click(function() {
		$('.hidden').hide();
		var action = $("#action").text();
		var email = $("#email").val();
		
		// error checking
		if (email == "") {
			$("#email_error").html("This field is required.");
			$("#email_error").show();
			$("#email").focus();
			return false;
		}
		else if (!(isValidEmailAddress(email))) {
			$("#email_error").html("This email address you entered is not formatted correctly.");
			$("#email_error").show();
			$("#email").focus();
			return false;
		} 
		
		// POST DATA
		var dataString = 'action=' + action + '&email=' + email;

		// AJAX CALL
		$.ajax({
		type: "POST",
		url: "/ajax/auth.php",
		dataType: 'json',
		data: dataString,
		async: true,
		success: function(msg) {
			//alert(msg.Status);			
			if (msg.Status == "0") {
				$("#email_error").html(msg.Message);
				$("#email").val("");
				$("#email_error").show();
				$("#email").focus();
				return false;
			}
			else {
				$("#email").val("");
				alert('An email has been sent to ' + email + ' with instructions on how to reset your password.');
			}
		}
		});		
		return false;
	});
	
	/* <<== USER REGISTRATION ==>> */		
	$("#buttonRegister").click(function() {
		$('.hidden').hide();
		var action = $("#action").text();
		var firstname = $("#firstname").val();
		var lastname = $("#lastname").val();
		var address1 = $("#address1").val();
		var address2 = $("#address2").val();
		var city = $("#city").val();
		var state = $("#state").val();
		var zip = $("#zip").val();
		var phone = $("#phone").val();
		var email = $("#email").val();
		var username = $("#username").val();
		var password = $("#password").val();
		var password_confirm = $("#password_confirm").val();
		
		// error checking
		if (firstname == "") {
			$("#firstname_error").html("This field is required.");
			$("#firstname_error").show();
			$("#firstname").focus();
			return false;
		}
		
		if (lastname == "") {
			$("#lastname_error").html("This field is required.");
			$("#lastname_error").show();
			$("#lastname").focus();
			return false;
		}		

		if (address1 == "") {
			$("#address1_error").html("This field is required.");
			$("#address1_error").show();
			$("#address1").focus();
			return false;
		}
		
		if (city == "") {
			$("#city_error").html("This field is required.");
			$("#city_error").show();
			$("#city").focus();
			return false;
		}
		
		if (zip == "") {
			$("#zip_error").html("This field is required.");
			$("#zip_error").show();
			$("#zip").focus();
			return false;
		}
		
		if (phone == "") {
			$("#phone_error").html("This field is required.");
			$("#phone_error").show();
			$("#phone").focus();
			return false;
		}
		
		if (email == "") {
			$("#email_error").html("This field is required.");
			$("#email_error").show();
			$("#email").focus();
			return false;
		}
		else if (!(isValidEmailAddress(email))) {
			$("#email_error").html("This email address you entered is not formatted correctly.");
			$("#email_error").show();
			$("#email").focus();
			return false;
		}
		
		if (username == "") {
			$("#username_error").html("This field is required.");
			$("#username_error").show();
			$("#username").focus();
			return false;
		}
		else {
			$.ajax({
				type: "POST",
				url: "/ajax/register.php",
				dataType: 'json',
				async: true,
				data: 'action=checkusername&username=' + username,
				success: function(msg) {
					//alert(msg.Status);			
					if (msg.Status == "1") {
						$("#username_error").html(msg.Message);
						$("#username").val("");
						$("#username_error").show();
						$("#username").focus();
						return false;
					}
				}
			});		
		}
		
		if (password == "") {
			$("#password_error").html("This field is required.");
			$("#password_error").show();
			$("#password").focus();
			return false;
		}
		
		if (password_confirm == "") {
			$("#password_confirm_error").html("This field is required.");
			$("#password_confirm_error").show();
			$("#password_confirm").focus();
			return false;
		}
		
		if (!(password == password_confirm)) {
			$("#password_confirm_error").html("Your passwords do not match.");
			$("#password_confirm_error").show();
			$("#password_confirm").val("");
			$("#password_confirm").focus();
			return false;
		}

		// POST DATA
		var dataString = 'action=' + action + '&firstname=' + firstname + '&lastname=' + lastname + '&address1=' + address1 + '&address2=' + address2 + '&city=' + city + '&state=' + state + '&zip=' + zip + '&phone=' + phone + '&email=' + email + '&username=' + username + '&password=' + password;

		// AJAX CALL
		$.ajax({
		type: "POST",
		url: "/ajax/register.php",
		dataType: 'json',
		async: true,
		data: dataString,
		success: function(msg) {
			if (msg.Status == "1") {
				checkLoginStatus();
				
				// clear all fields
				$("#firstname").val("");
				$("#lastname").val("");
				$("#address1").val("");
				$("#address2").val("");
				$("#city").val("");
				$("#zip").val("");
				$("#phone").val("");
				$("#email").val("");
				$("#username").val("");
				$("#password").val("");
				$("#password_confirm").val("");
				
				window.location = "/index.php";
				
				return false;
			}
			else {
				alert(msg.Message);
				return false;
			}
		}
		});		
		return false;
	});
	
	/* <<== UPDATE CART ITEMS ==> */
	$("input[name^=shoppingcartqty_]").blur(function() {
		var element = this.name;
		var start = element.indexOf('_') + 1;
		var end = element.lastIndexOf('_') + 1;
		var shoppingcartid = element.substring(start, end - 1);
		var productid = element.substring(end, element.length);
		var qty = this.value;
		
		//alert(this.name + "::" + start + "::" + shoppingcartid + "::" + productid + "::" + qty);
		
		// POST DATA
		var dataString = 'action=updatecartitem&shoppingcartid=' + shoppingcartid + '&productid=' + productid + '&qty=' + qty;
		//alert(dataString);
		
		// AJAX CALL
		$.ajax({
			type: "POST",
			url: "/webservice/cart/itemqty",
			async: true,
			data: dataString,
			success: function(msg) {
				//alert(msg);
				window.location = "/basket";
			}
		});		
		return false;
	});
	
	/* <<== START CHECKOUT GOTO COUPONS ==> */
	$("#startCheckout").click(function() {
		//window.location = "/basket/billingshipping";
		window.location = "/basket/coupons";
		return false;
	});
	
	/* <<== SKIP COUPONS ==> */
	$("#skipCouponCode").click(function() {
		window.location = "/basket/billing";
		return false;
	});
	
	/* <<== VALIDATE COUPON CODE ==> */
	$("#validateCouponCode").click(function() {
		var code = $("#entercouponcode").val();
		
		//alert("CODE::" + code);
		//return false;
		
		// POST DATA
		var dataString = 'code=' + code;
		//alert(dataString);
		
		// AJAX CALL
		$.ajax({
			type: "POST",
			url: "/webservice/coupon/validate",
			async: true,
			data: dataString,
			success: function(msg) {
				//alert(msg);
				
				if(msg > 0){
					//alert("valid");	
					window.location = "/basket/billingshipping";
					return false;
				}
				else{
					//alert("not valid");
					$("#couponError").html("The coupon code you entered does not exist, please enter a valid coupon code.");
					return false;
				}
								
			}
		});		
		return false;
	});
	
	/* <<== SLIDE ACCOUNT FORM ==>> */
	$("#accountCheckbox").click(function () {
		if ($('#accountCheckbox').is(':checked')) {
			$("#formCreateAccount").show("slide", { direction: "up" }, 1000);
		}
		else {
			$("#formCreateAccount").hide("slide", { direction: "up" }, 1000);
		}			
	});
	
	
	/* <<== COPY BILLING ADDRESS TO SHIPPING ADDRESS ==> */
	$("#shippingCheckbox").click(function() {
		$('.hidden').hide();
		if ($('#shippingCheckbox').is(':checked')) {
			$("#shipping_firstname").val($("#billing_firstname").val());
			$("#shipping_lastname").val($("#billing_lastname").val());
			$("#shipping_address1").val($("#billing_address1").val());
			$("#shipping_address2").val($("#billing_address2").val());
			$("#shipping_city").val($("#billing_city").val());
			$("#shipping_state").val($("#billing_state option:selected").val());
			$("#shipping_zip").val($("#billing_zip").val());
			$("#shipping_phone").val($("#billing_phone").val());
			$("#shipping_email").val($("#billing_email").val());
		}
		else {
			$("#shipping_firstname").val("");
			$("#shipping_lastname").val("");
			$("#shipping_address1").val("");
			$("#shipping_address2").val("");
			$("#shipping_city").val("");
			$("#shipping_state").val("AL");
			$("#shipping_zip").val("");
			$("#shipping_phone").val("");
			$("#shipping_email").val("");
		}
	});
	
	/* <<== PROCESS BILLING/SHIPPING FORM ==> */
	$("#reviewOrder").click(function() {
		// assign values to form variables
		$('.hidden').hide();
		$("#errorTextjQuery").hide();
		var bfirstname = $("#billing_firstname").val();
		var blastname = $("#billing_lastname").val();
		var baddress1 = $("#billing_address1").val();
		var baddress2 = $("#billing_address2").val();
		var bcity = $("#billing_city").val();
		var bstate = $("#billing_state option:selected").val();
		var bzip = $("#billing_zip").val();
		var bphone = $("#billing_phone").val();
		var bemail = $("#billing_email").val();
		var sfirstname = $("#shipping_firstname").val();
		var slastname = $("#shipping_lastname").val();
		var saddress1 = $("#shipping_address1").val();
		var saddress2 = $("#shipping_address2").val();
		var scity = $("#shipping_city").val();
		var sstate = $("#shipping_state option:selected").val();
		var szip = $("#shipping_zip").val();
		var sphone = $("#shipping_phone").val();
		var semail = $("#shipping_email").val();
		
		// do form validation
		if (!emptyTextboxValidation("billing_firstname")) {return false};
		if (!emptyTextboxValidation("billing_lastname")) {return false};
		if (!emptyTextboxValidation("billing_address1")) {return false};
		if (!emptyTextboxValidation("billing_city")) {return false};
		if (!emptyTextboxValidation("billing_zip")) {return false};
		if (!emptyTextboxValidation("billing_phone")) {return false};
		if (!emptyTextboxValidation("billing_email")) {return false};
		
		if (!emptyTextboxValidation("shipping_firstname")) {return false};
		if (!emptyTextboxValidation("shipping_lastname")) {return false};
		if (!emptyTextboxValidation("shipping_address1")) {return false};
		if (!emptyTextboxValidation("shipping_city")) {return false};
		if (!emptyTextboxValidation("shipping_zip")) {return false};
		if (!emptyTextboxValidation("shipping_phone")) {return false};
		if (!emptyTextboxValidation("shipping_email")) {return false};
		
		// check to see if they want to create an account
		if ($('#accountCheckbox').is(':checked')) {
			if (!emptyTextboxValidation("username")) {return false};
			if (!emptyTextboxValidation("password")) {return false};
			if (!emptyTextboxValidation("password_confirm")) {return false};
			
			if (!(password == password_confirm)) {
				$("#password_confirm_error").html("Your passwords do not match.");
				$("#password_confirm_error").show();
				$("#password_confirm").val("");
				$("#password_confirm").focus();
				return false;
			}
			
			/**************************************
			 * 	ADD METHOD FOR CREATING ACCOUNT
			 **************************************/
		}
		
		// now we are ready to put everything into a session variable
		// POST DATA
		var dataString = "action=saveaddresses" +
			"&bfirstname=" + bfirstname +
			"&blastname=" + blastname +
			"&baddress1=" + baddress1 +
			"&baddress2=" + baddress2 +
			"&bcity=" + bcity +
			"&bstate=" + bstate +
			"&bzip=" + bzip +
			"&bphone=" + bphone +
			"&bemail=" + bemail +
			"&sfirstname=" + sfirstname +
			"&slastname=" + slastname +
			"&saddress1=" + saddress1 +
			"&saddress2=" + saddress2 +
			"&scity=" + scity +
			"&sstate=" + sstate +
			"&szip=" + szip +
			"&sphone=" + sphone +
			"&semail=" + semail;
			
		//alert(dataString);

		// AJAX CALL
		$.ajax({
			type: "POST",
			//dataType: 'json',
			async: true,
			url: "/webservice/cart/addresses",
			data: dataString,
			success: function(msg) {
				//alert(msg);
				window.location = "/basket/checkout";
			}
		});		
		return false;		
	});
	
	/* <<== PROCESS ORDER ==> */
	$("#ccsubmit").click(function() {
		$('.hidden').hide();
		$("#ccForm").hide();
		$("#throbber").show();		
		
		if(!(doCheckout())){
			$("#ccForm").show();
			$("#throbber").hide();
			return false;
		}
		else {
			$("#checkoutForm").submit();
			return false;
		}
		return false;
	});
	
	//if close button is clicked
	$('.window .close').click(function (e) {
		//Cancel the link behavior
		e.preventDefault();
		
		$('#mask').hide();
		$('.window').hide();
	});		
	
	//if mask is clicked
	$('#mask').click(function () {
		$(this).hide();
		$('.window').hide();
	});
	
	/* <<== ADD ITEM TO CART ==>> */		
	$("div[id^=scrollerItem_]").click(function() {
	//$("#scrollerItem").click(function() {
		//var element = this.name;
		//var start = element.indexOf('_') + 1;
		//var productid = element.substring(end, element.length);
		
		alert(this.id);
		return false;		
	});
	
	/* <<== CONTINUE SHOPPING BUTTON ==>> */		
	$("#buttonContinueShopping").click(function() {
		window.location = "/";
	});
	
/***************************************************
 *  <<== GLOBAL FUNCTIONS ==>>
 ***************************************************/
	function emptyTextboxValidation(obj) {		
		$("#" + obj).removeClass("highlight");
		if ($("#" + obj).val() == "") {
			var label = $("label[for='" + obj + "']");
			label = label.text().substring(0, label.text().length - 1);
			$("#" + obj).addClass("highlight");
			$("#" + obj).focus();
			$("#errorTextjQuery").html(label + " is required.");
			$("#errorTextjQuery").show();
			return false;
		}
		return true;
	}
	
	function refreshCartTotals() {
		var dataString = '';
		$.ajax({
			type: "POST",
			url: site + "/webservice/cart",
			dataType: 'json',
			data: dataString,
			success: function(msg) {
				//alert(msg.qty);
				var qty = 0;
				var subtotal = 0.00;
				
				if (!(msg.qty == null)){
					qty = msg.qty;
				}
				
				if (!(msg.total == null)){
					subtotal = msg.total;
				}
				
				$('#cartitemcount').html(qty);
				$('#cartsubtotal').html(subtotal);
			}
		}); 
	}
	
	function logout() {
		alert("logout");
		// POST DATA
		var dataString = 'action=logout';

		// AJAX CALL
		$.ajax({
		type: "POST",
		url: site + "/ajax/auth.php",
		data: dataString,
		success: function() {
			checkLoginStatus();
		}
		});
		return false;
	}
	
	function checkLoginStatus() {
		var dataString = 'action=checkloginstatus';
		$.ajax({
			type: "POST",
			url: site + "/ajax/auth.php",
			dataType: 'json',
			data: dataString,
			success: function(msg) {
				//alert(msg.Status);
				if ((msg == null) || (msg.Status == "0")) {
					$('#labelUserName').html("");
					$('#linkLogin').show();
					$('#linkLogout').hide();
					$('#linkLogin').html("<a href=\"/login.php\" style=\"color: #ffffff; text-decoration: none;\">[login]</a>");
				}
				else {
					$('#linkLogin').hide();
					$('#linkLogout').show();
					$('#labelUserName').html(msg.Name + " ");
				}
			}
		});
	}
	
	function isValidEmailAddress(emailAddress) {
		var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
		return pattern.test(emailAddress);
	}
	
	function isValidCreditCard(cctype, ccnum) {
		var isValid = false;
		var ccCheckRegExp = /[^\d -]/;
		isValid = !(ccCheckRegExp.test(ccnum));
		
		// we know we have all numbers, spaces or dashes so let's check just the number against card type
		if (isValid) {			
			var cardNumbersOnly = ccnum.replace(/[ -]/g,"");
		    var cardNumberLength = cardNumbersOnly.length;
		    var lengthIsValid = false;
		    var prefixIsValid = false;
		    var prefixRegExp;
		    
		    // test based on card type
		    switch(cctype) {
			    case "Mastercard":
			        lengthIsValid = (cardNumberLength == 16);
			        prefixRegExp = /^5[1-5]/;
			        break;
			    case "Visa":
			        lengthIsValid = (cardNumberLength == 16 || cardNumberLength == 13);
			        prefixRegExp = /^4/;
			        break;
			    case "American Express":
			        lengthIsValid = (cardNumberLength == 15);
			        prefixRegExp = /^3(4|7)/;
			        break;
			    case "Discover":
			        lengthIsValid = (cardNumberLength == 16);
			        prefixRegExp = /^6/;
			        break;
			    default:
			        prefixRegExp = /^$/;
			        alert("Card type not found");
		    }
		    
		    prefixIsValid = prefixRegExp.test(cardNumbersOnly);
		    isValid = prefixIsValid && lengthIsValid;
		}
		return isValid;
	}
	
	function isValidCVV2(cctype, cvv2) {
		var isValid = false;
		var ccCheckRegExp = /[^\d]/;
		isValid = !(ccCheckRegExp.test(cvv2));
		
		// let's check the number against card type
		if (isValid) {			
		    var cvv2Length = cvv2.length;
		    var lengthIsValid = false;
		    
		    // test based on card type
		    switch(cctype) {
			    case "Mastercard":
			    case "Visa":
			    case "Discover":
			        lengthIsValid = (cvv2Length == 3);
			        break;
			    case "American Express":
			        lengthIsValid = (cvv2Length == 4);
			        break;
			    default:
			        prefixRegExp = /^$/;
			        alert("CCV2 not valid.");
			        break;
		    }
		    isValid = lengthIsValid;
		}
		return isValid;
	}
	
	function parseUri(sourceUri){
	    var uriPartNames = ["source","protocol","authority","domain","port","path","directoryPath","fileName","query","anchor"];
	    var uriParts = new RegExp("^(?:([^:/?#.]+):)?(?://)?(([^:/?#]*)(?::(\\d*))?)?((/(?:[^?#](?![^?#/]*\\.[^?#/.]+(?:[\\?#]|$)))*/?)?([^?#/]*))?(?:\\?([^#]*))?(?:#(.*))?").exec(sourceUri);
	    var uri = {};
	    
	    for(var i = 0; i < 10; i++){
	        uri[uriPartNames[i]] = (uriParts[i] ? uriParts[i] : "");
	    }
	    
	    // Always end directoryPath with a trailing backslash if a path was present in the source URI
	    // Note that a trailing backslash is NOT automatically inserted within or appended to the "path" key
	    if(uri.directoryPath.length > 0){
	        uri.directoryPath = uri.directoryPath.replace(/\/?$/, "/");
	    }
	    
	    return uri;
	}
	
	function doCheckout(){
		// do form validation
		if (!emptyTextboxValidation("ccnum")) {
			$("#jserror").html("The credit card number field cannot be left blank.");
			return false;
		}
		if (!emptyTextboxValidation("cvv2")) {
			$("#jserror").html("The credit card security code field cannot be left blank.");
			return false;
		}
		
		return true;	
	}
});
