$(document).ready(function() {
	var windowWidth = parseInt($(window).width());
	var windowHeight = parseInt($(window).height());	
	
	$('[data-toggle="tooltip"]').tooltip();
	
	$.ajaxSetup({cache:false});
	
	//Make later versions of jQuery compatible with ().live
	jQuery.fn.extend({
		live: function (event, callback) {
		   if (this.selector) {
				jQuery(document).on(event, this.selector, callback);
			}
		}
	});
});

function validateEmail(email) {
	var regixExp = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
	return regixExp.test(email);
};

function modalAlert(header, content, context) {
	$('#modalPopup h4').html(header);
	$('#modalPopup .modal-body p').html(content);
	$('#modalPopup').modal('show');
};

function clearModal() {
	$('#modalPopup h4').html('Modal Header');
	$('#modalPopup p').html('Modal Message');
	$('#modalWorkArea h4').html('Modal Header');
	$('#modalWorkArea #work_area p').html('Loading...');
	//$('#confirmDelete .modal-body p').html('Loading...');
	$('#modalWorkArea .modal-dialog').removeClass('modal-lg');
	$('#modalWorkArea #savechangesbutton, #confirmDelete #confirm').unbind();
	$('.status_messages').html('');
};

function viewProduct() {
	$('.product_tiles .panel-body img').bind('click', function() {
		var thisId = $(this).parent().parent().parent().attr('id').split('_')[1];
		if (!isNaN(thisId)) {
			$.ajax({
				url: 'view_product',
				data: {
					product_id: thisId	
				},
				success: function(data) {
					$('#modalViewProduct #modal_product_area').html(data);
					var productName = $('#vp_prodname').val();
					$('#modalViewProduct #modalViewProductLabel').html(productName);
					$('#modalViewProduct').modal('show');
				}
			});
		};
	});
};

function resetCreateAccountForm(thisId) {
	$('#create_account input[type!=radio]').val('');
	$('#create_account input[type=radio]').prop('checked', '');
	$('#create_account #title1').prop('checked', 'checked');
	$('#create_account label span').html('');
	$('#label_acc_email__'+thisId+', #label_acc_password__'+thisId+', #label_acc_password_confirm__'+thisId+', #label_acc_n1__'+thisId+', #label_acc_n2__'+thisId+', #label_acc_tel__'+thisId+', #label_acc_dob__'+thisId).css({'opacity':0});
	setTimeout(function() {
		$('#create_account').modal('hide');	
	}, 400);
};

function createAccount() {
	var isComplete = 'Y';
	var email, password, title, n1, n2, phone, dob, thisId;
	$('#form_create_account input[type=radio]').each(function() {
		if ($(this).prop('checked') == true) {
			title = $(this).attr('value');
		};
	});
	$('#form_create_account input[type!=radio]').each(function() {
		thisId = $(this).attr('id').split('__');
		switch(thisId[0]) {
			case 'acc_email':
				if (validateEmail($(this).val()) == false) {
					modalAlert('Form error <i class="fa fa-times-circle-o" style="color:#ff0000;" aria-hidden="true"></i>', 'Missing or invalid email address');
					isComplete = 'N';					
				}
				else {
					email = $(this).val();	
				};
				break;
			case 'acc_password':
				if ($(this).val().length < 1 || $(this).val() !== $('#acc_password_confirm__'+thisId[1]).val()) {
					modalAlert('Form error <i class="fa fa-times-circle-o" style="color:#ff0000;" aria-hidden="true"></i>', 'Password too short or mismatched');
					isComplete = 'N';					
				}
				else {
					password = $(this).val();
				};
				break;
			case 'acc_n1':
				if ($(this).val().replace(/ /g, '') === '') {
					modalAlert('Form error <i class="fa fa-times-circle-o" style="color:#ff0000;" aria-hidden="true"></i>', 'First name required');
					isComplete = 'N';					
				}
				else {
					n1 = $(this).val();
				};
				break;
			case 'acc_n2':
				if ($(this).val().replace(/ /g, '') === '') {
					modalAlert('Form error <i class="fa fa-times-circle-o" style="color:#ff0000;" aria-hidden="true"></i>', 'Last name required');
					isComplete = 'N';					
				}
				else {
					n2 = $(this).val();
				};
				break;
			case 'acc_tel':
				if (isNaN($(this).val().replace(/ /g, '')) || $(this).val().replace(/ /g, '').length < 10) {
					modalAlert('Form error <i class="fa fa-times-circle-o" style="color:#ff0000;" aria-hidden="true"></i>', 'Missing or invalid phone number');
					isComplete = 'N';					
				}
				else {
					phone = $(this).val();
				};
				break;
			case 'acc_dob':
				if (isNaN(Date.parse($(this).val().replace(/ /g, '')))) {
					modalAlert('Form error <i class="fa fa-times-circle-o" style="color:#ff0000;" aria-hidden="true"></i>', 'Invalid date of birth');
					isComplete = 'N';					
				}
				else {
					dob = $(this).val();
				};
				break;
		};
		if ($('#label_acc_email__'+thisId[1]+'>span>span').length) {
			if (!($('#label_acc_email__'+thisId[1]+'>span>span').html().indexOf('Address available to register') > -1)) {
				modalAlert('Form error <i class="fa fa-times-circle-o" style="color:#ff0000;" aria-hidden="true"></i>', 'The email address you are attempting to register with is already taken.<br />Please register using a different address.');
				isComplete = 'N';					
			};
		};
	});
	if (email !== '' && password !== '' && title !== '' && n1 !== '' && n2 !== '' && phone !== '' && dob !== '' && isComplete === 'Y') {
		$.ajax({
			url: 'add_account/index',
			data: {
				email: email,
				password: password,
				title: title,
				n1: n1,
				n2: n2,
				phone: phone,
				dob: dob
			},
			success: function(data) {
				$('#create_account #ajax_create_account').html(data);
				if ($('#account_added').length) {
					if ($('#account_added').html() === 'success') {
						resetCreateAccountForm(thisId[1]);
						modalAlert('Account <i class="fa fa-check-circle" style="color:#009900;" aria-hidden="true"></i>', 'You have successfully registered a new account');
						$('#modalPopup').on('hidden.bs.modal', function () {
							signIn(email, password);
						});						
					};
				};
			}
		});
	};
};

function createAccountForm(context) {
	var randomString = (Math.random()*1e32).toString(36);
	$('#form_create_account').attr('autocomplete', 'off');
	$('#create_account').modal('show');
	$('#create_account .close, #create_account #cancel_create_account').bind('click', function() {
		var thisId;
		$('#create_account input[type=text], #create_account input[type=password], #create_account input[type=email]').val('');
		$('#create_account input').each(function() {
			thisId = $(this).attr('id');
			if ($(this).attr('type') !== 'radio') {
				$(this).attr('id', thisId.split('__')[0]);
				$(this).attr('name', thisId.split('__')[0]);
				$('#create_account label span').html('');
				$('#create_account label').css({'opacity':0});
				$('#create_account #label_acc_password_confirm__'+randomString).css({'opacity':0});
			};
		});
		$('#create_account .title').prop('checked', '');
		setTimeout(function() {
			$('#create_account #title1').prop('checked', 'checked');
		}, 100);
		$('#label_acc_dob__'+randomString).css({'opacity':0});
		$('#create_account input')
	});
	var inputId;
	$('#form_create_account input').each(function() {
		inputId = $(this).attr('id');
		if ($(this).attr('type') === 'text' || $(this).attr('type') === 'password' || $(this).attr('type') === 'email') {
			$(this).attr('id', inputId+'__'+randomString);
			$(this).attr('name', inputId+'__'+randomString);
			$('#form_create_account label').each(function() {
				if ($(this).attr('for') === inputId) {
					$(this).attr('for', inputId+'__'+randomString);
					$(this).attr('id', 'label_'+inputId+'__'+randomString);
				};
			});
			if ($(this).hasClass('datemaskfields') === false) {
				$(this).bind('keyup paste', function(event) {
					inputId = $(this).attr('id');
					if ($(this).val() !== '' || ($(this).val() !== '' && event.which == 8)) {
						$('#label_'+inputId).stop(true, true).animate({'opacity':1}, 200);
					}
					else {
						$('#label_'+inputId).stop(true, true).animate({'opacity':0}, 200);
					};
					if ($(this).attr('id').split('__')[0] === 'acc_password') {
						$(this).bind('keyup', function() {
							$('#acc_password_confirm__'+randomString).val('');
							$('#label_acc_password_confirm__'+randomString).stop(true, true).animate({'opacity':0}, 200);
							
							if (parseInt($(this).val().length) > 0) {
								if (parseInt($(this).val().length) <= 8) {
									$('#label_acc_password__'+randomString+' span').html('<i class="fa fa-minus-circle deny" aria-hidden="true"></i> <span class="deny"> Too short</span>');
								}
								else {
									$('#label_acc_password__'+randomString+' span').html('<i class="fa fa-check-circle accept" aria-hidden="true"></i> <span class="accept"> Length ok</span>');
								};
							}
							else {
								$('#label_acc_password__'+randomString+' span').html('');
							};
						});
					};
					if ($(this).attr('id') === 'acc_password_confirm__'+randomString) {
						$(this).bind('keyup paste', function() {
							if ($(this).val() !== $('#acc_password__'+randomString).val()) {
								$('#label_acc_password_confirm__'+randomString+' span').html('<i class="fa fa-minus-circle deny" aria-hidden="true"></i>');
							}
							else {
								$('#label_acc_password_confirm__'+randomString+' span').html('<i class="fa fa-check-circle accept" aria-hidden="true"></i> <span class="accept"> Match</span>');
							};
						});
					};
					if ($(this).attr('type') === 'email') {
						$('#label_'+inputId+'>span').html('');
						setTimeout(function() {
							$.ajax({
								url: 'email_status/index',
								data: {
									email: $('#'+inputId).val()
								},
								success: function(data) {
									$('#label_'+inputId+'>span').html(data);
								}
							});
						}, 2000);
					};
				});
			}
			else {
				$(this).focus(function() {
					inputId = $(this).attr('id');
					if ($(this).val() !== 'yyyy-mm-dd') {
						$('#label_'+inputId).stop(true, true).animate({'opacity':1}, 300);
					}
					else {
						$('#label_'+inputId).stop(true, true).animate({'opacity':0}, 300);
					};
				})
				.blur(function() {
					inputId = $(this).attr('id');
					if ($(this).val() === '' || $(this).val() === 'yyyy-mm-dd' || isNaN(Date.parse($(this).val())) ) {
						$(this).stop(true, true).val('');
						$('#label_'+inputId).stop(true, true).animate({'opacity':0}, 300);
					};
				});
			};
		};
	});
	$('#submit_create_account').bind('click', function(context) {
		createAccount(context);
	});
};

function signIn(email, password) {
	$('#modalSignIn').modal('show');
	$('#modal_ajax_sign_in').html('<i class="fa fa-cog fa-spin"></i>&nbsp;Please wait');
	var randomString = (Math.random()*1e32).toString(36);
	var inputId;
	$('#modalSignIn input').each(function() {
		$(this).val('');
		$('#modalSignIn label').css({'opacity':0});
		thisId = $(this).attr('id');
		$(this).attr('id', thisId+'__'+randomString);
		$(this).attr('name', thisId+'__'+randomString);
		$('#label_'+thisId).attr('for', thisId+'__'+randomString);
		$('#label_'+thisId).attr('id', 'label_'+thisId+'__'+randomString);
	});
	if (!(typeof email === 'undefined') && email !== '') {
		$('#label_signin_email__'+randomString).css({'opacity':1});
		$('#signin_email__'+randomString).val(email);
	};
	if (!(typeof password === 'undefined') && password !== '') {
		$('#label_signin_password__'+randomString).css({'opacity':1});
		$('#signin_password__'+randomString).val(password);
	};
	$('#modalSignIn input').bind('keyup paste', function() {
		var inputId = $(this).attr('id');
		if ($(this).val() !== '' || ($(this).val() !== '' && event.which == 8)) {
			$('#label_'+inputId).stop(true, true).animate({'opacity':1}, 200);
		}
		else {
			$('#label_'+inputId).stop(true, true).animate({'opacity':0}, 200);
		};
	});
	$('#modalSignIn #signinbutton').bind('click', function() {
		var fieldId, email, password;
		$('#modalSignIn input').each(function() {
			fieldId = $(this).attr('id').split('__');
			switch(fieldId[0]) {
				case 'signin_email':
					email = $(this).val();
					break;
				case 'signin_password':
					password = $(this).val();
			};
		});
		$('#modal_ajax_sign_in').animate({'opacity':1} ,300).html('<i class="fa fa-cog fa-spin"></i>&nbsp;Please wait');
		$.ajax({
			type: 'POST', 
			url: 'sign_in/index',
			data: {
				email: email,
				password: password
			},
			success: function(data) {
				$('#modal_ajax_sign_in').html(data);
				if ($('#modal_ajax_sign_in').html() === 'Login successful') {
					document.location.href = $('#page_name').html();
				};
			}
		});
	});
};

function signOut() {
	var cartQuantity = parseInt($('#nav_cart .badge').html());
	if (!isNaN(cartQuantity) && cartQuantity > 0) {
		$('#confirmDelete h4').html('Confirm Sign Out');
		$('#confirmDelete .modal-body p').html('PLEASE NOTE<br />Any open shopping carts that have not been through the checkout process will be deleted!<br /><i class="fa fa-shopping-cart" aria-hidden="true" style="font-size:18pt;"></i> CONTINUE?');
		$('#confirmDelete #confirm').bind('click', function() {
			document.location.href = 'sign_out';	
		}).html('Sign Out');
		$('#confirmDelete').modal('show');
	}
	else {
		document.location.href = 'sign_out';
	};
};

function totalCartCount() {
	$.ajax({
		url: 'total_cart_count',
		data: '',
		success: function(data) {
			$('#nav_cart .badge').html(data);
		}
	});	
};

var popoverContent = '<div class="popover_head"><a href="javascript:void(0);">&times;</a></div>';
popoverContent = popoverContent + '<div class="col-xs-12 col-sm-12 col-md-12 col-lg-12">';
popoverContent = popoverContent + '<span class="col-xs-5 col-sm-5 col-md-5 col-lg-5 pull-left" style="margin-left:-30px!important;"><a href="javascript:void(0);" class="btn btn-primary btn-small popover_add_to_cart"> <i class="fa fa-shopping-cart" aria-hidden="true"></i> <span class="button_labels">BUTTON-LABEL <i class="fa fa-arrow-right" aria-hidden="true"></i><span class="badge"></span></span></a></span>';
popoverContent = popoverContent + '<span class="col-xs-6 col-sm-6 col-md-6 col-lg-6 pull-right;"style="right:-70px!important;"><input type="text" class="form-control item_quantities" name="quantity_PRODUCT-ID" id="quantity_PRODUCT-ID" value="" maxlength="4" min="1" placeholder="0" /></span><div class="clearfix"></div>';
popoverContent = popoverContent + '</div>';	
	
function addToCart(productId, quantity, blockType) {
	if (!(isNaN(parseInt(quantity))) && parseInt(quantity) > 0) {
		$('#mask').fadeIn();
		$.ajax({
			type: 'POST',
			url: 'add_to_cart/index',
			data: {
				product_id: productId,
				quantity: quantity	
			},
			success: function(data) {
				$('#'+blockType+'_ajax_prod_cart_actions__'+productId).html(data);
				$('#mask').fadeOut();
				console.log(data.split('__')[0])
				if (data.split('__')[0] === 'updated' || data.split('__')[0] === 'inserted') {
					if ($('#'+blockType+'prod_'+productId+' .remove_from_cart').length === 0) {
						var removeButton = '&nbsp;&nbsp;&nbsp;<span><a href="javascript:void(0);" class="remove_from_cart btn btn-default"> <i class="fa fa-remove" aria-hidden="true"></i> Remove</a></span>';
						var thisId;
						$('.product_tiles').each(function() {
							thisId = $(this).attr('id');
							if (thisId.split('_')[1] === productId) {
								$('#'+thisId+' .cart_addupd').after(removeButton);
							};
						});
						setTimeout(function(){
							$('#lprod_'+productId+' .remove_from_cart, #tprod_'+productId+' .remove_from_cart, #sprod_'+productId+' .remove_from_cart').bind('click', function() {
								$('#confirmDelete h4').html('Remove Product');
								$('#confirmDelete .modal-body p').html('Remove this item from the shopping cart?');
								$('#confirmDelete #confirm').html('Remove');
								$('#confirmDelete').modal('show');
								$('#confirmDelete #confirm').bind('click', function() {
									$.ajax({
										url: 'delete_from_cart/index',
										data: {
											product_id: productId
										},
										success: function(data) {
											$('#'+blockType+'_ajax_prod_cart_actions__'+productId).html(data);
											if (data === 'removed') {
												clearModal();
												$('#confirmDelete').modal('hide');
												totalCartCount();
												var buttonText;
												var thisId;
												$('.product_tiles').each(function() {
													thisId = $(this).attr('id');
													if (thisId.split('_')[1] === productId) {
														$('#'+thisId+' .remove_from_cart').remove();
														$('#'+thisId+' .badge').html('');
														buttonText = $('#'+thisId+' .add_to_cart').html();
														$('#'+thisId+' .add_to_cart').html(buttonText.replace('CHANGE', 'Add to Cart'));
													};
												});
											};
										}
									});
								});
							});
						}, 200);
					};
					var thisId;
					var buttonText;
					$('.product_tiles').each(function() { 
						thisId = $(this).attr('id');
						if (thisId.split('_')[1] === productId) {
							buttonText = $('#'+thisId+' .add_to_cart').html().replace('Add to Cart', 'CHANGE');
							$('#'+thisId+' .add_to_cart').html(buttonText)
						};
					});
					$('#'+blockType+'prod_'+productId+' .add_to_cart').click();
					$.ajax({
						url: 'total_cart_count/index',
						data: {
							x: ''
						},
						success: function(data) {
							$('#nav_cart .badge').html(data);
							$('.product_tiles').each(function() {
								thisId = $(this).attr('id');
								if (thisId.split('_')[1] === productId) {
									$('#'+thisId+' .badge').html(quantity);
								};
							});
						}
					});
				};
			}
		});
	}
	else {
		modalAlert('Cart Error <i class="fa fa-times-circle-o" style="color:#ff0000;" aria-hidden="true"></i>', 'Please enter a quantity!');
		return false;
	};
};

function updateCartItem(productId, quantity, context) {
	if (!(isNaN(quantity)) && quantity > 0) {
		$.ajax({
			url: 'update_cart',
			data: {
				product_id: productId,
				quantity: quantity
			},
			success: function(data) {
				$('#ajax_prod_cart_actions__'+productId).html(data);
				if (!(isNaN(parseInt(data))) && parseInt(data) > 0) {
					$('#oq_'+productId).val(quantity);
					modalAlert('Cart Updated <i class="fa fa-check-circle" style="color:#009900;" aria-hidden="true"></i>', 'Product quantity successfully changed');
				}
				else {
					var originalQuantity = $('#oq_'+productId).val();
					$('#ct_'+productId).val(quantity);
					modalAlert('Cart Error <i class="fa fa-times-circle-o" style="color:#ff0000;" aria-hidden="true"></i>', 'Quantity not changed!');
				};
			}
		});
	}
	else {
		modalAlert('Cart error <i class="fa fa-times-circle-o" style="color:#ff0000;" aria-hidden="true"></i>', 'Please select a quantity > 0');
		var originalQuantity = $('#oq_'+productId).val();
		$('#ct_'+productId).val(originalQuantity);
	};
};

function deleteFromCart(productId, context, blockType) {
	$('#confirmDelete h4').html('Remove Product');
	$('#confirmDelete .modal-body p').html('Remove this item from the shopping cart?');
	$('#confirmDelete #confirm').html('Remove');
	$('#confirmDelete').modal('show');
	$('#confirmDelete #confirm').bind('click', function() {
		$.ajax({
			url: 'delete_from_cart/index',
			data: {
				product_id: productId
			},
			success: function(data) {
				$('#'+blockType+'_ajax_prod_cart_actions__'+productId).html(data);
				console.log(data);
				totalCartCount();
				if (data === 'removed') {
					clearModal();
					$('#confirmDelete').modal('hide');
					switch(context) {
						case 'tile':
							var buttonText;
							var thisId;
							$('.product_tiles').each(function() {
								thisId = $(this).attr('id');
								if (thisId.split('_')[1] === productId) {
									$('#'+thisId+' .remove_from_cart').remove();
									$('#'+thisId+' .badge').html('');
									buttonText = $('#'+thisId+' .add_to_cart').html();
									$('#'+thisId+' .add_to_cart').html(buttonText.replace('CHANGE', 'Add to Cart'));
								};
							});
							break;
						case 'cart':
							$('#cart_table #cart_row_'+productId).remove();
							$.ajax({
								url: 'total_cart_count',
								data: '',
								success: function(data) {
									$('#nav_cart .badge').html(data);
									if (parseInt(data) !== 1) {
										$('#cart_record_count').html(data+' items');
									}
									else {
										$('#cart_record_count').html(data+' item');
									};
									if (parseInt(data) === 0) {
										$('#cart_record_count').removeClass('counter_gtzero').addClass('counter_zero');
										$('#checkout_button').remove();
									};
								}
							});
							break;
					};
				};
			}
		});
	});
};

function deliveryAddress() {
	$('#modalWorkArea').bind('click', function() {
		$('#').alert('close');
	});
	var randomString = (Math.random()*1e32).toString(36);
	var inputId;
	$('#form_delivery_address input[type=text]').each(function() {
		$('#modalWorkArea label').css({'opacity':0});
		thisId = $(this).attr('id');
		$(this).attr('id', thisId+'__'+randomString);
		$(this).attr('name', thisId+'__'+randomString);
		$('#label_'+thisId).attr('for', thisId+'__'+randomString);
		$('#label_'+thisId).attr('id', 'label_'+thisId+'__'+randomString);
	});
	setTimeout(function() {
		var customerOrderNumber, line1, line2, line3, line4, postalCode;
		customerOrderNumber = $('#h_customer_order_number').val();
		if (customerOrderNumber !== '') {
			$('#label_customer_order_number__'+randomString).css({'opacity':1});
		};
		line1 = $('#h_addr_line1').val();
		if (line1 !== '') {
			$('#label_addr_line1__'+randomString).css({'opacity':1});
		};
		line2 = $('#h_addr_line2').val();
		if (line2 !== '') {
			$('#label_addr_line2__'+randomString).css({'opacity':1});
		};
		line3 = $('#h_addr_line3').val();
		if (line3 !== '') {
			$('#label_addr_line3__'+randomString).css({'opacity':1});
		};
		line4 = $('#h_addr_line4').val();
		if (line4 !== '') {
			$('#label_addr_line4__'+randomString).css({'opacity':1});
		};
		postalCode = $('#h_addr_postal_code').val();
		if (postalCode !== '') {
			$('#label_addr_postal_code__'+randomString).css({'opacity':1});
		};
		$('#customer_order_number__'+randomString).val(customerOrderNumber);
		$('#addr_line1__'+randomString).val(line1);
		$('#addr_line2__'+randomString).val(line2);
		$('#addr_line3__'+randomString).val(line3);
		$('#addr_line4__'+randomString).val(line4);
		$('#addr_postal_code__'+randomString).val(postalCode).mask('0000');
	}, 200);
	setTimeout(function() {
		$('#modalWorkArea input[type=text]').bind('keyup paste', function() {
			var inputId = $(this).attr('id');
			if ($(this).val() !== '' || ($(this).val() !== '' && event.which == 8)) {
				$('#label_'+inputId).stop(true, true).animate({'opacity':1}, 200);
			}
			else {
				$('#label_'+inputId).stop(true, true).animate({'opacity':0}, 200);
			};
		});
	}, 300);
};

//Checkout
function checkOutButton() {
	if ($('#create_account').length) {
		$('#checkout_button').remove();
		$('#checkout_options').show();
		$('#checkout_options #sign-in_button').bind('click', function() {
			signIn();
		});
		$('#checkout_options #sign-up_button').bind('click', function() {
			createAccountForm();
		});
	}
	else {
		$('#modalWorkArea h4').html('Delivery Address & Order Number');
		$.ajax({
			url: 'delivery_address',
			data: '',
			success: function(data) {
				$('#modalWorkArea #work_area').html(data);
				$('#modalWorkArea #modal_ajax_actions').fadeOut(0);
				deliveryAddress();
			}
		});
		var customerOrderNumber, line1, line2, line3, line4, postalCode;
		$('#modalWorkArea #savechangesbutton').html(' Next <i class="fa fa-arrow-circle-right" aria-hidden="true"></i> ');
		$('#modalWorkArea #savechangesbutton').bind('click', function() {
			function addressError() {
				if (!($('#delivery_error').length)) {
					var alertHtml = '<div id="delivery_error" class="alert alert-dismissible alert-danger"><button type="button" class="close" data-dismiss="alert">&times;</button><strong> <i class="fa fa-times-circle-o" aria-hidden="true"></i> Required fields</strong><br />Address Line 1<br />Address Line 2<br />Address Line 3<br />Postal Code<br /></div>';
					$('#form_delivery_address').after(alertHtml).fadeIn(300);
					return false;
				};
			};
			$('#modalWorkArea input[type=text]').each(function() {
				if ($(this).css('display') !== 'none') {
					switch($(this).attr('id').split('__')[0]) {
						case 'customer_order_number':
							customerOrderNumber = $(this).val();
							break;
						case 'addr_line1':
							line1 = $(this).val();
							break;
						case 'addr_line2':
							line2 = $(this).val();
							break;
						case 'addr_line3':
							line3 = $(this).val();
							break;
						case 'addr_line4':
							line4 = $(this).val();
							break;
						case 'addr_postal_code':
							postalCode = $(this).val();
							break;
					};
				};
			});	
			if (line1 !== '' && line2 !== '' && line3 !== '' && postalCode !== '') {
			$('#modalWorkArea #modal_ajax_actions').fadeIn(100);
				$.ajax({
					type: 'POST',
					url: 'delivery_address',
					data: {
						line1: line1,
						line2: line2,
						line3: line3,
						line4: line4,
						postal_code: postalCode,
						customer_order_number: customerOrderNumber
					},
					success: function(data) {
						$('#modalWorkArea #modal_ajax_actions').html(data);
						if (parseInt(data) > -1 && parseInt(data) < 2) {
							$('#modalWorkArea #savechangesbutton').unbind();
							$('#modalWorkArea').modal('hide');
							document.location.href = 'pay';
						};
					}
				});
			}
			else {
				addressError();
				return false;	
			};
		});
		$('#modalWorkArea').modal('show');
	};
};

function eftPay() {
	$.ajax({
		url: 'banking_details',
		success: function(data) {
			$('#modalWorkArea #modalWorkAreaLabel').html('Banking Details for EFT');
			$('#modalWorkArea #work_area').html(data);
			$('#modalWorkArea #popfax').mask('000 000 0000');
			$('#modalWorkArea #savechangesbutton').bind('click', function () {
				document.location.href = 'eft_order';
			});
			$('#modalWorkArea #modal_ajax_actions').hide();
			$('#modalWorkArea #savechangesbutton').html(' Confirm <i class="fa fa-arrow-circle-right" aria-hidden="true"></i>');
			$('#modalWorkArea').modal('show');
		}
	});
};

function viewSelectedInvoice(orderId) {
	if (orderId !== '') {
		$('#load_invoice').attr('src', 'view_selected_invoice?order_id='+orderId);
		rowId = 'inv_'+orderId;
		if ($('#'+rowId).hasClass('missing_invoice')) {
			modalAlert('<div style="color:#ff0000;"><i class="fa fa-times-circle" aria-hidden="true"></i> Missing File!</div>', 'No invoice found for this order.');
		};
	};
};

function navSearch() {
	//$('#nav_search').bind('click', function() {
	//});
};

function searchBox() {
	var randomString = (Math.random()*1e32).toString(36);
	var inputId;
	$('#searchform input[type=text]').each(function() {
		thisId = $(this).attr('id');
		$(this).attr('id', thisId+'__'+randomString);
		$(this).attr('name', thisId+'__'+randomString);
	});
	$('#searchform button').bind('click', function() {
		var searchValue = $('#searchvalue__'+randomString).val();
		if (searchValue.replace(/ /g, '') === '') {
			modalAlert('Search Error', 'You cannot submit an empty field');
		}
		else {
			$.ajax({
				type: 'POST',
				url: 'search_count',
				data: {
					searchvalue__: searchValue
				},
				success: function(data) {
					var resultsMessage = data+' result';
					if (parseInt(data) !== 1) {
						resultsMessage = resultsMessage+'s';
					};
					resultsMessage = resultsMessage+' found';
					$('#search_count').html(resultsMessage);
					if (parseInt(data) > 0) {
						$('#searchform').submit();
					};
				}
			});
		};
	});
};

function categorySearch(type, name) {
	$('#categorytype').val(type);
	$('#categoryname').val(name);
	$('#catsend').submit();
};

function contactForm() {
	var randomString = (Math.random()*1e32).toString(36);
	$('#form_contact').attr('autocomplete', 'off');
	var inputId;
	$('#form_contact input').each(function() {
		inputId = $(this).attr('id');
		if ($(this).attr('type') === 'text' || $(this).attr('type') === 'email') {
			$(this).attr('id', inputId+'__'+randomString);
			$(this).attr('name', inputId+'__'+randomString);
			$('#form_contact label').each(function() {
				if ($(this).attr('for') === inputId) {
					$(this).attr('for', inputId+'__'+randomString);
					$(this).attr('id', 'label_'+inputId+'__'+randomString);
				};
			});
			if ($(this).val().replace(/ /g, '') !== '') {
				$('#label_'+inputId+'__'+randomString).css({'opacity':1});
			};
			$(this).bind('keyup paste', function(event) {
				inputId = $(this).attr('id');
				if ($(this).val() !== '' || ($(this).val() !== '' && event.which == 8)) {
					$('#label_'+inputId).stop(true, true).animate({'opacity':1}, 200);
				}
				else {
					$('#label_'+inputId).stop(true, true).animate({'opacity':0}, 200);
				};
				if ($(this).attr('id').indexOf('email__') > -1) {
					$('#label_'+inputId+'>span').html('');
					setTimeout(function() {
						$.ajax({
							url: 'validate_email/index',
							data: {
								email: $('#'+inputId).val()
							},
							success: function(data) {
								$('#label_'+inputId+'>span').html(data);
							}
						});
					}, 2000);
				};
			});
		};
		if ($('#contact_message').val().replace(/ /g, '') !== '') {
			$('#label_contact_message').css({'opacity':1});
		};
		$('#form_contact #contact_message').bind('keyup paste', function(event) {
			if ($(this).val() !== '' || ($(this).val() !== '' && event.which == 8 )) {
				$('#label_contact_message').stop(true, true).animate({'opacity':1}, 200);
			}
			else {
				$('#label_contact_message').stop(true, true).animate({'opacity':0}, 200);
			};
		});
		autosize($('#form_contact #contact_message'));
	});
	$('#submit_contact').bind('click', function(context) {
		if ($('#contact_firstname__'+randomString).val().replace(/ /g, '') === '' || $('#contact_lastname__'+randomString).val().replace(/ /g, '') === '' || $('#contact_tel__'+randomString).val().replace(/ /g, '') === '' || ($('#contact_email__'+randomString).val().replace(/ /g, '') === '' || validateEmail($('#contact_email__'+randomString).val()) === false) || ($('#contact_message').val().replace(/ /g, '').replace(/\n/g, '') === '')) {
			modalAlert('Form error <i class="fa fa-times-circle-o" style="color:#ff0000;" aria-hidden="true"></i>', 'Please complete all fields!');
		}
		else {
		$('#mask').fadeIn(300);
			$.ajax({
				type: 'POST',
				url: 'contact_form',
				data: {
					firstname: $('#contact_firstname__'+randomString).val(),
					lastname: $('#contact_lastname__'+randomString).val(),
					phone: $('#contact_tel__'+randomString).val(),
					email: $('#contact_email__'+randomString).val(),
					message: $('#contact_message').val()
				},
				success: function(data) {
					$('#mask').fadeOut(300);
					$('#ajax_contact_form').html(data);
					if ($('#contact_alert strong').html() === 'Success!') {
						$('#form_contact input, #form_contact textarea').val('');
					};
					contactForm();
				}
			});
		};
	});
};

function panelHeadingHeights() {
	$('.panel-heading').each(function() {
		alert($(this).css('height'));
	});
};