//Variables 
var nav_index, product_height, product_id, product_msg, removeItem, product_id, quantityAnchor, currentQuantity, total_price, emptyBasketElement, productOption, cc_icon, cc_icon_input, addressSelect, subscribe_form, subscribe_submit, newsletter_input, productStockLevel, stock_level, checkout_form, register_form, payment_form, salon_data, ajaxWait, notify_message, notify_title = 0;
//jQuery Objects
var bodyID = $('body').prop('id');
var main_nav = $('#main_nav');
var product_nav = $('#product_nav');
var nav_content = $('#nav_content');
var question = $('.question', '#main');
var basket_control = $('#basket_control', '#main');
var notify_panel = $('#notify');
var basket_count = $('#basket_count');
var basketTable = $('#user_basket', '#main');
var gateway_checkout = '/gateway/check-out';
var express_start_form = $('#express_start_form input[type=button]');
var salon_input = $('#salon', '#nearest_salon');
var salon_results = $('#salon_results', '#nearest_salon');
var checkout_content = $('#checkout_content', '#main');
var holder_b = $('#holder_b', '#checkout_wrapper');
var review_nav = $('li a', '#review_nav');
var account_nav = $('#account_nav', '#main');
var account_content = $('#account_content', '#main');

/* Feature Detection */
//Placeholder Support
yepnope({
	test : Modernizr.input.placeholder,
	nope : ['/static/js/libs/jquery.placeholder.js']
});

//Show Notifications Panel 
function open_notify(type, title, msg, autoclose) {
    if (typeof(title) == 'undefined' || title == null) {title = '';}
    if (typeof(msg) == 'undefined' || msg == null) {msg = '';}
    if (typeof(autoclose) == 'undefined' || autoclose == null) {autoclose = true;}
    $('#msg', notify_panel).html('<strong>' + title + '</strong>' + ' ' + msg).parents('#notify').removeClass().addClass(type).filter(':not(:animated)').slideDown('slow', function() {
    		if (autoclose === true) {
    			setTimeout('$(notify_panel).slideUp("slow", function() {$(this).removeClass()})', 4000);
    		}
    });
}

//Show Notify Message
notify_title = $('body').attr('data-notify-title');
notify_message = $('body').attr('data-notify-message');
if (notify_title != '' || notify_message != '') {
	open_notify('success', notify_title, notify_message);
}

//Hide Notifications Panel
function close_notify() {
    $(notify_panel).slideUp('slow', function() {
    	$(this).removeClass();
    });
}

//Close payment modal/iframe
function closePaymentModal() {
	$('#auth_frame').trigger('reveal:close');
}

//Case Insensitive version of :contains jQuery Selector
jQuery.expr[':'].Contains = function(a, i, m) {
  return jQuery(a).text().toUpperCase()
      .indexOf(m[3].toUpperCase()) >= 0;
};

//Salon Finder
function init_salon_data(data) {
	var salon_results = $('#salon_results', '#nearest_salon');
    
	var salon_data = '';
	$.each(data, function(count, item) {
		salon_data += '<li><a href="#" data-salon-id="' + item.id + '">' + item.title + '</a></li>';
	});
	salon_results.append(salon_data);
	
	$('#salon', '#nearest_salon').change( function () {
		var inputVal = this.value;
		document.getElementById('salon_id').value = '';
	    if (inputVal.length > 2) {
	    	salon_results.show();
    		salon_results.find("a:not(:Contains(" + inputVal + "))").parent().hide();
    		salon_results.find("a:Contains(" + inputVal + ")").parent().show();
	    } else {
	    	salon_results.slideUp();
	    }
	}).keyup( function () {
	    // fire the above change event after every letter
	    $(this).change();
	    //$('#salon_results').slideDown();
	}).focus(function() {
		if (!this.value) {
			document.getElementById('salon_id').value = '';
		}
	});
	//Hide list after click
	$('a', salon_results).live('click', function() {
	    $('#salon', '#nearest_salon').val($(this).text());
	    $('#salon_results').slideUp();
	    var salon_id = $(this).attr('data-salon-id');
		document.getElementById('salon_id').value = salon_id;
	    return false;
	});
	//Remove salons list after focusout
	$('#salon', '#nearest_salon').live('focusout', function() {
	    $('#salon_results').slideUp();
	});
}

//Payment Form Validation
function validatePaymentForm() {
    $('#payment_form').validate(payment_form);
	//Discount Code Show Button
	$('#discount_code', '#discount_form').bind('focusin', function() { $(this).next('.btn').fadeIn();
	}); 
	
	//Payment Form Credit Card Type Selectors
	cc_icon = $('.cc_icon', '#cc_icons');
	cc_icon_input = $('input[type=radio]', '#cc_icons');
	/*if(cc_icon_input.prop('checked') == true) {
	    cc_icon_input.prop('checked', false);
	}*/
	cc_icon.twipsy({live: true});
	cc_icon.live({
	    click: function(){
	    	cc_icon.removeClass('selected');
	      	$(this).addClass('selected').removeClass('error').next().trigger('click');
	      	$('li[for="cc_type"]', '#formErrors').hide();
	      	/*if($('li:visible', '#formErrors').length < 1) {
	    	  	$('#formErrors').fadeOut();
	    	}*/
	    	return false;
	    },
	    mouseleave: function(){
	      	$('.twipsy').remove();
	    }
	});
}

//When the DOM is ready…
$(function() {	
	
	/* GLOBAL SCRIPTS */
	
	//Main Navigation Dropdown
	$('li > ul', main_nav).removeClass('child');
	
	$('> ul > li', main_nav).hover(
		function () {
	    	$(this).children('ul').stop(true,true).slideDown('fast');
	  	}, 
	  	function () {
	    	$(this).children('ul').stop(true,true).slideUp('fast');
	  	}
	);
	
	$('#close', notify_panel).bind('click', function() {
		close_notify();
		return false;
	});
	
	//Enable Other input field for form Title fields
	function enableOtherField(element, form) {
		$(element, form).live('change', function() {
			if ($(this).val() == 'Other') {
		    	$('#other_input', form).prop('disabled', false).removeClass('disabled');
		    } else {
		    	$('#other_input', form).prop('disabled', true).addClass('disabled');
		    }
		});
	}
	
	//Validate search form
	$('#main_search', 'header').validate({
		rules: {
				searchInput: {
					required: true,
					minlength: 3
				}
			},
			invalidHandler: function(form, validator) {
				//Show notification panel with number of errors
				var errors = validator.numberOfInvalids();
				if (errors) {
		      		var message = 'Please enter a search term with at least 3 characters.';
		        	open_notify('error','Form Error', message);
		      	}
		    }
	});
	
	//Validate newsletter form
	$('#newsletter_form').validate({
		rules: {
			email: {
		    	required: true,
		    	email: true
		    }
		},
		invalidHandler: function(form, validator) {
		    //Show notification panel with number of errors
		    var errors = validator.numberOfInvalids();
		    if (errors) {
		  		var message = 'Please enter a valid email address.';
		    	open_notify('error','Newsletter Error', message);
		  	}
		},
		submitHandler: function(form) {
			var ajaxWait = setTimeout("open_notify('','Please Wait', 'Sorry, it is taking a little longer than usual.')",8000);
			$.ajax({
				url: '/gateway/subscription-add',
				data: $(form).serializeArray(),
				dataType: 'json',
				type: 'POST',
				error: function(data) {
					open_notify('error','Newsletter Error', 'There was an error, please try again.');
				    $('input[type=submit]', '#newsletter_form').removeClass('loading').val('Sign Up');
				    clearTimeout(ajaxWait);
				},
				success: function(data) {
					if (data.success == 0) {
				    	open_notify('error','Newsletter Error', data.message);
				    	$('input[type=submit]', '#newsletter_form').removeClass('loading').val('Sign Up');
				    }
				    else if (data.success == 1){
				    	window.location = '/subscription' ;
				    }
				    else {
				    	open_notify('error','Newsletter Error', 'There was an error with the email you gave us, please try again.');
				    	$('input[type=submit]', '#newsletter_form').removeClass('loading').val('Sign Up');
				    }
				    clearTimeout(ajaxWait);
				},
  	    		complete: function() {
  	    		    clearTimeout(ajaxWait);
  	    		}
			});
		}
		    
	});
	
	//Validate Reset Password Form
	$('#password_reminder').validate({
		rules: {
			reset_email: {
		    	required: true,
		    	email: true
		    }
		},
		invalidHandler: function(form, validator) {
		    //Show notification panel with number of errors
		    var errors = validator.numberOfInvalids();
		    if (errors) {
		  		var message = 'Please enter a valid email address.';
		    	open_notify('error','Form Error', message);
		  	}
		},
		submitHandler: function(form) {
			$('#reset_submit', '#password_reminder').prop('disabled', true).addClass('loading').val('');
			var ajaxWait = setTimeout("open_notify('','Please Wait', 'Sorry, it is taking a little longer than usual.')",8000);
			$.ajax({
				url: 'gateway/user-password-reset',
				data: $(form).serializeArray(),
				dataType: 'json',
				type: 'POST',
				error: function(data) {
					open_notify('error','Form Error', 'There was an error, please try again.');
				    $('#reset_submit', '#password_reminder').removeClass('loading').val('Reset!');
				    clearTimeout(ajaxWait);
				},
				success: function(data) {
					if (data.success == 1){
						open_notify('success', data.title, data.message, false)
						$('#password_modal').trigger('reveal:close');
				    }
				    else {
				    	open_notify('error','Form Error', data.message);
				    }
				    $('#reset_submit', '#password_reminder').removeClass('loading').prop('disabled', false).val('Reset!');
				    clearTimeout(ajaxWait);
				},
  	    		complete: function() {
  	    		    clearTimeout(ajaxWait);
  	    		}
			});
		},
		errorElement: 'div'
	});
	
	/* PRODUCT PAGE */
	if (bodyID === 'product') {
		//Product Info Tabs
		$('li.nav_item > a', product_nav).bind('click', function() {
			if ($(this).attr('id') === 'reviews') {
				$('#review_nav', nav_content).stop(true,true).fadeIn('slow');
			} else {
				$('#review_nav', nav_content).stop(true,true).fadeOut('fast');
			}
			//Find index of clicked Anchor
			nav_index = $(this).parent('li').index();
			//Remove clicked Anchor's class
			$('li.nav_item > a', product_nav).removeClass('current');
			
			//Hide visible content
			$('li.nav_item', nav_content).hide();
			//Show clicked Anchor's content & add class
			$('li.nav_item', nav_content).eq(nav_index).show();
			$(this).addClass('current');
			
			return false;
		});
		//Account Tabs
		$('li > a', account_nav).bind('click', function() {
			//Find index of clicked Anchor
			nav_index = $(this).parent('li').index();
			//Remove clicked Anchor's class
			$('li > a', account_nav).removeClass('current');
			//Hide visible content
			$('li', account_content).eq(! + nav_index).fadeOut(400, function() {
				//Show clicked Anchor's content & add class
				$('li', account_content).eq(nav_index).fadeIn();
			});
			$(this).addClass('current');
			return false;
		});
		
		//Load Reviews
		review_nav.bind('click', function() {
			if (this.id === 'rv_next') {
				//Do AJAX call for more reviews
			} else {
				//Do AJAX call for less reviews
			}
		});
		
		//Add to basket
		$('#basket_add', basket_control).bind('click', function() {
			var add_button = $(this);
			$(this).prop('disabled', true).addClass('loading').prop('value', 'Please wait');
			if ($('#product_options', basket_control).length > 0) {
				product_id = $('select', basket_control).val();
			} else {
				product_id = $('#add_product_id', basket_control).val();
			}
			addToBasket('product', product_id, add_button);
			return false;
		});
		
		//Add to Basket Error
		function productAddError() {
			$('#basket_add', basket_control).prop('disabled', false).removeClass('loading').prop('value', '+ Add to basket');
		}
		
		//Add to Basket Success
		function productAddSuccess() {
			$('#basket_add', basket_control).prop('disabled', false).removeClass('loading').prop('value', '+ Add to basket');
		}
		
		//Basket Control Select Box
		$(basket_control).bind('change', function() {
			productOption = $('option:selected', this).attr('data-price');
			productWasPrice = $('option:selected', this).attr('data-was-price');
			productStockLevel = $('option:selected', this).attr('data-stock');
			$('#price', this).text(productOption);
			if(productWasPrice != 0) $('#was-price', this).text(productWasPrice);
			stockLevelUpdater(productStockLevel);
		});
		
		//Send to friend form validation
		$('#send_to_friend').validate({
			rules: {
				to_email: {
					required: true,
					email: true
				},
				from_name: 'required',
				from_email: {
					required: true,
					email: true
				},
				captcha: {
					required: true,
				    rangelength: [6, 6]
				}
			},
			submitHandler: function(form) {
			    	$('input[type=submit]', '#send_to_friend').addClass('loading').val('');
			    	var ajaxWait = setTimeout("open_notify('','Please Wait', 'Sorry, it is taking a little longer than usual.')",8000);
			    	$.ajax({
						url: '/gateway/email-a-friend/',
						data: $(form).serializeArray(),
						dataType: 'json',
						type: 'POST',
						error: function(data) {
							open_notify('error','Form Error', 'There was an error, please try again.');
							$('input[type=submit]', '#send_to_friend').removeClass('loading').val('Continue');
							clearTimeout(ajaxWait);
						},
						success: function(data) {
							if (data.success == 0) {
								open_notify('error','Form Error', data.message);
								$('input[type=submit]', '#send_to_friend').removeClass('loading').val('Continue');
							}
							else if (data.success == 1){
								open_notify('success','Email Sent', 'Details about this product have been sent.');
								$('#email_modal').trigger('reveal:close');
								$('input[type=submit]', '#send_to_friend').removeClass('loading').val('Continue');
								$("#captcha").attr("src", "/assets/captcha-image");
								form.from_email.value = '';
								form.from_name.value = '';
								form.to_email.value = '';
								form.captcha.value = '';
							}
							
							else {
								open_notify('error','Form Error', data.message);
								$('input[type=submit]', '#send_to_friend').removeClass('loading').val('Continue');
								$("#captcha").attr("src", "/assets/captcha-image");
							}
							clearTimeout(ajaxWait);
						}
					});
					return false;
			    },
			    /*DH*/
				errorElement: 'div',
  	    		complete: function() {
  	    		    clearTimeout(ajaxWait);
  	    		}
			});
		

		$('#captchaRefresh').bind('click', function() {
			d = new Date();
			$("#captcha").attr("src", "/assets/captcha-image?"+d.getTime());
			return false;
		});
		
		//Stock Level Checker
		function stockLevelUpdater(stockLevel) {
			stock_level = $('#stock_level', '#col_b');
			if (stockLevel == 1) {
				$(stock_level).removeClass('noStock').addClass('stock').text('In stock - Delivery within 2 working days');
				$('#basket_add', basket_control).removeClass('disabled').removeProp('disabled', true).val('+ Add to basket');
			} else {
				$(stock_level).addClass('noStock').text('Sorry, product is not in stock at the moment.');
				$('#basket_add', basket_control).addClass('disabled').prop('disabled', true).val('Out of Stock');
			}
		}
		if ($('option:selected', basket_control).length > 0) {
			productStockLevel = $('option:selected', basket_control).attr('data-stock');
		}
		
		if ($('#add_product_id', basket_control).length > 0) {
			productStockLevel = $('#add_product_id', basket_control).attr('data-stock');
		}
		stockLevelUpdater(productStockLevel);
	}
	
	function addToBasket(section, product_id, element) {
		var ajaxWait = setTimeout("open_notify('','Please Wait', 'Sorry, it is taking a little longer than usual.')",8000);
		$.ajax({
			url: '/gateway/basket-add/' + product_id + '/true',
		    dataType: "json",
		    error: function() {
		    	open_notify('error', 'We were unable to add your item to the basket on this occasion, please try again.');
		    	if (section === 'product') {
		    		productAddError();
		    	} else {
		    		element.removeClass('loading');
		    	}
		    	clearTimeout(ajaxWait);
		    },
		    success: function(data) {
		    	if (data.success === 1) {
		    		if (section === 'product') {
		    			open_notify('success', data.title, data.message);
		    			productAddSuccess();
		    		} else {
		    			updateQuantity(element, data.item_quantity);
		    			updateTotal(data.basket_total);
		    			updateSubTotal(element, data.item_rrp_inc_vat_subtotal);
		    			element.removeClass('loading');
		    		}
		    		updateBasket(data.basket_count);
		    	} else {
  		       		open_notify('error',data.title,  data.message);
		    		if (section === 'product') {
		    			productAddError();
		    		} else {
		    			element.removeClass('loading');
		    		}
  		       	}
  		       	clearTimeout(ajaxWait);
  		    },
  	    	complete: function() {
  	    	    clearTimeout(ajaxWait);
  	    	}
		});
	}
	
	function removeFromBasket(section, product_id, element) {
		var ajaxWait = setTimeout("open_notify('','Please Wait', 'Sorry, it is taking a little longer than usual.')",8000);
		$.ajax({
			url: '/gateway/basket-remove/' + product_id + '/true',
	    	dataType: "json",
	    	error: function() {
	    		open_notify('error', '', 'We were unable to remove your item from the basket on this occasion, please try again.');
	    		element.removeClass('loading');
	    		clearTimeout(ajaxWait);
	    	},
	    	success: function(data) {
	    		if (data.success === 1) {
	    			if (section === 'remove') {
	    				basketRemoveSuccess(element);
	    			} else {
	    				updateQuantity(element, data.item_quantity);
	    			}
	    			updateBasket(data.basket_count);
	    			updateTotal(data.basket_total);
	    			updateSubTotal(element, data.item_rrp_inc_vat_subtotal);
	    			element.removeClass('loading');
	    		} else {
  	           		open_notify('error',data.title, data.message);
  	           		element.removeClass('loading');
  	           	}
  	           	clearTimeout(ajaxWait);
  	        },
  	    	complete: function() {
  	    	    clearTimeout(ajaxWait);
  	    	}
	    });
	}
	
	/* BASKET CONTROLS */
	//Update Basket
	function updateBasket(amount) {
		$('.amount', basket_count).text(parseInt(amount));
	}
		
	if (bodyID === 'basket') {
		
		//Empty Basket
		function emptyBasket(element) {
			var ajaxWait = setTimeout("open_notify('','Please Wait', 'Sorry, it is taking a little longer than usual.')",8000);
			$.ajax({
				url: '/gateway/basket-empty',
				dataType: "json",
				error: function() {
					open_notify('error','Basket Error', "We were unable to empty the basket on this occasion, please try again");
					clearTimeout(ajaxWait);	
				},
				success: function(data) {
					if (data.success === 1) {
				    	element.removeClass('disabled');
				    	window.location.reload();
				    } else {
  				   		open_notify('error',data.title, data.message);
  				   		element.removeClass('disabled');
  				   	}
  				   	clearTimeout(ajaxWait);
  				},
  	    		complete: function() {
  	    		    clearTimeout(ajaxWait);
  	    		}
			});
		}
		
		function reloadBasket() {
			$('tbody tr', basketTable).not('.row_title').fadeOut(function() {
					$(this).remove();
					$('tr.basketDefault', basketTable).fadeIn();
				});
			updateBasket(0);
			updateTotal(0);
		}
		
		$('#basket_empty').bind('click', function() {
			emptyBasketElement = $(this);
			$(this).addClass('disabled');
			var confirm_empty = confirm("Are you sure you want to empty the basket?");
			if (confirm_empty === true) {
				emptyBasket(emptyBasketElement);
			} else {
				$(this).removeClass('disabled');
			}
			return false;
		});
		
		//Update Quantity	
		$('td.quantity a', basketTable).live('click', function() {
			currentQuantity = $(this).parentsUntil('quantity').children('span').text();
			quantityAnchor = $(this);
			product_id = $(this).parents('tr').attr('data-product-id');
			if ($(this).hasClass('more')) {
				//Update server via AJAX
				addToBasket('basket', product_id, quantityAnchor);
				quantityAnchor.addClass('loading');
			} else {
				//If the quantity is more than 1 update the server via AJAX
				if (currentQuantity > 1) {
					removeFromBasket('quantity', product_id, quantityAnchor);
					quantityAnchor.addClass('loading');
				}
			}
			return false;
		});
		
		//Add to Basket Success
		function updateQuantity(element, item_quantity) {
			element.parentsUntil('quantity').children('span').text(item_quantity);
		}
		
		//Remove From Basket Success
		function basketRemoveSuccess(element) {
			element.parents('tr').fadeOut('slow', function(){
				$(this).remove();
			});
		}
		
		//Remove Item from table on basket page
		$('.removeItem', basketTable).live('click', function() {
			removeItem = $(this);
			product_id = removeItem.parents('tr').attr('data-product-id');
			removeItem.addClass('loading');
			var ajaxWait = setTimeout("open_notify('','Please Wait', 'Sorry, it is taking a little longer than usual.')",8000);
			$.ajax({
				url: '/gateway/basket-remove-all/' + product_id +'/true',
	    		dataType: "json",
	    		error: function() {
	    			open_notify('error', 'We were unable to remove your item to the basket on this occasion, please try again.');
	    			removeItem.removeClass('loading');
	    			clearTimeout(ajaxWait);
	    		},
	    		success: function(data) {
	    			if (data.success === 1) {
	    				if (data.basket_count != 0) {
	    					basketRemoveSuccess(removeItem);
	    					updateBasket(data.basket_count);
	    					updateTotal(data.basket_total);
	    				} else {
	    					window.location.reload();
	    				}
	    				
	    			} else {
  	    	       		open_notify('error',data.title, data.message);
  	    	       		removeItem.removeClass('loading');
  	    	       	}
  	    	       	clearTimeout(ajaxWait);
  	    	    },
  	    		complete: function() {
  	    		    clearTimeout(ajaxWait);
  	    		}
	    	});
			//Swap delete icon for loading gif whilst waiting for AJAX
			return false;
		});
		
		function updateTotal(amount) {
			$('#total_price span', basketTable).text(amount);
		}
		
		function updateSubTotal(element, amount) {
			element.parents('tr').children('.subTotal').children('span').text(amount);
		}
	}
	
	/* FAQ PAGE */
	if (bodyID == 'information') {
		$('a', question).bind('click', function() {
			$(this).toggleClass('active');
			$(this).parents('.question').children('p').toggle('fast');
		});
	}
	
	/* CHECKOUT PAGES */
	if (bodyID == 'check-out') {
	
		//Validation for Login form
		register_form = {
			rules: {
				email: {
					required: true,
					email: true
				},
				password: 'required'
			},
			invalidHandler: function(form, validator) {
				//Show notification panel with number of errors
				var errors = validator.numberOfInvalids();
				if (errors) {
		      		var message = errors == 1
						? 'You missed 1 field. Please correct the error and try again.'
						: 'You missed ' + errors + ' fields. Please correct the errors and try again.';
		        	open_notify('error','Form Error', message);
		      	}
		    },
		    submitHandler:  function(form) {
		    	var register_form_this = this;
		    	$(register_form_this.submitButton).addClass('loading').val('');
		    	var ajaxWait = setTimeout("open_notify('','Please Wait', 'Sorry, it is taking a little longer than usual.')",8000);
		    	$.ajax({
		    		url: gateway_checkout,
					cache: false,
					dataType: 'json',
					data: $(form).serializeArray(),
					type: 'POST',
					error: function(data) { 
						open_notify('error','Login Error', data.message);
						$(register_form_this.submitButton).removeClass('loading').val('Log In & Check Out');
						clearTimeout(ajaxWait);
					},
					success: function(data) {
						updateBasket(data.basket_total);
						if (data.success == 1) {
							$('#holder_b', '#checkout_wrapper').html(data.content);
						    $('#checkout_form').validate(checkout_form);
						    // --- STEP 2 --- 
							if (data.checkout_step == 0) {
							    //Delivery Address Selection
							    addressSelector();
							    document.getElementById('control_nav').children[0].innerHTML = '<a href="/log-out">Log Out</a>';
							    document.getElementById('control_nav').children[1].innerHTML = '<a href="/my-account">My Account</a>';
							}
							
							// --- PAYMENT --- 
							if (data.checkout_step == 2) {
							    validatePaymentForm();
							}
						    checkoutAnimate('fade');
						} else {
						    $(register_form_this.submitButton).removeClass('loading').val('Log In & Check Out');
						    open_notify('error','Login Error', data.message);
						}
						clearTimeout(ajaxWait);
					},
  	    		    complete: function() {
  	    		    	clearTimeout(ajaxWait);
  	    		    }
		    	});
		    },
			errorElement: 'div'
		}
		
		//Checkout Animation
		function checkoutAnimate(effect) {
			var holder_a = $('#holder_a', '#checkout_wrapper');
			var holder_b = $('#holder_b', '#checkout_wrapper');
			var checkout_wrapper = $('#checkout_wrapper', '#checkout_content');
			var checkout_height = holder_a.height();
			
			checkout_wrapper.css('height', checkout_height);
			
			if (Modernizr.cssanimations) {
				cssAnimate(effect);
			} else {
				jQueryfallback(effect)
			}
			
			function cssAnimate(effect) {
				holder_a.addClass('animated');
				if (effect == 'fade') {
			        holder_a.addClass('fadeOut hide');
			        checkout_height = holder_b.height();
			        holder_a.remove();
			        checkout_wrapper.animate({
						height: checkout_height
			        },200, function() {
						holder_b.addClass('animated fadeIn').attr('id', 'holder_a').parent().height('auto').append('<div id="holder_b"></div>');
					});
			    } else {
			    	holder_a.addClass('fadeOutLeftBig');
			        checkout_height = holder_b.height();
			        checkout_wrapper.animate({
						height: checkout_height
			        },200, function() {
			        	holder_a.remove();
						holder_b.addClass('animated fadeInRightBig').attr('id', 'holder_a').parent().height('auto').append('<div id="holder_b"></div>');
					});
			    }
			}	
				
			function jQueryfallback(effect) {
				if (effect == 'fade') {
			        holder_a.fadeOut(400, function() {
			            checkout_height = holder_b.height();
			            holder_a.remove();
			            checkout_wrapper.animate({
			                height: checkout_height
			            },200, function() {
			                holder_b.fadeIn(800).attr('id', 'holder_a').parent().height('auto').append('<div id="holder_b"></div>');
			            });
			        });
			    } else {
			        holder_a.animate({
			            left: '-=110%',
			            opacity: 0.1
			        }, 400, function() {
			            checkout_height = holder_b.height();
			            holder_a.remove();
			            checkout_wrapper.animate({
			                height: checkout_height
			            },200, function() {
			                holder_b.animate({
			                    left: '-=110%',
			                    opacity: 1
			                }, 800).attr('id', 'holder_a').parent().height('auto').append('<div id="holder_b"></div>');
			            });
			        });
			    }
			}	
		}
	
		/* --- CHOICE PAGE FORM --- */
		express_start_form.live('click', function() {
			express_start_form = $(this);
			express_start_form.addClass('loading').val('');
			var ajaxWait = setTimeout("open_notify('','Please Wait', 'Sorry, it is taking a little longer than usual.')",8000);
			$.ajax({
				url: gateway_checkout,
				cache: false,
				dataType: 'json',
				data: {checkout_type:'express'},
				type: 'POST',
				error: function(data) { 
					open_notify('error','Checkout Error', data.message);
					express_start_form.removeClass('loading').val('Start Here');
					clearTimeout(ajaxWait);
				},
				success: function(data) {
					updateBasket(data.basket_total);
					if (data.success == 1) {
						$('#holder_b', '#checkout_wrapper').html(data.content);
					    $('#checkout_form').validate(checkout_form);
					    //Show other title field if selected
					    enableOtherField('#title_input','#checkout_form');
					    //Salon Finder
					    $.ajax({
					    	url: '/gateway/user-salon-list',
					    	dataType: 'json',
					    	success: function(data){
					    		init_salon_data(data);
					    	}
					    });
					    checkoutAnimate('slide');
					} else {
					    express_start_form.removeClass('loading').val('Start Here');
					    open_notify('error','Checkout Error', data.message);
					    $('#holder_a', '#checkout_wrapper').html(data.content);
					}
					clearTimeout(ajaxWait);
				},
  	    		complete: function() {
  	    		    clearTimeout(ajaxWait);
  	    		}
			});
		});
		
		/* --- CHOICE PAGE LOAD CONTENT --- */
		var ajaxWait = setTimeout("open_notify('','Please Wait', 'Sorry, it is taking a little longer than usual.')",8000);
		$.ajax({
			url: gateway_checkout,
			dataType: 'json',
			error: function(data) {
				$('#checkout_loading', '#main').fadeOut(2000, function() {
			    	$('#checkout_error', '#main').fadeIn();
			    	open_notify('error','Checkout Error', data.message);
				});
				clearTimeout(ajaxWait);
			},
			success: function(data) {
				updateBasket(data.basket_total);
				$('#holder_b', '#checkout_wrapper').html(data.content);
				checkoutAnimate('fade');
				$('#checkout_form').validate(checkout_form);
				$('#register_form').validate(register_form);
				// --- EXPRESS STEP 1 --- 
				if (data.checkout_type == 'express' && data.checkout_step == 0) {
					//Salon Finder
					$.ajax({
					    url: '/gateway/user-salon-list',
					    dataType: 'json',
					    success: function(data){
					    	init_salon_data(data);
					    }
					});
				}
				// --- EXPRESS STEP 2 --- 
				if (data.checkout_type == 'express' && data.checkout_step == 1) {
				    //Delivery Address Selection
				    addressSelector();
				}
				// --- EXPRESS STEP 4 ---
				if (data.checkout_type == 'express' && data.checkout_step == 3) {
				    validatePaymentForm();
				}
				
				// --- REGISTERED STEP 1 --- 
				if (data.checkout_type == 'registered' && data.checkout_step == 0) {
				    //Delivery Address Selection
				    addressSelector();
				}
				
				// --- REGISTERED STEP - PAYMENT --- 
				if (data.checkout_type == 'registered' && data.checkout_step == 2) {
				    validatePaymentForm();
				}
				clearTimeout(ajaxWait);
			},
  	    	complete: function() {
  	    	    clearTimeout(ajaxWait);
  	    	}
		});
		
		/* --- VALIDATION RULES FOR CHECKOUT FORMS --- */
		checkout_form = {
			invalidHandler: function(form, validator) {
				//Show notification panel with number of errors
				var errors = validator.numberOfInvalids();
				if (errors) {
		      		var message = errors == 1
						? 'You missed 1 field. Please correct the error and try again.'
						: 'You missed ' + errors + ' fields. Please correct the errors and try again.';
		        	open_notify('error','Form Error', message);
		      	}
		    },
		    submitHandler: function(form) {
		    	$('input[type=submit]', '#checkout_form').addClass('loading').val('');
		    	var ajaxWait = setTimeout("open_notify('','Please Wait', 'Sorry, it is taking a little longer than usual.')",8000);
		    	$.ajax({
					url: gateway_checkout,
					data: $(form).serializeArray(),
					dataType: 'json',
					type: 'POST',
					error: function(data) { 
						$('input[type=submit]', '#checkout_form').removeClass('loading').val('Continue');
						open_notify('error','Checkout Error', data.message);
						$('#holder_a', '#checkout_wrapper').html(data.content);
						clearTimeout(ajaxWait);
					},
					success: function(data) {
						updateBasket(data.basket_total);
						if (data.success == 1) {
							$('#holder_b', '#checkout_wrapper').html(data.content);
							checkoutAnimate('slide');
							// --- STEP 2 --- 
							if (data.checkout_type == 'express' && data.checkout_step == 1) {
								//Delivery Address Selection
								addressSelector();
							}
							
							// --- STEP 4 ---
							if (data.checkout_type == 'express' && data.checkout_step == 3) {
								validatePaymentForm();
							}
							
							// --- REGISTERED STEP 1 --- 
							if (data.checkout_type == 'registered' && data.checkout_step == 0) {
							    //Delivery Address Selection
							    addressSelector();
							}
							
							// --- REGISTERED STEP - PAYMENT --- 
							if (data.checkout_type == 'registered' && data.checkout_step == 2) {
							    validatePaymentForm();
							}
							
							// EVENT DELEGATION FOR FORM SUBMIT
							$('body').delegate('#checkout_submit','click', function() {
								$('#checkout_form').validate(checkout_form);
							});
						} else {
							open_notify('error','Checkout Error', data.message);
							$('input[type=submit]', '#checkout_form').removeClass('loading').val('Continue');
							//Turned this off as dont need to reload content
							//$('#holder_a', '#checkout_wrapper').html(data.content);
						}
						clearTimeout(ajaxWait);
					},
  	    		    complete: function() {
  	    		    	clearTimeout(ajaxWait);
  	    		    }
				});
				return false;
		    },
			errorElement: 'div'
			//,debug: true
		};
		
		function addressSelector() {
			addressSelect = $('.addressSelect', '#address_table');
			addressSelect.live('click', function() {
			    if ($(this).prop('value') == 'other') {
			    	addressSelect.parent().next().children('.other').fadeOut('fast', function() {
			    		addressSelect.parent().next().children('#other_address').slideDown();
			    	});
			    } else {
			    	addressSelect.parent().next().children('#other_address').slideUp(function() {
			    		addressSelect.parent().next().children('.other').fadeIn('fast');
			    	});
			    }
			});
		}
				
		/* --- PAYMENT FORM VALIDATIONS --- */
		
		//Handle page reload/refreshes on final step of checkout
		$(window).load(function() {
 			validatePaymentForm();
		});
		
		payment_form = {
			rules: {
				cc_name: 'required',
				cc_number: {
					required: true,
					creditcard: true,
					digits: true
				},
				cc_type: {
					required: true
				},
				cc_end_month: {
					required: true
				},
				cc_end_year: {
					required: true
				},
				cc_cvv: {
					required: true,
					minlength: 3,
					digits: true
				}
			},
			
			messages: {
				cc_name: '<strong>Cardholder Name:</strong> Please enter the name as it appears on the card.',
				cc_number: '<strong>Card Number:</strong> Please enter a valid credit card number.',
				cc_type: '<strong>Card Type:</strong> Please select a card type.',
				cc_start_month: '<strong>Start Month:</strong> Please enter the valid from month.',
				cc_start_year: '<strong>Start Year:</strong> Please enter the valid from year.',
				cc_end_month: '<strong>End Month:</strong> Please enter the valid till month.',
				cc_end_year: '<strong>End Year:</strong> Please enter the valid till year.',
				cc_cvv: '<strong>CVV:</strong> Please enter the CVV number.'
			},
			
			invalidHandler: function(form, validator) {
				//Show notification panel with number of errors
				var errors = validator.numberOfInvalids();
				if (errors) {
					//Add .error class to alert box
					$('.alert-message', '#main').addClass('error');
		      		var message = errors == 1
						? 'You missed 1 field. Please correct the error and try again.'
						: 'You missed ' + errors + ' fields. Please correct the errors and try again.';
		        	open_notify('error','Form Error', message);
		      	}
		    },
		    
		    submitHandler: function(form){
		    	close_notify();
		    	$('#payment_submit').attr('disabled','disabled');
		    	$('#payment_loading', checkout_content).fadeIn();
		    	var ajaxWait = setTimeout("open_notify('','Please Wait', 'Sorry, it is taking a little longer than usual.')",8000);
		    	
		    	/*DH*/
		    	$.ajax({
					url: gateway_checkout,
					data: $(form).serializeArray(),
					dataType: 'json',
					type: 'POST',
					error: function(data) {
						$('#payment_loading', checkout_content).fadeOut('fast', function() {
							open_notify('error','Checkout Error', data.message, false);
						});
						clearTimeout(ajaxWait);
					},
					success: function(data) {
						if (data.success === 1) {
							//If the card needs 3DAUTH
							if(data.message == '3DAUTH') {
								var auth_form = $('#auth_form').attr({
									action: data.ACSURL,
									method: 'POST'
								});
								
								$('<input>').attr({type:'hidden',id:"MD",name:"MD",value:data.MD}).appendTo(auth_form); 
								$('<input>').attr({type:'hidden',id:"PaReq",name:"PaReq",value:data.PAReq}).appendTo(auth_form); 
								$('<input>').attr({type:'hidden',id:"TermUrl",name:"TermUrl",value:data.TermURL}).appendTo(auth_form);
								
								//Submit 3DAUTH form through iframe
								auth_form.submit();
								
								//Remove error class from validation info box
								$('.alert-message', '#main').removeClass('error');
								
								//Prevent user from closing modal
								$('#auth_frame').reveal({
									closeonbackgroundclick: false
								});
							};
							//If the card is authorised
							if(data.message == 'OK') {
								$('#payment_loading', checkout_content).fadeOut('slow', function() {
										checkout_content.html(data.content);
								});
							}
						} else {
							//If there is an error (success = 0), e.g if the user navigates away from the page in another window or adds something else to basket
							$('#payment_loading', checkout_content).fadeOut('fast', function() {
								open_notify('error','Checkout Error', data.message, false);
							});
						}
						clearTimeout(ajaxWait);
					},
  	    		    complete: function() {
  	    		    	clearTimeout(ajaxWait);
  	    		    }
		    	})
		    	/*DH*/
		    },
		    errorElement: 'li',
		    errorContainer: '#formErrors',
		    errorLabelContainer: "#formErrors ul"
		}
	}
		
	/* SUBSCRIPTION PAGE */
	if (bodyID == 'subscription') {
			
		//Validate Subscribe Form
		subscribe_form = $('#subscribe_form');
		subscribe_submit = $('#submit', subscribe_form);
		subscribe_form.validate({
			rules: {
				email: {
					required: true,
					email: true
				},
				title: 'required',
				first_name: 'required',
				last_name: 'required'
			},
			invalidHandler: function(form, validator) {
				//Show notification panel with number of errors
				var errors = validator.numberOfInvalids();
				if (errors) {
		      		var message = errors == 1
						? 'You missed 1 field. Please correct the error and try again.'
						: 'You missed ' + errors + ' fields. Please correct the errors and try again.';
		        	open_notify('error','Form Error', message);
		      	}
		      	clearTimeout(ajaxWait);
		    },
		    submitHandler: function(form) {
		    	subscribe_submit.prop('disabled', true).addClass('loading disabled').attr('value', 'Loading');
		    	var ajaxWait = setTimeout("open_notify('','Please Wait', 'Sorry, it is taking a little longer than usual.')",8000);
			   	$.ajax({
					url: '/gateway/subscription-add-detail',
					data: $(form).serializeArray(),
	    			dataType: "json",
	    			type: 'POST',
	    			error: function() {
	    				open_notify('error', "Sorry there appears to have been an error. Please try again.");
	    				subscribe_submit.removeProp('disabled').attr('Value', 'Update').removeClass('loading disabled');
	    			},
	    			success: function(data) {
	    				if (data.success === 1) {
	    					subscribe_form.fadeOut('slow', function() {
	    						$('#thank_you').fadeIn();
	    					});
	    				} else {
  	    		       		open_notify('error','Error', data.message);
							subscribe_submit.removeProp('disabled').attr('Value', 'Update').removeClass('loading disabled');
  	    		       	}
  	    		       	clearTimeout(ajaxWait);
  	    		    }
				});
				return false;
			},
			errorElement: 'div',
  	    	complete: function() {
  	    	    clearTimeout(ajaxWait);
  	    	}
		});
	}
	
	/* LOGIN PAGE */
	if (bodyID == 'log-in') {
		//Validate Login Form
		$('#login_form').validate({
			rules: {
				email: {
					required: true,
					email: true
				},
				password: 'required'
			},
			invalidHandler: function(form, validator) {
				//Show notification panel with number of errors
				var errors = validator.numberOfInvalids();
				if (errors) {
		      		var message = errors == 1
						? 'You missed 1 field. Please correct the error and try again.'
						: 'You missed ' + errors + ' fields. Please correct the errors and try again.';
		        	open_notify('error','Form Error', message);
		      	}
		    },
		    errorElement: 'div',
		    submitHandler: function(form) {
		    	$('#user_login').prop('disabled', true).addClass('loading disabled').attr('value', '');
		    	var ajaxWait = setTimeout("open_notify('','Please Wait', 'Sorry, it is taking a little longer than usual.')",8000);
			   	$.ajax({
					url: '/gateway/user-log-in',
	    			data: $(form).serializeArray(),
					dataType: 'json',
					type: 'POST',
	    			error: function() {
	    				open_notify('error', "Sorry there appears to have been an error. Please try again.");
	    				$('#user_login', '#login_form').removeProp('disabled').attr('Value', 'Log In').removeClass('loading disabled');
	    				clearTimeout(ajaxWait);
	    			},
	    			success: function(data) {
	    				if (data.success === 1) {
	    					window.document.location = '/';
	    				} else {
  	    		       		open_notify('error',data.title, data.message);
							$('#user_login', '#login_form').removeProp('disabled').attr('Value', 'Log In').removeClass('loading disabled');
  	    		       	}
  	    		       	clearTimeout(ajaxWait);
  	    		    },
  	    		    complete: function() {
  	    		    	clearTimeout(ajaxWait);
  	    		    }
				});
				return false;
			}
			//,debug: true
		});
	}
	
	/* REGISTER PAGE */
	if (bodyID == 'register') {
		
		//Show & Hide other address fields
		$('#show_other_address', '#delivery_address').bind('click', function() {
			$(this).parents('#delivery_address').children('#other_address').slideToggle();
		});
		
		//Validate Form
		$('#register_form').validate({
			errorElement: 'div',
			rules: {
				user_password: "required",
				confirm_user_password: {
					equalTo: "#user_password"
				}
			},
			invalidHandler: function(form, validator) {
				//Show notification panel with number of errors
				var errors = validator.numberOfInvalids();
				if (errors) {
		      		var message = errors == 1
						? 'You missed 1 field. Please correct the error and try again.'
						: 'You missed ' + errors + ' fields. Please correct the errors and try again.';
		        	open_notify('error','Form Error', message);
		      	}
		    },
		    submitHandler: function(form) {
		    	$('#user_register').prop('disabled', true).addClass('loading disabled').attr('value', '');
		    	var ajaxWait = setTimeout("open_notify('','Please Wait', 'Sorry, it is taking a little longer than usual.')",8000);
			   	$.ajax({
					url: '/gateway/user-register',
	    			data: $(form).serializeArray(),
					dataType: 'json',
					type: 'POST',
	    			error: function() {
	    				open_notify('error', "Sorry there appears to have been an error. Please try again.");
	    				$('#user_register').removeProp('disabled').attr('Value', 'Register').removeClass('loading disabled');
	    				clearTimeout(ajaxWait);
	    			},
	    			success: function(data) {
	    				if (data.success === 1) {
	    					window.document.location = '/my-account';
	    				} else {
  	    		       		open_notify('error',data.title, data.message);
							$('#user_register').removeProp('disabled').attr('Value', 'Register').removeClass('loading disabled');
  	    		       	}
  	    		       	clearTimeout(ajaxWait);
  	    		    },
  	    		    complete: function() {
  	    		    	clearTimeout(ajaxWait);
  	    		    }
				});
				return false;
			}
		});
		
		//Enable other field
		enableOtherField('#title_input', '#register_form');
		
		//Nearest Salon Field
		$.ajax({
		    url: '/gateway/user-salon-list',
		    dataType: 'json',
		    success: function(data){
		    	init_salon_data(data);
		    }
		});
	}
	
	/* RESET PASSWORD PAGE */
	if (bodyID == 'reset-password') {	
		$('#reset_password_form', '#main').validate({
			errorElement: 'div',
			rules: {
				password: "required",
				confirm_password: {
					equalTo: "#password"
				}
			},
			submitHandler: function(form) {
				var ajaxWait = setTimeout("open_notify('','Please Wait', 'Sorry, it is taking a little longer than usual.')",8000);
				$.ajax({
					url: '/gateway/user-password-update',
					data: $(form).serializeArray(),
					dataType: 'json',
					type: 'POST',
					error: function() {
	    				open_notify('error', "Sorry there appears to have been an error. Please try again.");
	    				$('#reset_submit', '#reset_password_form').removeProp('disabled').attr('Value', 'Reset').removeClass('loading disabled');
	    				clearTimeout(ajaxWait);
	    			},
	    			success: function(data) {
	    				if (data.success === 1) {
	    					window.location = '/' ;
	    				} else {
  	    		       		open_notify('error',data.title, data.message);
  	    		       	}
  	    		       	$('#reset_submit', '#reset_password_form').removeProp('disabled').attr('Value', 'Reset').removeClass('loading disabled');
  	    		       	clearTimeout(ajaxWait);
  	    		    },
  	    		    complete: function() {
  	    		    	clearTimeout(ajaxWait);
  	    		    }
				});
			},
			invalidHandler: function(form, validator) {
				//Show notification panel with number of errors
				var errors = validator.numberOfInvalids();
				if (errors) {
		      		var message = errors == 1
						? 'You missed 1 field. Please correct the error and try again.'
						: 'You missed ' + errors + ' fields. Please correct the errors and try again.';
		        	open_notify('error','Form Error', message);
		      	}
		    }
		});
	}
	
	/* MY ACCOUNT PAGE */
	if (bodyID == 'my-account') {
		//Account Tabs
		$('li > a', account_nav).live('click', function() {
			//Find index of clicked Anchor
			nav_index = $(this).parent('li').index();
			//Remove clicked Anchor's class
			$('li > a', account_nav).removeClass('current');
			//Hide visible content
			$('li.nav_item', account_content).not(nav_index).hide();
			//Show clicked Anchor's content & add class
			$('li.nav_item', account_content).eq(nav_index).show();
			$(this).addClass('current');
			return false;
		});
		
		//Show delivery address if checked
		if ($(document.getElementById('show_other_address')).prop('checked')) {
			$('#other_address', '#delivery_address').show();
		}
		
		//Validate Account Details Form
		$('#ac_details_form').validate({
			errorElement: 'div',
			rules: {
				user_password: "required",
				confirm_user_password: {
					equalTo: "#user_password"
				}
			},
			invalidHandler: function(form, validator) {
				//Show notification panel with number of errors
				var errors = validator.numberOfInvalids();
				if (errors) {
		      		var message = errors == 1
						? 'You missed 1 field. Please correct the error and try again.'
						: 'You missed ' + errors + ' fields. Please correct the errors and try again.';
		        	open_notify('error','Form Error', message);
		      	}
		    },
		    submitHandler: function(form) {
		    	$('#user_update').prop('disabled', true).addClass('loading disabled').attr('value', '');
		    	var ajaxWait = setTimeout("open_notify('','Please Wait', 'Sorry, it is taking a little longer than usual.')",8000);
			   	$.ajax({
					url: '/gateway/user-update-details',
	    			data: $(form).serializeArray(),
					dataType: 'json',
					type: 'POST',
	    			error: function() {
	    				open_notify('error', "Sorry there appears to have been an error. Please try again.");
	    				$('#user_update').removeProp('disabled').attr('Value', 'Update').removeClass('loading disabled');
	    				clearTimeout(ajaxWait);
	    			},
	    			success: function(data) {
	    				if (data.success === 1) {
	    					open_notify('success',data.title, data.message);
	    				} else {
  	    		       		open_notify('error',data.title, data.message);
  	    		       	}
  	    		       	$('#user_update').removeProp('disabled').attr('Value', 'Update').removeClass('loading disabled');
  	    		       	clearTimeout(ajaxWait);
  	    		    },
  	    		    complete: function() {
  	    		    	clearTimeout(ajaxWait);
  	    		    }
				});
				return false;
			}
			//,debug: true
		});
		
		//Show & Hide other address fields
		$('#show_other_address', '#delivery_address').bind('click', function() {
			$(this).parents('#delivery_address').children('#other_address').slideToggle();
		});
		
		//Enable other field
		enableOtherField('#title_input', '#ac_details_form');
		
		//Nearest Salon Field
		$.ajax({
		    url: '/gateway/user-salon-list',
		    dataType: 'json',
		    success: function(data){
		    	init_salon_data(data);
		    }
		});
		
		//Show Previous Order Details
		$('li > h3', '#previousOrders').bind('click', function() {
			
			if ($(this).hasClass('more')) {
				$(this).removeClass('more').children('span').text('+').parent().next('.orderInfo').stop(true, true).slideUp();
			} else {
				$(this).addClass('more').children('span').text('-').parent().next('.orderInfo').stop(true, true).slideDown();
			}
			return false;
		});
	}
	
	/* SITE MANAGER */
	if (bodyID == 'site-manager') {
		$('#tracking_form').validate({
			errorElement: 'div',
			invalidHandler: function(form, validator) {
				//Show notification panel with number of errors
				var errors = validator.numberOfInvalids();
				if (errors) {
		      		var message = errors == 1
						? 'You missed 1 field. Please correct the error and try again.'
						: 'You missed ' + errors + ' fields. Please correct the errors and try again.';
		        	open_notify('error','Form Error', message);
		      	}
		    },
		    submitHandler: function(form) {
		    	$('#tracking_submit', '#tracking_form').prop('disabled', true).addClass('loading disabled').attr('value', '');
		    	var ajaxWait = setTimeout("open_notify('','Please Wait', 'Sorry, it is taking a little longer than usual.')",8000);
			   	$.ajax({
					url: '/gateway/tracking-manager',
	    			data: $(form).serializeArray(),
					dataType: 'json',
					type: 'POST',
	    			error: function() {
	    				open_notify('error', "Sorry there appears to have been an error. Please try again.");
	    				$('#tracking_submit', '#tracking_form').removeProp('disabled').attr('Value', 'Update').removeClass('loading disabled');
	    				clearTimeout(ajaxWait);
	    			},
	    			success: function(data) {
	    				if (data.success === 1) {
	    					open_notify('success',data.title, data.message);
	    				} else {
  	    		       		open_notify('error',data.title, data.message);
  	    		       	}
  	    		       	$('#tracking_submit', '#tracking_form').removeProp('disabled').attr('Value', 'Update').removeClass('loading disabled');
  	    		       	clearTimeout(ajaxWait);
  	    		    },
  	    		    complete: function() {
  	    		    	clearTimeout(ajaxWait);
  	    		    }
				});
				return false;
			}
		});
	}
	
});

