// Application var using global abatement
var fbs = {
	/*
	 *	Helper and utility functions
	 */
	helpers : {
		getPage : function() {
			var detectedPage = "UNKNOWN_PAGE";
			if($("body").attr("class")) {
				fbs.options.DEBUG ? console.log("Body Classes: " + classes) : "";
				var classes = ($("body").attr("class").split(" "));
				$.each(classes, function(index, value) {
					if(value.substring(0, 5) === "page-") {
						detectedPage = (value.substring(5)).trim();
					}
				});

			}
			return detectedPage;
		},

		showModal : function() {
			var modal = $("[data-controls-modal]");
			if(modal.attr("data-show") === "true") {
				return true;
			}

			return false;
		},

		showConfirm : function(button) {
			var modalDiv = $('<div></div>', {
				id : 'confirm-modal',
				class : 'modal hide',
				style : 'display:none;',
			});

            var title = button.data('confirm-title') ? button.data('confirm-title') : "Are you sure?";
			modalDiv.append('<div class="modal-header"><h2>' + title + '</h2></div>');
			modalDiv.append($('<div></div>', {
				class : "modal-body",
				style : "text-align:center;"
			}).append($('<h4></h4>', {
				html : button.data('confirm-message')
			})));

			var modalFooter = $('<div></div>', {
				class : 'modal-footer'
			});

			var yes = $('<button></button>', {
				class : 'btn primary',
				html : 'Yes',
				click : function() {
					button.unbind('click');
					button.click();
				}

			});

			var no = $('<button></button>', {
				class : 'btn',
				html : 'No',
				click : function() {
					$('#confirm-modal').modal('hide');
					$('#confirm-modal').remove();
				}

			});

			modalFooter.append(no);
			modalFooter.append(yes);
			modalDiv.append(modalFooter);
			$('body').append(modalDiv);

			var $this = $(this).data({
				'show' : true,
				'backdrop' : 'static'
			});
			$('#confirm-modal').modal($this.data());
		},

		switchUsers : function(unique_key, password) {
			if(password === undefined) {
				$.ajax({
					url : "/salons/authentication/switch_user",
					type : "POST",
					data : "unique_key=" + unique_key + "&ci_csrf_token=" + $.cookie('ci_csrf_token'),
					dataType : "JSON",
					success : function(data) {
						if(data.action === "redirect") {
							window.location.replace(data.location);
						} else if(data.action === "authenticate") {
							// User is admin so get their password and re-submit
							var modalDiv = $('<div></div>', {
								id : 'auth-modal',
								class : 'modal hide',
								style : 'display:none;',
							});

							modalDiv.append('<div class="modal-header"><h2>Please enter your password</h2></div>');

							var modalBody = $('<div></div>', {
								class : 'modal-body'
							});

							modalBody.append('<p>The account you are attempting to login to is an administrator account. Please enter your password in order to access this account</p>');
							modalBody.append($('<form></form>').append($('<div></div>', {
								class : 'clearfix'
							}).append($('<label></label>', {
								'for' : 'switch-user-pw',
								html : 'Password'
							})).append($('<div></div>', {
								class : 'input'
							}).append($('<input />', {
								id : 'switch-user-pw',
								class : 'xlarge',
								type : 'password',
								name : 'password'
							})))));

							var modalFooter = $('<div></div>', {
								class : 'modal-footer'
							});

							var auth = $('<button></button>', {
								class : 'btn primary',
								html : 'Switch users',
								click : function() {
									fbs.helpers.switchUsers(unique_key, $('#auth-modal input#switch-user-pw').val());
								}

							});

							var cancel = $('<button></button>', {
								class : 'btn',
								html : 'Cancel',
								click : function() {
									$('#auth-modal').modal('hide');
									$('#auth-modal').remove();
								}

							});

							modalFooter.append(cancel);
							modalFooter.append(auth);
							modalDiv.append(modalBody);
							modalDiv.append(modalFooter);
							$('body').append(modalDiv);

							var $this = $(this).data({
								'show' : true,
								'backdrop' : 'static'
							});
							$('#auth-modal').modal($(this).data());
						}
					},

					error : function() {
						alert("It was not possible to change user account. An unexpected error occurred. Please try again");
					},

				});
			} else {
				// This is an authentication request
				$.ajax({
					url : "/salons/authentication/switch_user",
					type : "POST",
					data : "unique_key=" + unique_key + "&password=" + password + "&ci_csrf_token=" + $.cookie('ci_csrf_token'),
					dataType : "JSON",
					success : function(data) {
						if(data.action === "redirect") {
							window.location.replace(data.location);
						} else if(data.action === "show_error") {
							if($('#auth-modal .modal-body .alert-message').length > 0) {
								$('#auth-modal .modal-body .alert-message p').text(data.error);
							} else {
								$('#auth-modal .modal-body').prepend('<div class="alert-message error"><p>' + data.error + '</p></div>');
							}
						}
					},

					error : function() {
						alert("It was not possible to change user account. An unexpected error occurred. Please try again");
					}

				});
			}
			return false;
		},

		resume : function(unique_key, password) {
			if(password === undefined) {
				$.ajax({
					url : "/salons/authentication/switch_user",
					type : "POST",
					data : "unique_key=" + unique_key + "&ci_csrf_token=" + $.cookie('ci_csrf_token'),
					dataType : "JSON",
					success : function(data) {
						if(data.action === "redirect" && unique_key !== '' && data.error === undefined) {
							window.location.replace(data.location);
				        } else if (data.error) {
				            $(".lock-login-container").animate({
									height : "+=44px"
								}, 500);
				            if($('.lock-login-body .alert-message').length > 0) {
    							$('.lock-login-body .alert-message p').text(data.error);
    						} else {
    							$('.lock-login-body').prepend('<div class="alert-message error"><p>' + data.error + '</p></div>');
    						}
						} else if(data.action === "authenticate") {
							if($(".lock-login-body #password").length === 0) {
                                if ($(".lock-login-body .alert-message").length > 0) {
                                    $('.lock-login-body .alert-message').remove();
                                }
								// User is admin so get their password and re-submit
								var $pwField = $('<div></div>', {
									class : 'clearfix'
								}).append($('<label></label>', {
									'for' : 'password',
									html : 'Password'
								})).append($('<div></div>', {
									class : 'input'
								}).append($('<input />', {
									type : 'password',
									name : 'password',
									id : 'password',
									class : 'large'
								})));

								$pwField.insertBefore($(".lock-login-body #resume-system"));
								$(".lock-login-container").animate({
									height : 215
								}, 500);
							}
							return false;
						}
					},

					error : function() {
						alert("It was not possible to change user account. An unexpected error occurred. Please try again");
					},

				});
			} else {
				// This is an authentication request
				$.ajax({
					url : "/salons/authentication/switch_user",
					type : "POST",
					data : "unique_key=" + unique_key + "&password=" + password + "&ci_csrf_token=" + $.cookie('ci_csrf_token'),
					dataType : "JSON",
					success : function(data) {
						if(data.action === "redirect") {
							window.location.replace(data.location);
						} else if(data.action === "show_error") {
							if($('.lock-login-container .lock-login-body .alert-message').length > 0) {
								$('.lock-login-container .lock-login-body .alert-message p').text(data.error);
							} else {
								$('.lock-login-container .lock-login-body').prepend('<div class="alert-message error"><p>' + data.error + '</p></div>');
								$('.lock-login-container').animate({
									height : "+=44px"
								}, 300);
							}
						}
					},

					error : function() {
						alert("It was not possible to change user account. An unexpected error occurred. Please try again");
					}

				});
			}
			return false;
		},

		scrollCalendarDates : function(direction) {
			// Fetch our starting date
			var dateBtnNum = direction === 'left' ? 8 : 0;
			var startDate = new Date($('#day-sel-day-today-p' + dateBtnNum).data('date'));

			$('.day-btn').animate({
				left : '-=100px'
			}, 1000);
		},
		
		chznAddCallbacks : {
		
            addRole : function(term, field) {
                $.ajax({
					url : "/salons/staff/add_staff_type",
					type : "POST",
					data : "name=" + term + "&ci_csrf_token=" + $.cookie('ci_csrf_token'),
					dataType : "JSON",
					success : function(data) {
						if (data.role_id) {
                            field.append_option({
                               value: data.role_id,
                               text: term
                            });
						} else if (data.error) {
                            alert (data.error);
						}
					},

					error : function() {
						alert ("It was not possible to add a new role. Please try again");
					}

				});
            },
            
            addProdCategory : function(term, field) {
                $.ajax({
					url : "/salons/inventory/add_category",
					type : "POST",
					data : "cat_name=" + term + "&ci_csrf_token=" + $.cookie('ci_csrf_token'),
					dataType : "JSON",
					success : function(data) {
						if (data.category_id) {
                            field.append_option({
                               value: data.category_id,
                               text: term
                            });
						} else if (data.error) {
                            alert (data.error);
						}
					},

					error : function() {
						alert ("It was not possible to add a new category. Please try again");
					}

				});
            },
            
            addService : function(term, field) {
                $.ajax({
					url : "/salons/salon_services/add_service",
					type : "POST",
					data : "name=" + term + "&ci_csrf_token=" + $.cookie('ci_csrf_token'),
					dataType : "JSON",
					success : function(data) {
						if (data.service_id) {
                            field.append_option({
                               value: data.service_id,
                               text: term
                            });
						} else if (data.error) {
                            alert (data.error);
						}
					},

					error : function() {
						alert ("It was not possible to add a new service. Please try again");
					}

				});
            },
            
            addServiceCategory : function(term, field) {
                $.ajax({
					url : "/salons/salon_services/add_category",
					type : "POST",
					data : "name=" + term + "&ci_csrf_token=" + $.cookie('ci_csrf_token'),
					dataType : "JSON",
					success : function(data) {
						if (data.category_id) {
                            field.append_option({
                               value: data.category_id,
                               text: term
                            });
						} else if (data.error) {
                            alert (data.error);
						}
					},

					error : function() {
						alert ("It was not possible to add a new service. Please try again");
					}

				});
            }
		
		}

	},
	/*
	 *	Appwide settings and variables
	 */
	options : {
		defaultDatepickerOptions : {
			dateFormat : 'dd-mm-yy',
			dayNamesMin: ['S', 'M', 'T', 'W', 'T', 'F', 'S'],
			changeMonth : true,
			changeYear : true,
			firstDay: 1,
			monthNamesShort: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
			showOtherMonths: true,
			selectOtherMonths: true
		},
		defaultTimeEntryOptions : {
            show24Hours: true,
            useMouseWheel: false,
            spinnerImage: '',
            ampmNames: ['', '']
		},
		DEBUG : true
	},
	/*
	 *	Common behaviour for forms
	 */
	forms : {
		formInit : function() {

			/*
			 *	Setup user editable tables
			 */
			$('table.user-editable').each(function() {

                $(this).find(".remove-row").click(function() {
                    $(this).parents("tr").remove();
                });
                
				var $currentTable = $(this);
				var $placeholderRow = $currentTable.find('.editable-row-placeholder');
				
                var rowIndex = $(this).find("tbody tr[class!=editable-row-placeholder]").length;
                
				$(this).find("tr:last").delegate('a.add-row', 'click', function() {
				    
				    var $newRow  = $placeholderRow.clone();
				    $newRow.find('td').each(function() {
				    
				        $(this).find("input, select").each(function() {
    				        // Update its name if required
    				        var name = $(this).attr("name");
    				        if (name !== undefined) {
    				            name = name.replace("%row", rowIndex);
    				            $(this).attr("name", name);
    				        }
				        });
				    });
				    
				    $newRow.removeClass("editable-row-placeholder");
				    $newRow.insertBefore($(this).parents("tr"));
				    
				    $(this).parents("table").find("tr:last").prev().find("td").each(function() {
				        $(this).find("input, select").each(function() {
				        
				            // Ensure the input is enabled for submission
    				        $(this).removeAttr("disabled");
    				        
				            // Enable chosen on this field if required
    				        if ($(this).hasClass("chzn")) {
    				            $(this).chosen();
    				        }
				        });
				        
				        $(this).find(".remove-row").click(function() {
				            $(this).parents("tr").remove();
				            return false;
				        });
				    });
				    rowIndex++;
				    return false;
				});

			});
			
			
			if (typeof jQuery.fn.chosen === "function") {
                // This check means we don't have to load chosen for the remote booking screen when we're not going to use it anyway
                $(".chzn-load").chosen();
                $(".chzn-add-load").chosen({
                    create_option_text: "Add this option",
                    create_option: function(term) {
                        var functionName = "fbs.helpers.chznAddCallbacks." + $(this.form_field).data('callback');
                        eval(functionName)(term, this);
                    }
                });
			}
			
			$(".time").timeEntry(fbs.options.defaultTimeEntryOptions);

		}

	},
	/*
	 *	Common behaviour to all pages in the system
	 */
	globalInit : function() {
		fbs.options.DEBUG ? console.log("Running globalinit()") : "";

		// Augmented functions for later use
		if( typeof String.prototype.trim !== 'function') {
			String.prototype.trim = function() {
				// Props to Steven Levithan http://blog.stevenlevithan.com/archives/faster-trim-javascript
				return str.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
			}

		}

		if($('form').size() > 0) {
			fbs.forms.formInit();
		}

		// Setup optional content for forms
		var $optionalContentItems = $('form .optional-content').parents('fieldset').find('input[type=radio]');

		$optionalContentItems.each(function() {
			var $currentItem = $(this);

			if($currentItem.is(':checked')) {
                if ($(this).parents('label').siblings('.optional-content').length > 0 || $(this).data('show-container')) {
                    if($(this).data('show-container')) {
    					$optionalContainer = $('#' + $(this).data('show-container'));
    				} else {
    					$optionalContainer = $(this).parents('li').find('.optional-content');
    					$optionalContainer.slideDown(400, function() {
    						$optionalContainer.fadeTo(400, 1);
    					});
    
    				}
                }
			}
		});


		$optionalContentItems.change(function() {
			$optionalContainer = null;
			if($(this).data('show-container')) {
				$optionalContainer = $('#' + $(this).data('show-container'));
			} else {
				$optionalContainer = $(this).parents('li').find('.optional-content');
			}

			if($optionalContainer.length > 0) {
				$optionalContainer.slideDown(400, function() {
					$optionalContainer.fadeTo(400, 1);
				});

				if($(this).parents('li').siblings().find('[name="' + $(this).attr('name') + '"][data-show-container]:visible').length > 0) {
					$(this).parents('li').siblings().find('[name="' + $(this).attr('name') + '"][data-show-container]:visible').each(function() {
						$("#" + $(this).data('show-container')).fadeTo(400, 0, function() {
							$(this).slideUp();
						});

					});

				}
			} else {
				if($(this).parents('li').siblings().find('[name="' + $(this).attr('name') + '"][data-show-container]').length > 0) {
					$('input[name="' + $(this).attr('name') + '"][data-show-container]').each(function() {
						$('#' + $(this).data('show-container')).fadeTo(400, 0, function() {
							$(this).slideUp();
						});

					});

				}

				if($(this).parents('li').siblings().find('.optional-content').is(':visible')) {
					$(this).parents('li').siblings().find('.optional-content').fadeTo(400, 0, function() {
						$(this).slideUp();
					});

				}
			}
		});

        updateTimes = function() {
            $(".live-time").each(function() {
                var datetime = $(this).data('start-time') ? new Date($(this).data('start-time') * 1000) : new Data();
                
                datetime.setSeconds(datetime.getSeconds() + 1);
                $(this).data('start-time', datetime / 1000);
                
                var hours = ("0" + datetime.getHours()).slice(-2);
                var mins  = ("0" + datetime.getMinutes()).slice(-2);
                var secs  = ("0" + datetime.getSeconds()).slice(-2);
                
                $(this).html(hours + ':' + mins + ':' + secs);
            });
        }
        
        setInterval('updateTimes()', 1000);
	},

	pageInit : function(page) {
		var that = this;
		if(page !== "UNKNOWN_PAGE") {
			fbs.options.DEBUG ? console.log("Called pageInit for " + page) : "";
			var page = page.toLowerCase();
			if(page === "home") {
				$("#diary-lhs-pad-content").mCustomScrollbar("vertical", 900, "easeOutCirc", 1.05, "auto", "yes", "no", 0);
				$("#diary-rhs-pad-content").mCustomScrollbar("vertical", 900, "easeOutCirc", 1.05, "auto", "yes", "no", 0);

				if($("body").hasClass("locked")) {
					$(".lock-screen").show(150);
					$(".lock-login-float").show(150);
				}

				var dpOptions = {
					beforeShow: function(input, instance) {
						// Grab the datepicker instance						
						var $dpDiv = instance.dpDiv;		
										
						// Move the element from body to a more suitable containing element
						$dpDiv.appendTo('#day-controls');
					},
					onSelect : function(dateText, instance) {
						window.location.replace('/salons/salon_home/' + dateText);
					},
					showOn : 'button'
				};
				
				$('#day-sel-calendar-datepicker').datepicker($.extend({}, fbs.options.defaultDatepickerOptions, dpOptions));

				$("#day-sel-calendar-btn-link").click(function() {
					var $trigger = $(this);
					$('#day-sel-calendar-datepicker').datepicker("show");

					var $picker = $('#ui-datepicker-div');
					var pickerWidth = $picker.width(); 
					
					// Ensure date picker is above calendar and set correct position
					$('#ui-datepicker-div')
						.css('z-index', 100)
						.offset({ left: parseInt($trigger.offset().left - pickerWidth/2 + 15, 10), top: 30 });
				});

				// Prepare 'next' and 'previous' calendar date buttons
				$('#day-sel-next-btn-link').bind('click', function() {

				});


				$('#day-sel-prev-btn-link').bind('click', function() {

				});
				
				$(".show-appointment").click(function() {
				    $("#view-appointment-modal #appt-cust-name").val($(this).data('customer-name'));
				    $("#view-appointment-modal #appt-staff-name").val($(this).data('staff-name'));
				    
				    var startDate = new Date($(this).data('datetime') * 1000);
				    var endDate   = new Date($(this).data('end-datetime') * 1000);
				    
				    $("#view-appointment-modal #appt-start-date").val($.datepicker.formatDate('dd-mm-yy', startDate));
				    $("#view-appointment-modal #appt-start-time").val(startDate.getHours() + ":" + startDate.getMinutes());
				    
				    $("#view-appointment-modal #appt-end-date").val($.datepicker.formatDate('dd-mm-yy', endDate));
				    $("#view-appointment-modal #appt-end-time").val(endDate.getHours() + ":" + endDate.getMinutes());
				    
				    $("#view-appointment-modal .modal-footer .amend-appointment").attr("href",  "/salons/salon_home/amend_appointment/" + $(this).data('appointment-id'));
				    $("#view-appointment-modal .modal-footer #payment-transaction").val($(this).data("transaction"));
				    
				    if ($(this).data("paid") === true) {
				        $("#view-appointment-modal .modal-footer #amend-pay-now").hide();
				    }
				    else {
				        $("#view-appointment-modal .modal-footer #amend-pay-now").show();
				    }
				    
				    if ($(this).data("flagged") === true) {
				        $("#view-appointment-modal .modal-footer #view-notes").attr("href",  "/salons/customers/view_customer/" + $(this).data('customer-id'));
				        $("#view-appointment-modal .modal-footer #view-notes").show();
				    } else {
				        $("#view-appointment-modal .modal-footer #view-notes").attr("href", "#");
				        $("#view-appointment-modal .modal-footer #view-notes").hide();
				    }
				    
				    var $this = $(this).data({
						'show' : true,
						'backdrop' : 'static',
						'keyboard' : true
					});
				    $("#view-appointment-modal").modal($this.data());
				    
				    return false;
				});
				
				$(".waiting-list-assign").click(function() {
				
				    $("#assign-waiting-list-modal #queue").val($(this).data("queue-id"));
				    var $this = $(this).data({
						'show' : true,
						'backdrop' : 'static',
						'keyboard' : true
					});
				    $("#assign-waiting-list-modal").modal($this.data());
				});
				
				$(".waiting-list-pay").click(function() {
				
				    $("#pay-waiting-list-modal #transaction").val($(this).data("transaction-id"));
				    var $this = $(this).data({
						'show' : true,
						'backdrop' : 'static',
						'keyboard' : true
					});
				    $("#pay-waiting-list-modal").modal($this.data());
				});
				
				$(".waiting-list-scroll-right").click(function() {
				    var currentScroll = $(".waiting-list-scroll-wrapper").data("currentposition");
				        currentScroll = currentScroll ? currentScroll : 0;
				    var scroll        = Math.min(300, $(".waiting-list").width() - currentScroll);
				    $(".waiting-list-scroll-wrapper").data("currentposition", currentScroll + scroll);
				    $(".waiting-list-scroll-wrapper").animate({scrollLeft: "+=" + scroll});
				    return false;
				});
				
				$(".waiting-list-scroll-left").click(function() {
				    var currentScroll = $(".waiting-list-scroll-wrapper").data("currentposition");
				        currentScroll = currentScroll ? currentScroll : 0;
				    var scroll        = Math.min(300, $(".waiting-list").width() - currentScroll);
				    $(".waiting-list-scroll-wrapper").data("currentposition", currentScroll - scroll);
				    $(".waiting-list-scroll-wrapper").animate({scrollLeft: "-=" + scroll});
				    return false;
				});
				
				$(".toggle-calendar-staff").change(function() {
				    var staffID = $(this).data("staff");
				    if ($(this).is(":checked")) {
				        $("#employee-column-" + staffID).show();
				    } else {
				        $("#employee-column-" + staffID).hide();
				    }
				});

			} else if(page === "vouchers") {
				this.updateDiscountTypeLabel = function() {
					var discountType = $('#discount_type').val();
					if(discountType === 'P') {
						$('#discount_value').siblings('.add-on').text('%');
					} else if(discountType === 'V') {
						$('#discount_value').siblings('.add-on').text('£');
					} else {
						$('#discount_value').siblings('.add-on').text('?');
					}
				}

				/*
				 *	Call the update function initially incase the select already has a non default value on page load
				 */
				this.updateDiscountTypeLabel();

				// Setup listener for discount type field so we can update the prepend label for the amount field
				$('#discount_type').change(function() {
					that.updateDiscountTypeLabel();
				});
				
				// Setup the chosen fields
				$("table tbody tr[class!=editable-row-placeholder] .chzn").chosen()

			} else if(page === "send-sms") {
				var $messageField = $('#message');
				var $messageCharCounter = $messageField.parents('ul').siblings('.help-block');
				var messageFieldHelpText = $messageCharCounter.text();
				var charsPerSMS = 160;
				var messageTemplate = "{charsUsed}/" + charsPerSMS + " characters ({numMessages} message)";

				this.updateCounter = function(usedChars) {
					var compiledMessage = messageTemplate;
					compiledMessage = compiledMessage.replace('{charsUsed}', usedChars);
					compiledMessage = compiledMessage.replace('{numMessages}', Math.ceil(parseInt(usedChars, 10) / parseInt(charsPerSMS, 10)));
					$messageCharCounter.text(compiledMessage);
				}

				/*
				 *	Call the update function initially incase the textarea already has content on page load
				 * e.g. the user enters some text and then refreshes the page.
				 */
				if($messageField.val().length > 0) {
					this.updateCounter($messageField.val().length);
				}

				// Setup listener for message body field to update character counter
				$('form').on('keyup', null, function() {
					var usedChars = $messageField.val().length;
					if(usedChars > 0) {
						that.updateCounter(usedChars);
					} else {
						$messageCharCounter.text(messageFieldHelpText);
					}
				});

				// Add action for button to add voucher code to the message
				$('.insert-voucher').click(function() {
					$("#message").insertAtCaret("{voucher}");
					return false;
				});

				// Add action for button to add salon name to the message
				$('.insert-salon-name').click(function() {
					$("#message").insertAtCaret("{salon-name}");
					return false;
				});

				criteriaChangeEvent = function($row) {
					$row.find(".search-condition option").hide();
					$row.find(".input").hide();
					conditions = $row.find(".search-criteria :selected").data("conditions").split(",");
					valueType = $row.find(".search-criteria :selected").data("value");
					$.each(conditions, function(index, value) {
						$row.find(".search-condition option[value='" + value + "']").show();
						if(index === 0) {
							$row.find(".search-condition").val(value);
						}
					});


					$row.find(".input .search-value-" + valueType).parents(".input").show();
				}

				// Set defaults for custom search modal

				$("#customers-modal .search-criteria :selected").each(function() {
					$row = $(this).parents("tr");
					criteriaChangeEvent($row);
				});


				$("#customers-modal .remove-criteria").click(function() {
					$(this).parents("tr").remove();
				});

				// Setup handlers for customer search modal
				var rowCount = 0;
				$("#add-search-term").click(function() {
					var $placeholder = $(this).parents("tbody").find("tr.editable-row-placeholder").clone();
					$placeholder.find(".search-condition option").hide();
					$placeholder.find(".search-criteria").change(function() {
						$row = $(this).parents("tr");
						criteriaChangeEvent($row);
					});


					$placeholder.find(".remove-criteria").click(function() {
						$(this).parents("tr").remove();
						return false;
					});
					
					$placeholder.find(".search-value-date").datepicker(fbs.options.defaultDatepickerOptions);


					$placeholder.find(".input .search-value-" + valueType).show();
					$placeholder.removeClass("editable-row-placeholder");
					$placeholder.find(".search-criteria").attr("name", "criteria_type[" + rowCount + "]").removeAttr("disabled");
					$placeholder.find(".search-condition").attr("name", "criteria_condition[" + rowCount + "]").removeAttr("disabled");
					$placeholder.find(".search-value-date").attr("name", "criteria_date[" + rowCount + "]").removeAttr("disabled");
					$placeholder.find(".search-value-price").attr("name", "criteria_price[" + rowCount + "]").removeAttr("disabled");
					$placeholder.find(".search-value-service").attr("name", "criteria_service[" + rowCount + "]").removeAttr("disabled");
					$placeholder.find(".search-value-value").attr("name", "criteria_value[" + rowCount + "]").removeAttr("disabled");
					$placeholder.insertBefore($("#customers-modal table tr").last());
					criteriaChangeEvent($placeholder);
					$placeholder.find(".input .search-value-" + valueType).parents(".input").show();
					rowCount++;
					return false;
				});

				addRecipients = function(response) {
					if(response.error) {
						if($('#customers-modal .modal-body .alert-message').length > 0) {
							$('#customers-modal .modal-body .alert-message p').text(response.error);
						} else {
							$('#customers-modal .modal-body').prepend('<div class="alert-message error"><p>' + response.error + '</p></div>');
						}
					} else {
						$recipientsTable = $("#sms-recipients").clone();
						$recipientsTable.find("tr").last().siblings().remove();
						$.each(response, function(index, value) {
							$row = $("<tr></tr>").append($("<td></td>").append($("<input />", {
								type : "text",
								name : "recipients[" + value.customer_id + "]",
								value : value.forename + " " + value.surname,
								readonly : "readonly"
							})));
							$row.insertBefore($recipientsTable.find("tr").last());
						});

						if($("#open-customers-modal").parents("tr").siblings().length > 0) {
							$("#open-customers-modal").parents("tr").siblings().replaceWith($recipientsTable.find("#open-customers-modal").parents("tr").siblings());
						} else {
							$recipientsTable.find("#open-customers-modal").parents("tr").siblings().insertBefore($("#open-customers-modal").parents("tr"));
						}

						if($('#customers-modal .modal-body .alert-message').length > 0) {
							$('#customers-modal .modal-body .alert-message').remove();
						}

						$("#customers-modal #add-search-term").parents("tr").siblings("[class!='editable-row-placeholder']").remove();
						$("#customers-modal").modal("hide");
					}
				}


				$("#customers-modal #find-recipients").click(function() {
					$.ajax({
						url : "/salons/customers/find_customers_ajax",
						data : $(this).parents(".modal-footer").siblings(".modal-body").find("form").serialize(),
						dataType : "JSON",
						type : "POST",
						beforeSend : function() {
							$("#customers-modal").block({
								message : "Searching"
							});
						},

						success : function(response) {
							addRecipients(response);
						},

						error : function() {
							alert("Unable to search for recipients. An unexpected error occurred");
						},

						complete : function() {
							$("#customers-modal").unblock();
						}

					});
				});


				$("#select-all-customers").click(function() {
					$.ajax({
						url : "/salons/customers/all_customers_ajax",
						dataType : "JSON",
						type : "POST",
						beforeSend : function() {
							$("#customers-modal").block({
								message : "Searching"
							});
						},

						success : function(response) {
							addRecipients(response);
						},

						error : function() {
							alert("Unable to search for recipients. An unexpected error occurred");
						},

						complete : function() {
							$("#customers-modal").unblock();
						}

					});
				});

			} else if(page === "checkout") {
				// Check if the payment method is cash and show cash field if so
				if($('input[name="payment_type"]:checked').val() === "CASH") {
					$('#cash-field').show();
				}

				$("#add_prod").autocomplete({
					source : "/salons/inventory/product_search_ajax"
				});
			} else if(page === "register-salon") {
				if($("#child_salon").is(":checked")) {
					$("#vat_reg").parents("div .clearfix").hide();
					$("#voucher").parents("div .clearfix").hide();
					$("#company_id").parents("div .clearfix").show();
				} else {
					$("#company_id").parents("div .clearfix").hide();
					$("#vat_reg").parents("div .clearfix").show();
					$("#voucher").parents("div .clearfix").show();
				}

				$("#child_salon").bind("click", function() {
					$("#vat_reg").parents("div .clearfix").toggle(500);
					$("#voucher").parents("div .clearfix").toggle(500);
					$("#company_id").parents("div .clearfix").toggle(500);
				});

			} else if(page === "registration") {
				$('label[for="company_name"]').html($('input[name="registration_type"]:checked').val() === "individual" ? "Salon Name" : "Company Name");
				$('input[name="registration_type"]').change(function() {
					$('label[for="company_name"]').html($(this).val() === "individual" ? "Salon Name" : "Company Name");
				});
				
				$('button.confirm-email').click(function(){
				    if ($("#contact_email").val().length > 0) {
				        $("#contact_email_conf").val($("#contact_email").val());
				        $(this).data('confirm-title', 'Please confirm your email address');
				        $(this).data('confirm-message', 'Is the email address "' + $("#contact_email").val() + '" correct?');
				        fbs.helpers.showConfirm($(this));
				        return false;
				    }
				});

			} else if(page === "find-appointment") {
				$(".select-service").click(function() {
					var service     = $(this).data('service');
					var type        = $(this).data('type');
					var serviceName = $(this).text();
					var typeName    = $(this).parents("td").siblings().text();
					if($(".required-services tr input[name='required_service[" + service + ':' + type + "]']").length === 0) {
						// Not already added so lets add it
						$("<tr></tr>").append($("<td></td>").append($("<input>", {
							class : "xlarge disabled",
							value : serviceName + " (" + typeName + ")",
							type : "text",
							name : "required_service[" + service + ":" + type + "]",
							readonly : "readonly"
						}))).append($("<td></td>").append($("<a></a>", {
							href : "#",
							html : "Remove",
							click : function() {
								// If any criteria is changed, then remove all existing search results
								if($("#appointments").length > 0) {
									$("#appointments").slideUp(400, function() {
										$("#appointments").remove();
									});

								}
								$(this).parents("tr").remove();
							}

						}))).insertBefore($(".required-services").find("tr").last());
						// If any criteria is changed, then remove all existing search results
						if($("#appointments").length > 0) {
							$("#appointments").slideUp(400, function() {
								$("#appointments").remove();
							});

						}
					}
					// Now close the modal
					$("#services-modal").modal("hide");
				});


				$(".remove-service").click(function() {
					// If any criteria is changed, then remove all existing search results
					if($("#appointments").length > 0) {
						$("#appointments").slideUp(400, function() {
							$("#appointments").remove();
						});

					}
					$(this).parents("tr").remove();
				});


				$("#" + $("input[name='search_for']:checked").data('show-container')).show();

				$("#search-criteria form input, #search-criteria form select").change(function() {
					// If any criteria is changed, then remove all existing search results
					if($("#appointments").length > 0) {
						$("#appointments").slideUp(400, function() {
							$("#appointments").remove();
						});

					}
				});


				$("a.book-appointment").click(function() {
					var date = new Date($(this).data('datetime') * 1000);

					// Set fields on modal
					$("#appointment-modal #appt-date").val($.datepicker.formatDate('dd-mm-yy', date));
					$("#appointment-modal #appt-time").val(date.toLocaleTimeString());
					$("body").not(".iframe").find("#appointment-modal #appt-services tbody").empty().append($(".required-services tbody tr td input").parents("tr").clone());
					$("body").not(".iframe").find("#appointment-modal #appt-services tbody .remove-service").parent().remove();
					$("#appointment-modal #appt-staff").val($(this).parents(".tab-pane").find(".staff-name").html());
					$("#appointment-modal #appt-staff-id").val($(this).parents(".tab-pane").attr("id"));
					$("body").not(".iframe").find("#appointment-modal #appt-customer").val($("#customer").val());
					$("body").not(".iframe").find("#appointment-modal #appt-customer-id").val($("#customer-id").val());

					var $this = $(this).data({
						'show' : true,
						'backdrop' : 'static',
						'keyboard' : true
					});
					$("#appointment-modal").modal($this.data());
					return false;
				});


				$(".select-customer").click(function() {
					$("#customer").val($(this).html());
					$("#customer-id").val($(this).data("cust-id"));
					$("#customers-modal").modal("hide");
				});


				$("#btn-confirm-appointment").click(function() {
					$.ajax({
						url : "/salons/salon_home/create_appointment",
						data : $(this).parents(".modal-footer").siblings(".modal-body").find("form").serialize(),
						dataType : "JSON",
						type : "POST",
						success : function(response) {
							if(response.error) {
								if($('#appointment-modal .modal-body .alert-message').length > 0) {
									$('#appointment-modal .modal-body .alert-message p').text(response.error);
								} else {
									$('#appointment-modal .modal-body').prepend('<div class="alert-message error"><p>' + response.error + '</p></div>');
								}
							} else if(response.success) {
								$('#appointment-modal .modal-body').children().remove();
								$('#appointment-modal .modal-body').append($("<div></div>", {
									class : "alert-message block-message success"
								}).append($("<p></p>", {
									html : "The appointment was successfully created."
								}).prepend($("<strong></strong>", {
									html : "Success!"
								}))));
								$('#appointment-modal .modal-footer').children().remove();
								$('#appointment-modal .modal-footer').append($("<button></button>", {
									class : "btn success",
									type : "button",
									click : function() {
										window.location.replace(response.location);
									},

									html : "Done"
								}));
							} else {
								alert("Unable to book appointment. An unexpected error occurred. Please try again");
							}
						},

						error : function() {
							alert("An unexpected error occurred");
						}

					});
				});
            } else if(page === "amend-appointment") {
                // We need the same things so call the find appointment initialiser
                fbs.pageInit("find-appointment");
                $(".show-search-criteria").click(function() {
                    if ($(this).hasClass("active")) {
                        $("#find-times").slideUp(400);
                        $(this).toggleClass("active");
                    } else {
                        $("#find-times").slideDown(400);
                        $(this).toggleClass("active");
                    }
                });
                
                $("#find-times .select-time").click(function() {
                    var datetime = new Date($(this).data("datetime") * 1000);
                    
                    // Set the date and time
                    $("#date").val($.datepicker.formatDate('dd-mm-yy', datetime));
                    $("#time").val(datetime.getHours() + ":" + datetime.getMinutes());
                    
                    // Update the member of staff
                    $("#staff").val($(this).parents("div.tab-pane").attr("id"));
                    $("#find-times .search-results").remove();
                    $("#find-times").slideUp(400);
                    $(".show-search-criteria").toggleClass("active");
                    $("#find-times input[name='search_date']").val("");
                    $("#find-times input[name='search_date_from']").val("");
                    $("#find-times input[name='search_date_to']").val("");
                    $("#find-times input[name='search_date']").val("");
                });
                
                $(".add-appt-note").bind('click', function() {
					$newRow = $('<tr></tr>');
					$newCell = $('<td></td>');

					$newRow.append($newCell.clone().append($('<input />', {
						class : 'xxlarge',
						type : 'text',
						name : 'appt_notes[]',
						value : ''
					})));

					$newRow.append($newCell.clone().append($('<button></button>', {
						type : 'button',
						class : 'remove-appt-note btn',
						html : 'Remove',
						click : function() {
							$(this).parents('tr').remove();
						}

					})));

					$newRow.insertBefore($(this).parents("table").find('tbody').find('tr').last());
					return false;
				});
				
				$(".remove-appt-note").click(function() {
				    $(this).parents("tr").remove();
				});
                
			} else if(page === "add-to-waiting-list") {
                fbs.pageInit("find-appointment");
                $(".chzn-select").chosen({no_results_text: "No customer found"});
			}
		} else {
			fbs.options.DEBUG ? console.log("No custom initialisation for this page") : "";
		}
	}

};

$(document).ready(function() {
	// Setup any modal dialog close buttons
	$(".modal-close").click(function() {
		$(this).parents(".modal").modal("hide");
	});

	var modal = $("[data-controls-modal]").attr("data-controls-modal");
	$("#" + modal).data("keyboard", true);
	$("#" + modal).data("show", true);
	$("#" + modal).data("backdrop", true);
	if(fbs.helpers.showModal()) {
		$("#" + modal).modal($("#" + modal).data());
	}

	$(".confirm-action").bind("click", function(e) {
		fbs.helpers.showConfirm($(this));
		return false;
	});


	$("#user-switch").bind("click", function(e) {
		fbs.helpers.switchUsers($(this).siblings("#unique_key").val());
	});


	$("#resume-system").bind("click", function() {
		if($(".lock-login-container #password").length === 0) {
			fbs.helpers.resume($(this).siblings().find("#unique_key").val());
		} else {
			fbs.helpers.resume($(this).siblings().find("#unique_key").val(), $(this).siblings().find("#password").val());
		}
	});

    
    if ($('.alert-message.fadeout').length > 0) {
        var timeout = $('.alert-message.fadeout').data('fade-timeout');
            timeout = timeout === '' ? 1000 : timeout;
        $('.alert-message.fadeout').delay(timeout).fadeOut('slow');
    }
    
	$('.dropdown-menu').find('input').click(function(e) {
		e.stopPropagation();
	});


	$(".date-picker").datepicker(fbs.options.defaultDatepickerOptions);

	fbs.globalInit();
	fbs.options.DEBUG ? console.log("Detected page: " + fbs.helpers.getPage()) : "";
	fbs.pageInit(fbs.helpers.getPage());
});

